hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d637895b07b415a8699927ffec8e3b2f3800f18d | 5,308 | h | C | ecm/include/tencentcloud/ecm/v20190719/model/ListenerBackend.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | ecm/include/tencentcloud/ecm/v20190719/model/ListenerBackend.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | ecm/include/tencentcloud/ecm/v20190719/model/ListenerBackend.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_ECM_V20190719_MODEL_LISTENERBACKEND_H_
#define TENCENTCLOUD_ECM_V20190719_MODEL_LISTENERBACKEND_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ecm/v20190719/model/Backend.h>
namespace TencentCloud
{
namespace Ecm
{
namespace V20190719
{
namespace Model
{
/**
* 监听器后端
*/
class ListenerBackend : public AbstractModel
{
public:
ListenerBackend();
~ListenerBackend() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取监听器 ID
注意:此字段可能返回 null,表示取不到有效值。
* @return ListenerId 监听器 ID
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetListenerId() const;
/**
* 设置监听器 ID
注意:此字段可能返回 null,表示取不到有效值。
* @param ListenerId 监听器 ID
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetListenerId(const std::string& _listenerId);
/**
* 判断参数 ListenerId 是否已赋值
* @return ListenerId 是否已赋值
*/
bool ListenerIdHasBeenSet() const;
/**
* 获取监听器的协议
注意:此字段可能返回 null,表示取不到有效值。
* @return Protocol 监听器的协议
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string GetProtocol() const;
/**
* 设置监听器的协议
注意:此字段可能返回 null,表示取不到有效值。
* @param Protocol 监听器的协议
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetProtocol(const std::string& _protocol);
/**
* 判断参数 Protocol 是否已赋值
* @return Protocol 是否已赋值
*/
bool ProtocolHasBeenSet() const;
/**
* 获取监听器的端口
注意:此字段可能返回 null,表示取不到有效值。
* @return Port 监听器的端口
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t GetPort() const;
/**
* 设置监听器的端口
注意:此字段可能返回 null,表示取不到有效值。
* @param Port 监听器的端口
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetPort(const int64_t& _port);
/**
* 判断参数 Port 是否已赋值
* @return Port 是否已赋值
*/
bool PortHasBeenSet() const;
/**
* 获取监听器上绑定的后端服务列表
注意:此字段可能返回 null,表示取不到有效值。
* @return Targets 监听器上绑定的后端服务列表
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<Backend> GetTargets() const;
/**
* 设置监听器上绑定的后端服务列表
注意:此字段可能返回 null,表示取不到有效值。
* @param Targets 监听器上绑定的后端服务列表
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetTargets(const std::vector<Backend>& _targets);
/**
* 判断参数 Targets 是否已赋值
* @return Targets 是否已赋值
*/
bool TargetsHasBeenSet() const;
private:
/**
* 监听器 ID
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_listenerId;
bool m_listenerIdHasBeenSet;
/**
* 监听器的协议
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_protocol;
bool m_protocolHasBeenSet;
/**
* 监听器的端口
注意:此字段可能返回 null,表示取不到有效值。
*/
int64_t m_port;
bool m_portHasBeenSet;
/**
* 监听器上绑定的后端服务列表
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<Backend> m_targets;
bool m_targetsHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ECM_V20190719_MODEL_LISTENERBACKEND_H_
| 30.331429 | 116 | 0.480972 | [
"vector",
"model"
] |
d6379ddb00e5d865426562d37ab21954bf0c0e79 | 19,598 | h | C | aws-cpp-sdk-pinpoint/include/aws/pinpoint/model/APNSVoipChannelResponse.h | derpferd/aws-sdk-cpp | daf01b788cfe074ffcd788174c0538256afc40e3 | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-pinpoint/include/aws/pinpoint/model/APNSVoipChannelResponse.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-pinpoint/include/aws/pinpoint/model/APNSVoipChannelResponse.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Pinpoint
{
namespace Model
{
/**
* <p>Provides information about the status and settings of the APNs (Apple Push
* Notification service) VoIP channel for an application.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/APNSVoipChannelResponse">AWS
* API Reference</a></p>
*/
class AWS_PINPOINT_API APNSVoipChannelResponse
{
public:
APNSVoipChannelResponse();
APNSVoipChannelResponse(Aws::Utils::Json::JsonView jsonValue);
APNSVoipChannelResponse& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline const Aws::String& GetApplicationId() const{ return m_applicationId; }
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline bool ApplicationIdHasBeenSet() const { return m_applicationIdHasBeenSet; }
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline void SetApplicationId(const Aws::String& value) { m_applicationIdHasBeenSet = true; m_applicationId = value; }
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline void SetApplicationId(Aws::String&& value) { m_applicationIdHasBeenSet = true; m_applicationId = std::move(value); }
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline void SetApplicationId(const char* value) { m_applicationIdHasBeenSet = true; m_applicationId.assign(value); }
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline APNSVoipChannelResponse& WithApplicationId(const Aws::String& value) { SetApplicationId(value); return *this;}
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline APNSVoipChannelResponse& WithApplicationId(Aws::String&& value) { SetApplicationId(std::move(value)); return *this;}
/**
* <p>The unique identifier for the application that the APNs VoIP channel applies
* to.</p>
*/
inline APNSVoipChannelResponse& WithApplicationId(const char* value) { SetApplicationId(value); return *this;}
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline const Aws::String& GetCreationDate() const{ return m_creationDate; }
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline bool CreationDateHasBeenSet() const { return m_creationDateHasBeenSet; }
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline void SetCreationDate(const Aws::String& value) { m_creationDateHasBeenSet = true; m_creationDate = value; }
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline void SetCreationDate(Aws::String&& value) { m_creationDateHasBeenSet = true; m_creationDate = std::move(value); }
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline void SetCreationDate(const char* value) { m_creationDateHasBeenSet = true; m_creationDate.assign(value); }
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline APNSVoipChannelResponse& WithCreationDate(const Aws::String& value) { SetCreationDate(value); return *this;}
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline APNSVoipChannelResponse& WithCreationDate(Aws::String&& value) { SetCreationDate(std::move(value)); return *this;}
/**
* <p>The date and time when the APNs VoIP channel was enabled.</p>
*/
inline APNSVoipChannelResponse& WithCreationDate(const char* value) { SetCreationDate(value); return *this;}
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline const Aws::String& GetDefaultAuthenticationMethod() const{ return m_defaultAuthenticationMethod; }
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline bool DefaultAuthenticationMethodHasBeenSet() const { return m_defaultAuthenticationMethodHasBeenSet; }
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline void SetDefaultAuthenticationMethod(const Aws::String& value) { m_defaultAuthenticationMethodHasBeenSet = true; m_defaultAuthenticationMethod = value; }
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline void SetDefaultAuthenticationMethod(Aws::String&& value) { m_defaultAuthenticationMethodHasBeenSet = true; m_defaultAuthenticationMethod = std::move(value); }
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline void SetDefaultAuthenticationMethod(const char* value) { m_defaultAuthenticationMethodHasBeenSet = true; m_defaultAuthenticationMethod.assign(value); }
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline APNSVoipChannelResponse& WithDefaultAuthenticationMethod(const Aws::String& value) { SetDefaultAuthenticationMethod(value); return *this;}
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline APNSVoipChannelResponse& WithDefaultAuthenticationMethod(Aws::String&& value) { SetDefaultAuthenticationMethod(std::move(value)); return *this;}
/**
* <p>The default authentication method that Amazon Pinpoint uses to authenticate
* with APNs for this channel, key or certificate.</p>
*/
inline APNSVoipChannelResponse& WithDefaultAuthenticationMethod(const char* value) { SetDefaultAuthenticationMethod(value); return *this;}
/**
* <p>Specifies whether the APNs VoIP channel is enabled for the application.</p>
*/
inline bool GetEnabled() const{ return m_enabled; }
/**
* <p>Specifies whether the APNs VoIP channel is enabled for the application.</p>
*/
inline bool EnabledHasBeenSet() const { return m_enabledHasBeenSet; }
/**
* <p>Specifies whether the APNs VoIP channel is enabled for the application.</p>
*/
inline void SetEnabled(bool value) { m_enabledHasBeenSet = true; m_enabled = value; }
/**
* <p>Specifies whether the APNs VoIP channel is enabled for the application.</p>
*/
inline APNSVoipChannelResponse& WithEnabled(bool value) { SetEnabled(value); return *this;}
/**
* <p>(Not used) This property is retained only for backward compatibility.</p>
*/
inline bool GetHasCredential() const{ return m_hasCredential; }
/**
* <p>(Not used) This property is retained only for backward compatibility.</p>
*/
inline bool HasCredentialHasBeenSet() const { return m_hasCredentialHasBeenSet; }
/**
* <p>(Not used) This property is retained only for backward compatibility.</p>
*/
inline void SetHasCredential(bool value) { m_hasCredentialHasBeenSet = true; m_hasCredential = value; }
/**
* <p>(Not used) This property is retained only for backward compatibility.</p>
*/
inline APNSVoipChannelResponse& WithHasCredential(bool value) { SetHasCredential(value); return *this;}
/**
* <p>Specifies whether the APNs VoIP channel is configured to communicate with
* APNs by using APNs tokens. To provide an authentication key for APNs tokens, set
* the TokenKey property of the channel.</p>
*/
inline bool GetHasTokenKey() const{ return m_hasTokenKey; }
/**
* <p>Specifies whether the APNs VoIP channel is configured to communicate with
* APNs by using APNs tokens. To provide an authentication key for APNs tokens, set
* the TokenKey property of the channel.</p>
*/
inline bool HasTokenKeyHasBeenSet() const { return m_hasTokenKeyHasBeenSet; }
/**
* <p>Specifies whether the APNs VoIP channel is configured to communicate with
* APNs by using APNs tokens. To provide an authentication key for APNs tokens, set
* the TokenKey property of the channel.</p>
*/
inline void SetHasTokenKey(bool value) { m_hasTokenKeyHasBeenSet = true; m_hasTokenKey = value; }
/**
* <p>Specifies whether the APNs VoIP channel is configured to communicate with
* APNs by using APNs tokens. To provide an authentication key for APNs tokens, set
* the TokenKey property of the channel.</p>
*/
inline APNSVoipChannelResponse& WithHasTokenKey(bool value) { SetHasTokenKey(value); return *this;}
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline const Aws::String& GetId() const{ return m_id; }
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline bool IdHasBeenSet() const { return m_idHasBeenSet; }
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; }
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); }
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); }
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline APNSVoipChannelResponse& WithId(const Aws::String& value) { SetId(value); return *this;}
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline APNSVoipChannelResponse& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}
/**
* <p>(Deprecated) An identifier for the APNs VoIP channel. This property is
* retained only for backward compatibility.</p>
*/
inline APNSVoipChannelResponse& WithId(const char* value) { SetId(value); return *this;}
/**
* <p>Specifies whether the APNs VoIP channel is archived.</p>
*/
inline bool GetIsArchived() const{ return m_isArchived; }
/**
* <p>Specifies whether the APNs VoIP channel is archived.</p>
*/
inline bool IsArchivedHasBeenSet() const { return m_isArchivedHasBeenSet; }
/**
* <p>Specifies whether the APNs VoIP channel is archived.</p>
*/
inline void SetIsArchived(bool value) { m_isArchivedHasBeenSet = true; m_isArchived = value; }
/**
* <p>Specifies whether the APNs VoIP channel is archived.</p>
*/
inline APNSVoipChannelResponse& WithIsArchived(bool value) { SetIsArchived(value); return *this;}
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline const Aws::String& GetLastModifiedBy() const{ return m_lastModifiedBy; }
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline bool LastModifiedByHasBeenSet() const { return m_lastModifiedByHasBeenSet; }
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline void SetLastModifiedBy(const Aws::String& value) { m_lastModifiedByHasBeenSet = true; m_lastModifiedBy = value; }
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline void SetLastModifiedBy(Aws::String&& value) { m_lastModifiedByHasBeenSet = true; m_lastModifiedBy = std::move(value); }
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline void SetLastModifiedBy(const char* value) { m_lastModifiedByHasBeenSet = true; m_lastModifiedBy.assign(value); }
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline APNSVoipChannelResponse& WithLastModifiedBy(const Aws::String& value) { SetLastModifiedBy(value); return *this;}
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline APNSVoipChannelResponse& WithLastModifiedBy(Aws::String&& value) { SetLastModifiedBy(std::move(value)); return *this;}
/**
* <p>The user who last modified the APNs VoIP channel.</p>
*/
inline APNSVoipChannelResponse& WithLastModifiedBy(const char* value) { SetLastModifiedBy(value); return *this;}
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline const Aws::String& GetLastModifiedDate() const{ return m_lastModifiedDate; }
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline bool LastModifiedDateHasBeenSet() const { return m_lastModifiedDateHasBeenSet; }
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline void SetLastModifiedDate(const Aws::String& value) { m_lastModifiedDateHasBeenSet = true; m_lastModifiedDate = value; }
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline void SetLastModifiedDate(Aws::String&& value) { m_lastModifiedDateHasBeenSet = true; m_lastModifiedDate = std::move(value); }
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline void SetLastModifiedDate(const char* value) { m_lastModifiedDateHasBeenSet = true; m_lastModifiedDate.assign(value); }
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline APNSVoipChannelResponse& WithLastModifiedDate(const Aws::String& value) { SetLastModifiedDate(value); return *this;}
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline APNSVoipChannelResponse& WithLastModifiedDate(Aws::String&& value) { SetLastModifiedDate(std::move(value)); return *this;}
/**
* <p>The date and time when the APNs VoIP channel was last modified.</p>
*/
inline APNSVoipChannelResponse& WithLastModifiedDate(const char* value) { SetLastModifiedDate(value); return *this;}
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline const Aws::String& GetPlatform() const{ return m_platform; }
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline bool PlatformHasBeenSet() const { return m_platformHasBeenSet; }
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline void SetPlatform(const Aws::String& value) { m_platformHasBeenSet = true; m_platform = value; }
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline void SetPlatform(Aws::String&& value) { m_platformHasBeenSet = true; m_platform = std::move(value); }
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline void SetPlatform(const char* value) { m_platformHasBeenSet = true; m_platform.assign(value); }
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline APNSVoipChannelResponse& WithPlatform(const Aws::String& value) { SetPlatform(value); return *this;}
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline APNSVoipChannelResponse& WithPlatform(Aws::String&& value) { SetPlatform(std::move(value)); return *this;}
/**
* <p>The type of messaging or notification platform for the channel. For the APNs
* VoIP channel, this value is APNS_VOIP.</p>
*/
inline APNSVoipChannelResponse& WithPlatform(const char* value) { SetPlatform(value); return *this;}
/**
* <p>The current version of the APNs VoIP channel.</p>
*/
inline int GetVersion() const{ return m_version; }
/**
* <p>The current version of the APNs VoIP channel.</p>
*/
inline bool VersionHasBeenSet() const { return m_versionHasBeenSet; }
/**
* <p>The current version of the APNs VoIP channel.</p>
*/
inline void SetVersion(int value) { m_versionHasBeenSet = true; m_version = value; }
/**
* <p>The current version of the APNs VoIP channel.</p>
*/
inline APNSVoipChannelResponse& WithVersion(int value) { SetVersion(value); return *this;}
private:
Aws::String m_applicationId;
bool m_applicationIdHasBeenSet;
Aws::String m_creationDate;
bool m_creationDateHasBeenSet;
Aws::String m_defaultAuthenticationMethod;
bool m_defaultAuthenticationMethodHasBeenSet;
bool m_enabled;
bool m_enabledHasBeenSet;
bool m_hasCredential;
bool m_hasCredentialHasBeenSet;
bool m_hasTokenKey;
bool m_hasTokenKeyHasBeenSet;
Aws::String m_id;
bool m_idHasBeenSet;
bool m_isArchived;
bool m_isArchivedHasBeenSet;
Aws::String m_lastModifiedBy;
bool m_lastModifiedByHasBeenSet;
Aws::String m_lastModifiedDate;
bool m_lastModifiedDateHasBeenSet;
Aws::String m_platform;
bool m_platformHasBeenSet;
int m_version;
bool m_versionHasBeenSet;
};
} // namespace Model
} // namespace Pinpoint
} // namespace Aws
| 37.329524 | 169 | 0.687519 | [
"model"
] |
d639a5d3a411243b30df80d7a940d0c1730fc7b6 | 13,938 | h | C | third_party/crashpad/crashpad/snapshot/mac/mach_o_image_segment_reader.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/crashpad/crashpad/snapshot/mac/mach_o_image_segment_reader.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/crashpad/crashpad/snapshot/mac/mach_o_image_segment_reader.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_SNAPSHOT_MAC_MACH_O_IMAGE_SEGMENT_READER_H_
#define CRASHPAD_SNAPSHOT_MAC_MACH_O_IMAGE_SEGMENT_READER_H_
#include <mach/mach.h>
#include <stdint.h>
#include <sys/types.h>
#include <map>
#include <string>
#include <vector>
#include "snapshot/mac/process_types.h"
#include "util/misc/initialization_state_dcheck.h"
namespace crashpad {
//! \brief Determines whether a module appears to be a malformed OpenCL
//! `cl_kernels` module based on its name and Mach-O file type.
//!
//! `cl_kernels` modules require special handling because they’re malformed on
//! OS X 10.10 and later. A `cl_kernels` module always has Mach-O type
//! `MH_BUNDLE` and is named `"cl_kernels"` until macOS 10.14, and
//! `"/private/var/db/CVMS/cvmsCodeSignObj"` plus 16 random characters on macOS
//! 10.14.
//!
//! Malformed `cl_kernels` modules have a single `__TEXT` segment, but one of
//! the sections within it claims to belong to the `__LD` segment. This mismatch
//! shouldn’t happen. This errant section also has the `S_ATTR_DEBUG` flag set,
//! which shouldn’t happen unless all of the other sections in the segment also
//! have this bit set (they don’t). These odd sections are reminiscent of unwind
//! information stored in `MH_OBJECT` images, although `cl_kernels` images claim
//! to be `MH_BUNDLE`.
//!
//! These `cl_kernels` modules have only been observed on x86, not on arm64.
//! This function always returns `false` on arm64.
//!
//! This function is exposed for testing purposes only.
//!
//! \param[in] mach_o_file_type The Mach-O type of the module being examined.
//! \param[in] module_name The pathname that `dyld` reported having loaded the
//! module from.
//! \param[out] has_timestamp Optional, may be `nullptr`. If provided, and the
//! module is a maformed `cl_kernels` module, this will be set to `true` if
//! the module was loaded from the filesystem (as is the case when loaded
//! from the CVMS directory) and is expected to have a timestamp, and
//! `false` otherwise. Note that even when loaded from the filesystem, these
//! modules are unlinked from the filesystem after loading.
//!
//! \return `true` if the module appears to be a malformed `cl_kernels` module
//! based on the provided information, `false` otherwise.
bool IsMalformedCLKernelsModule(uint32_t mach_o_file_type,
const std::string& module_name,
bool* has_timestamp);
//! \brief A reader for `LC_SEGMENT` or `LC_SEGMENT_64` load commands in Mach-O
//! images mapped into another process.
//!
//! This class is capable of reading both `LC_SEGMENT` and `LC_SEGMENT_64` based
//! on the bitness of the remote process.
//!
//! A MachOImageSegmentReader will normally be instantiated by a
//! MachOImageReader.
class MachOImageSegmentReader {
public:
MachOImageSegmentReader();
MachOImageSegmentReader(const MachOImageSegmentReader&) = delete;
MachOImageSegmentReader& operator=(const MachOImageSegmentReader&) = delete;
~MachOImageSegmentReader();
//! \brief Reads the segment load command from another process.
//!
//! This method must only be called once on an object. This method must be
//! called successfully before any other method in this class may be called.
//!
//! \param[in] process_reader The reader for the remote process.
//! \param[in] load_command_address The address, in the remote process’
//! address space, where the `LC_SEGMENT` or `LC_SEGMENT_64` load command
//! to be read is located. This address is determined by a Mach-O image
//! reader, such as MachOImageReader, as it walks Mach-O load commands.
//! \param[in] load_command_info A string to be used in logged messages. This
//! string is for diagnostic purposes only, and may be empty.
//! \param[in] module_name The path used to load the module. This string is
//! used to relax otherwise strict parsing rules for common modules with
//! known defects.
//! \param[in] file_type The module’s Mach-O file type. This is used to relax
//! otherwise strict parsing rules for common modules with known defects.
//!
//! \return `true` if the load command was read successfully. `false`
//! otherwise, with an appropriate message logged.
bool Initialize(ProcessReaderMac* process_reader,
mach_vm_address_t load_command_address,
const std::string& load_command_info,
const std::string& module_name,
uint32_t file_type);
//! \brief Sets the image’s slide value.
//!
//! This method must only be called once on an object, after Initialize() is
//! called successfully. It must be called before Address(), Size(),
//! GetSectionByName(), or GetSectionAtIndex() can be called.
//!
//! This method is provided because slide is a property of the image that
//! cannot be determined until at least some segments have been read. As such,
//! it is not necessarily known at the time that Initialize() is called.
void SetSlide(mach_vm_size_t slide);
//! \brief Returns the segment’s name.
//!
//! The segment’s name is taken from the load command’s `segname` field.
//! Common segment names are `"__TEXT"`, `"__DATA"`, and `"__LINKEDIT"`.
//! Symbolic constants for these common names are defined in
//! `<mach-o/loader.h>`.
std::string Name() const;
//! \return The segment’s actual load address in memory, adjusted for any
//! “slide”.
//!
//! \note For the segment’s preferred load address, not adjusted for slide,
//! use vmaddr().
mach_vm_address_t Address() const;
//! \return The segment’s actual size address in memory, adjusted for any
//! growth in the case of a nonsliding segment.
//!
//! \note For the segment’s preferred size, not adjusted for growth, use
//! vmsize().
mach_vm_address_t Size() const;
//! \brief The segment’s preferred load address.
//!
//! \return The segment’s preferred load address as stored in the Mach-O file.
//!
//! \note This value is not adjusted for any “slide” that may have occurred
//! when the image was loaded. Use Address() for a value adjusted for
//! slide.
//!
//! \sa MachOImageReader::GetSegmentByName()
mach_vm_address_t vmaddr() const { return segment_command_.vmaddr; }
//! \brief Returns the segment’s size as mapped into memory.
//!
//! \note For non-sliding segments, this value is not adjusted for any growth
//! that may have occurred when the image was loaded. Use Size() for a
//! value adjusted for growth.
mach_vm_size_t vmsize() const { return segment_command_.vmsize; }
//! \brief Returns the file offset of the mapped segment in the file from
//! which it was mapped.
//!
//! The file offset is the difference between the beginning of the
//! `mach_header` or `mach_header_64` and the beginning of the segment’s
//! mapped region. For segments that are not mapped from a file (such as
//! `__PAGEZERO` segments), this will be `0`.
mach_vm_size_t fileoff() const { return segment_command_.fileoff; }
//! \brief Returns the number of sections in the segment.
//!
//! This will return `0` for a segment without any sections, typical for
//! `__PAGEZERO` and `__LINKEDIT` segments.
//!
//! Although the Mach-O file format uses a `uint32_t` for this field, there is
//! an overall limit of 255 sections in an entire Mach-O image file (not just
//! in a single segment) imposed by the symbol table format. Symbols will not
//! be able to reference anything in a section beyond the first 255 in a
//! Mach-O image file.
uint32_t nsects() const { return segment_command_.nsects; }
//! \brief Obtain section information by section name.
//!
//! \param[in] section_name The name of the section to search for, without the
//! leading segment name. For example, use `"__text"`, not
//! `"__TEXT,__text"` or `"__TEXT.__text"`.
//! \param[out] address The actual address that the section was loaded at in
//! memory, taking any “slide” into account if the section did not load at
//! its preferred address as stored in the Mach-O image file. This
//! parameter can be `nullptr`.
//!
//! \return A pointer to the section information if it was found, or `nullptr`
//! if it was not found. The caller does not take ownership; the lifetime
//! of the returned object is scoped to the lifetime of this
//! MachOImageSegmentReader object.
//!
//! \note The process_types::section::addr field gives the section’s preferred
//! load address as stored in the Mach-O image file, and is not adjusted
//! for any “slide” that may have occurred when the image was loaded.
//!
//! \sa MachOImageReader::GetSectionByName()
const process_types::section* GetSectionByName(
const std::string& section_name,
mach_vm_address_t* address) const;
//! \brief Obtain section information by section index.
//!
//! \param[in] index The index of the section to return, in the order that it
//! appears in the segment load command. Unlike
//! MachOImageReader::GetSectionAtIndex(), this is a 0-based index. This
//! parameter must be in the range of valid indices aas reported by
//! nsects().
//! \param[out] address The actual address that the section was loaded at in
//! memory, taking any “slide” into account if the section did not load at
//! its preferred address as stored in the Mach-O image file. This
//! parameter can be `nullptr`.
//!
//! \return A pointer to the section information. If \a index is out of range,
//! execution is aborted. The caller does not take ownership; the
//! lifetime of the returned object is scoped to the lifetime of this
//! MachOImageSegmentReader object.
//!
//! \note The process_types::section::addr field gives the section’s preferred
//! load address as stored in the Mach-O image file, and is not adjusted
//! for any “slide” that may have occurred when the image was loaded.
//! \note Unlike MachOImageReader::GetSectionAtIndex(), this method does not
//! accept out-of-range values for \a index, and aborts execution instead
//! of returning `nullptr` upon encountering an out-of-range value. This
//! is because this method is expected to be used in a loop that can be
//! limited to nsects() iterations, so an out-of-range error can be
//! treated more harshly as a logic error, as opposed to a data error.
//!
//! \sa MachOImageReader::GetSectionAtIndex()
const process_types::section* GetSectionAtIndex(
size_t index,
mach_vm_address_t* address) const;
//! Returns whether the segment slides.
//!
//! Most segments slide, but the `__PAGEZERO` segment does not, it grows
//! instead. This method identifies non-sliding segments in the same way that
//! the kernel does.
bool SegmentSlides() const;
//! \brief Returns a segment name string.
//!
//! Segment names may be 16 characters long, and are not necessarily
//! `NUL`-terminated. This function will return a segment name based on up to
//! the first 16 characters found at \a segment_name_c.
static std::string SegmentNameString(const char* segment_name_c);
//! \brief Returns a section name string.
//!
//! Section names may be 16 characters long, and are not necessarily
//! `NUL`-terminated. This function will return a section name based on up to
//! the first 16 characters found at \a section_name_c.
static std::string SectionNameString(const char* section_name_c);
//! \brief Returns a segment and section name string.
//!
//! A segment and section name string is composed of a segment name string
//! (see SegmentNameString()) and a section name string (see
//! SectionNameString()) separated by a comma. An example is
//! `"__TEXT,__text"`.
static std::string SegmentAndSectionNameString(const char* segment_name_c,
const char* section_name_c);
private:
//! \brief The internal implementation of Name().
//!
//! This is identical to Name() but does not perform the
//! InitializationStateDcheck check. It may be called during initialization
//! provided that the caller only does so after segment_command_ has been
//! read successfully.
std::string NameInternal() const;
// The segment command data read from the remote process.
process_types::segment_command segment_command_;
// Section structures read from the remote process in the order that they are
// given in the remote process.
std::vector<process_types::section> sections_;
// Maps section names to indices into the sections_ vector.
std::map<std::string, size_t> section_map_;
// The image’s slide. Note that the segment’s slide may be 0 and not the value
// of the image’s slide if SegmentSlides() is false. In that case, the
// segment is extended instead of slid, so its size as loaded will be
// increased by this value.
mach_vm_size_t slide_;
InitializationStateDcheck initialized_;
InitializationStateDcheck initialized_slide_;
};
} // namespace crashpad
#endif // CRASHPAD_SNAPSHOT_MAC_MACH_O_IMAGE_SEGMENT_READER_H_
| 46.152318 | 80 | 0.703257 | [
"object",
"vector"
] |
d63a65620371157f00ba5c99ea7c3e90a8c14af1 | 30,926 | h | C | src/utils.h | Himujjal/tree-sitter-html | 2bc426b0d5bccbbaa9631f2da962054a48e6de93 | [
"MIT"
] | null | null | null | src/utils.h | Himujjal/tree-sitter-html | 2bc426b0d5bccbbaa9631f2da962054a48e6de93 | [
"MIT"
] | null | null | null | src/utils.h | Himujjal/tree-sitter-html | 2bc426b0d5bccbbaa9631f2da962054a48e6de93 | [
"MIT"
] | null | null | null | /**
* ------- UTILS CONTENTS --------
* 67 - 318 -> allocator
* 320 - 474 -> vc_vector
* 476 - 527 -> ekstring
* 529 - 746 -> tags
* 748 - 1216 -> hashmap
* -------------------------------
* */
#ifndef UTILS_H
#define UTILS_H
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#if defined(_MSC_VER)
// Workaround a bug in the MSVC runtime where it uses __cplusplus when not
// defined.
#pragma warning(push, 0)
#pragma warning(disable : 4668)
#endif
#if (defined(_MSC_VER) && defined(__AVX__)) || \
(!defined(_MSC_VER) && defined(__SSE4_2__))
#define HASHMAP_SSE42
#endif
#if defined(HASHMAP_SSE42)
#include <nmmintrin.h>
#endif
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#if defined(_MSC_VER)
#pragma warning(push)
/* Stop MSVC complaining about unreferenced functions */
#pragma warning(disable : 4505)
/* Stop MSVC complaining about not inlining functions */
#pragma warning(disable : 4710)
/* Stop MSVC complaining about inlining functions! */
#pragma warning(disable : 4711)
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#endif
#if defined(_MSC_VER)
#define HASHMAP_USED
#elif defined(__GNUC__)
#define HASHMAP_USED __attribute__((used))
#else
#define HASHMAP_USED
#endif
#if defined(__cplusplus)
#define HASHMAP_CAST(type, x) static_cast<type>(x)
#define HASHMAP_PTR_CAST(type, x) reinterpret_cast<type>(x)
#define HASHMAP_NULL NULL
#else
#define HASHMAP_CAST(type, x) ((type)x)
#define HASHMAP_PTR_CAST(type, x) ((type)x)
#define HASHMAP_NULL 0
#endif
// ------------------- ALLOCATOR ----------------------
// 默认每次内存翻倍
#ifndef za_Delta
#define za_Delta 2
#endif
#ifndef za_INIT_SIZE
#define za_INIT_SIZE (1024 * 128)
#endif
#ifndef za_BIN_LEVEL
#define za_BIN_LEVEL 5
#endif
#ifndef za_BIN_LEVEL_SIZE
#define za_BIN_LEVEL_SIZE 16
#endif
#ifndef za_BIN_MIN_CHUNK
#define za_BIN_MIN_CHUNK 8
#endif
#if defined(__GNUC__) || defined(__clang__)
#define za_LIKELY(x) __builtin_expect(x, 1)
#define za_UNLIKELY(x) __builtin_expect(x, 0)
#else
#define za_LIKELY(x) x
#define za_UNLIKELY(x) x
#endif
// 内存基本单元链表
typedef struct za_binNode {
void *Ptr;
struct za_binNode *Next;
} za_binNode;
typedef struct za_bin {
size_t ChunkSize;
za_binNode *Head;
za_binNode *FreeHead;
} za_bin;
// 内存分配器的节点
typedef struct za_allocatorNode {
void *Data;
size_t Pos;
size_t Size;
struct za_allocatorNode *Next;
} za_allocatorNode;
// 内存分配器
typedef struct za_Allocator {
za_allocatorNode *Head;
za_allocatorNode *End;
za_bin Bins[za_BIN_LEVEL * za_BIN_LEVEL_SIZE];
size_t LevelMins[za_BIN_LEVEL];
size_t LevelMaxs[za_BIN_LEVEL];
#ifdef za_ALLOCTOR_DEBUG
size_t AllocSize;
size_t FreeSize;
#endif
} za_Allocator;
static inline void *za_innerNew(size_t size);
static inline void za_innerFree(void *pointer);
// 新建一个Allocator
static inline za_Allocator *za_New() {
// 分配大块内存
void *ptr = za_innerNew(sizeof(za_Allocator) + sizeof(za_allocatorNode) +
za_INIT_SIZE);
if (za_UNLIKELY(ptr == 0))
return 0;
za_Allocator *allocator = (za_Allocator *)ptr;
allocator->Head = (za_allocatorNode *)((char *)ptr + sizeof(za_Allocator));
allocator->End = allocator->Head;
#ifdef za_ALLOCTOR_DEBUG
allocator->AllocSize = 0;
allocator->FreeSize = 0;
#endif
memset(allocator->Bins, 0, sizeof(allocator->Bins));
size_t chunk_size = za_BIN_MIN_CHUNK;
for (size_t i = 0; i < za_BIN_LEVEL; ++i) {
allocator->LevelMins[i] = chunk_size;
for (size_t j = 0; j < za_BIN_LEVEL_SIZE;) {
za_bin *b = allocator->Bins + i * za_BIN_LEVEL_SIZE + j;
b->Head = 0;
b->ChunkSize = chunk_size * (++j);
}
allocator->LevelMaxs[i] = chunk_size * za_BIN_LEVEL_SIZE;
chunk_size = chunk_size * za_BIN_LEVEL_SIZE * 2;
}
allocator->Head->Size = za_INIT_SIZE;
allocator->Head->Data =
(char *)ptr + sizeof(za_Allocator) + sizeof(za_allocatorNode);
allocator->Head->Pos = 0;
allocator->Head->Next = 0;
return allocator;
}
// 释放一个Allocator
static inline void za_Release(za_Allocator *allocator) {
// 遍历整个链表,每次释放一块内存
za_allocatorNode *next = allocator->Head->Next;
while (za_LIKELY(next != 0)) {
za_allocatorNode *nn = next->Next;
za_innerFree((void *)next);
next = nn;
}
// 最后释放第一块内存
za_innerFree((void *)allocator);
}
static inline za_bin *za_findBin(za_Allocator *allocator, size_t size);
static inline void *za_alloc(za_Allocator *allocator, size_t size);
static inline void za_Free(za_Allocator *allocator, void *ptr);
// 分配内存
static inline void *za_Alloc(za_Allocator *allocator, size_t size) {
if (za_UNLIKELY(size == 0))
return 0;
za_bin *bin = za_findBin(allocator, size);
size_t *s;
if (za_UNLIKELY(bin == 0)) {
s = (size_t *)za_innerNew(sizeof(size_t) + size);
if (za_UNLIKELY(s == 0))
return 0;
*s = size;
#ifdef za_ALLOCTOR_DEBUG
allocator->AllocSize += size;
#endif
return (void *)(s + 1);
}
if (bin->Head != 0) {
s = (size_t *)bin->Head->Ptr;
*s = size;
za_binNode *bn = bin->Head;
bin->Head = bin->Head->Next;
bn->Next = bin->FreeHead;
bin->FreeHead = bn;
#ifdef za_ALLOCTOR_DEBUG
allocator->AllocSize += size;
#endif
return (void *)(s + 1);
}
s = (size_t *)za_alloc(allocator, sizeof(size_t) + bin->ChunkSize);
if (za_UNLIKELY(s == 0))
return 0;
*s = size;
#ifdef za_ALLOCTOR_DEBUG
allocator->AllocSize += size;
#endif
return (void *)(s + 1);
}
static inline void *za_ReAlloc(za_Allocator *allocator, void *addr,
size_t size) {
void *ret = za_Alloc(allocator, size);
size_t *addr_size = (size_t *)addr - 1;
if (za_UNLIKELY(*addr_size > size)) {
memcpy(ret, addr, size);
} else {
memcpy(ret, addr, *addr_size);
}
za_Free(allocator, addr);
return ret;
}
// 释放内存
static inline void za_Free(za_Allocator *allocator, void *ptr) {
size_t *s = (size_t *)ptr - 1;
if (za_UNLIKELY(*s == 0))
return;
#ifdef za_ALLOCTOR_DEBUG
allocator->FreeSize += *s;
#endif
za_bin *bin = za_findBin(allocator, *s);
if (za_UNLIKELY(bin == 0)) {
za_innerFree(s);
return;
}
*s = 0;
za_binNode *bn;
if (bin->FreeHead != 0) {
bn = bin->FreeHead;
bin->FreeHead = bin->FreeHead->Next;
} else {
bn = (za_binNode *)za_alloc(allocator, sizeof(za_binNode));
if (za_UNLIKELY(bn == 0)) {
return;
}
}
bn->Ptr = (void *)s;
bn->Next = bin->Head;
bin->Head = bn;
return;
}
// 找到合适的Bin
static inline za_bin *za_findBin(za_Allocator *allocator, size_t size) {
for (size_t i = 0; i < za_BIN_LEVEL; ++i) {
if (za_LIKELY(size <= allocator->LevelMaxs[i])) {
return allocator->Bins + ((size - 1) / allocator->LevelMins[i]) +
za_BIN_LEVEL_SIZE * i;
}
}
return 0;
}
// 追加一个Allocator
static inline bool za_appendChild(size_t init_size,
struct za_Allocator *allocator) {
// 每次分配一大块内存,避免多次分配
void *ptr = za_innerNew(sizeof(za_allocatorNode) + init_size);
if (za_UNLIKELY(ptr == 0))
return false;
za_allocatorNode *node = (za_allocatorNode *)ptr;
node->Size = init_size;
node->Data = (char *)ptr + sizeof(za_allocatorNode);
node->Pos = 0;
node->Next = 0;
// 在ANode组成的链表最后加一个ANode
allocator->End->Next = node;
allocator->End = node;
return true;
}
// 分配大小为size的内存
static inline void *za_alloc(za_Allocator *allocator, size_t size) {
za_allocatorNode *cur_node = allocator->End;
size_t s = cur_node->Size;
if (za_UNLIKELY(cur_node->Pos + size > s)) {
s *= za_Delta;
// 通过循环计算最终需要的空间大小
// 这里应该有更好的方法,就是直接通过计算所得
while (za_UNLIKELY(size > s))
s *= za_Delta; // 每次分配内存的大小是上次的za_Delta倍
if (za_UNLIKELY(za_appendChild(s, allocator) == false))
return 0;
cur_node = allocator->End;
}
void *ret = (char *)(cur_node->Data) + cur_node->Pos;
cur_node->Pos += size;
return ret;
}
static inline void *za_innerNew(size_t size) { return malloc(size); }
static inline void za_innerFree(void *pointer) { free(pointer); }
// ---------------------------------------------------
// ------------------ VECTORS ------------------------
#define GROWTH_FACTOR 1.5
#define DEFAULT_COUNT_OF_ELEMENTS 8
#define MINIMUM_COUNT_OF_ELEMENTS 2
// vc_vector structure
typedef void(vc_vector_deleter)(void *, za_Allocator *);
typedef struct vc_vector {
size_t count;
size_t element_size;
size_t reserved_size;
char *data;
vc_vector_deleter *deleter;
za_Allocator *A;
} vc_vector;
// Constructs an empty vector with an reserver size for count_elements.
vc_vector *vc_vector_create(za_Allocator *A, size_t count_elements,
size_t size_of_element,
vc_vector_deleter *deleter) {
vc_vector *v = (vc_vector *)za_Alloc(A, sizeof(vc_vector));
if (count_elements < MINIMUM_COUNT_OF_ELEMENTS) {
count_elements = DEFAULT_COUNT_OF_ELEMENTS;
}
if (v != NULL) {
v->data = za_Alloc(A, size_of_element * count_elements);
v->count = 0;
v->element_size = size_of_element;
v->deleter = deleter;
v->A = A;
v->reserved_size = count_elements * size_of_element;
}
return v;
}
void *vc_vector_at(vc_vector *vector, size_t index) {
return vector->data + index * vector->element_size;
}
size_t vc_vector_count(const vc_vector *vector) { return vector->count; }
// [first_index, last_index)
void vc_vector_call_deleter(vc_vector *vector, size_t first_index,
size_t last_index) {
for (size_t i = first_index; i < last_index; ++i) {
vector->deleter(vc_vector_at(vector, i), vector->A);
}
}
// delete all data
void vc_vector_call_deleter_all(vc_vector *vector) {
vc_vector_call_deleter(vector, 0, vc_vector_count(vector));
}
// clear all data
void vc_vector_clear(vc_vector *vector) {
if (vector->deleter != NULL) {
vc_vector_call_deleter_all(vector);
}
vector->count = 0;
}
// Returns the last item in the vector.
void *vc_vector_back(vc_vector *vector) {
return vector->data + (vector->count - 1) * vector->element_size;
}
bool vc_vector_realloc(vc_vector *vector, size_t new_count) {
const size_t new_size = new_count * vector->element_size;
char *new_data = (char *)za_ReAlloc(vector->A, vector->data, new_size);
if (!new_data) {
return false;
}
vector->reserved_size = new_size;
vector->data = new_data;
return true;
}
bool vc_vector_resize(vc_vector *vector, size_t new_count, void *defaultValue) {
// trim or append elements, provide strong guarantee
const size_t old_count = vector->count;
if (new_count == old_count)
return true;
if (new_count < old_count) { // trim
for (int i = new_count; i < old_count; i++)
vector->deleter(vc_vector_at(vector, i), vector->A);
return true;
}
// new_count > old_count
const size_t old_capacity = vector->reserved_size;
if (new_count > old_capacity) { // reallocate
vc_vector_realloc(vector, new_count);
}
for (int i = old_count; i < new_count; i++)
memcpy(vector->data + i, defaultValue, vector->element_size);
vector->count = new_count;
return true;
}
size_t vc_vector_max_count(const vc_vector *vector) {
return vector->reserved_size / vector->element_size;
}
bool vc_vector_append(vc_vector *vector, const void *values, size_t count) {
/* #define GROWTH_FACTOR 1.5 */
const size_t count_new = count + vc_vector_count(vector);
if (vc_vector_max_count(vector) < count_new) {
size_t max_count_to_reserved = vc_vector_max_count(vector) * GROWTH_FACTOR;
while (count_new > max_count_to_reserved) {
max_count_to_reserved *= GROWTH_FACTOR;
}
if (!vc_vector_realloc(vector, max_count_to_reserved)) {
return false;
}
}
if (memcpy(vector->data + vector->count * vector->element_size, values,
vector->element_size * count) == NULL) {
return false;
}
vector->count = count_new;
return true;
}
bool vc_vector_push_back(vc_vector *vector, const void *value) {
if (!vc_vector_append(vector, value, 1)) {
return false;
}
return true;
}
bool vc_vector_pop_back(vc_vector *vector) {
if (vector->deleter != NULL) {
vector->deleter(vc_vector_back(vector), vector->A);
}
vector->count--;
return true;
}
// ----------------------------------------------------------
// ----------------------- String ---------------------------
typedef struct {
const char *buf;
size_t length;
za_Allocator *A;
} ekstring;
#define NaS(x) ((ekstring){NULL, 0, (x)})
const ekstring init_string_str(za_Allocator *A, const char *buf,
size_t length) {
char *s = (char *)za_Alloc(A, sizeof(char) * (length + 1));
strncpy(s, buf, length);
s[length] = '\0';
return (const ekstring){s, length, A};
}
const ekstring init_string_string(const ekstring str) {
za_Allocator *A = str.A;
char *s = (char *)za_Alloc(A, (str.length + 1) * sizeof(char));
strncpy(s, str.buf, str.length + 1);
return (const ekstring){s, str.length, A};
}
bool compare_string_string(const ekstring s1, const ekstring s2) {
if (s1.length == s2.length)
return strncmp(s1.buf, s2.buf, s1.length) == 0;
return false;
}
const ekstring concat_string_string(const ekstring s1, const ekstring s2) {
const size_t length = s1.length + s2.length + 1;
char *s = (char *)za_Alloc(s1.A, length);
strncpy(s, s1.buf, s1.length);
strncpy(s + s1.length, s2.buf, s2.length);
s[length] = '\0';
return (const ekstring){s, length - 1, s1.A};
}
const ekstring concat_string_char(const ekstring s1, const char c) {
if (s1.buf == NULL) {
char *s = (char *)za_Alloc(s1.A, 2);
s[0] = c;
s[1] = '\0';
return (const ekstring){s, 1, s1.A};
}
size_t length = s1.length + 2;
char *s = (char *)za_Alloc(s1.A, length);
strncpy(s, s1.buf, s1.length);
s[length - 2] = c;
s[length - 1] = '\0';
return (const ekstring){s, length - 1, s1.A};
}
const int parse_int(const ekstring s1) { return atoi(s1.buf); }
const char *get_string_cstring(const ekstring s) { return s.buf; }
void destroy_string(const ekstring s) { za_Free(s.A, (void *)s.buf); }
// -----------------------------------------------------------
// ------------------------ Tag ------------------------------
typedef enum TagType {
AREA = 1,
BASE,
BASEFONT,
BGSOUND,
BR,
COL,
COMMAND,
EMBED,
FRAME,
HR,
IMAGE,
IMG,
INPUT,
ISINDEX,
KEYGEN,
LINK,
MENUITEM,
META,
NEXTID,
PARAM,
SOURCE,
TRACK,
WBR,
END_OF_VOID_TAGS,
A,
ABBR,
ADDRESS,
ARTICLE,
ASIDE,
AUDIO,
B,
BDI,
BDO,
BLOCKQUOTE,
BODY,
BUTTON,
CANVAS,
CAPTION,
CITE,
CODE,
COLGROUP,
DATA,
DATALIST,
DD,
DEL,
DETAILS,
DFN,
DIALOG,
DIV,
DL,
DT,
EM,
FIELDSET,
FIGCAPTION,
FIGURE,
FOOTER,
FORM,
H1,
H2,
H3,
H4,
H5,
H6,
HEAD,
HEADER,
HGROUP,
HTML,
I,
IFRAME,
INS,
KBD,
LABEL,
LEGEND,
LI,
MAIN,
MAP,
MARK,
MATH,
MENU,
METER,
NAV,
NOSCRIPT,
OBJECT,
OL,
OPTGROUP,
OPTION,
OUTPUT,
P,
PICTURE,
PRE,
PROGRESS,
Q,
RB,
RP,
RT,
RTC,
RUBY,
S,
SAMP,
SCRIPT,
SECTION,
SELECT,
SLOT,
SMALL,
SPAN,
STRONG,
STYLE,
SUB,
SUMMARY,
SUP,
SVG,
TABLE,
TBODY,
TD,
TEMPLATE,
TEXTAREA,
TFOOT,
TH,
THEAD,
TIME,
TITLE,
TR,
U,
UL,
VAR,
VIDEO,
CUSTOM,
} TagType;
typedef struct Tag {
TagType type;
ekstring custom_tag_name;
} Tag;
static const TagType TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS[] = {
ADDRESS, ARTICLE, ASIDE, BLOCKQUOTE, DETAILS, DIV, DL,
FIELDSET, FIGCAPTION, FIGURE, FOOTER, FORM, H1, H2,
H3, H4, H5, H6, HEADER, HR, MAIN,
NAV, OL, P, PRE, SECTION,
};
static const unsigned int TTNAIP_LEN =
sizeof(TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS) / sizeof(TagType);
Tag *initTag(za_Allocator *A) {
Tag *t = (Tag *)za_Alloc(A, sizeof(Tag));
t->type = END_OF_VOID_TAGS;
t->custom_tag_name = NaS(A);
return t;
}
Tag *initTagArgs(za_Allocator *A, TagType type, const ekstring name) {
Tag *t = (Tag *)za_Alloc(A, sizeof(Tag));
t->type = type;
t->custom_tag_name = init_string_string(name);
return t;
}
bool compareTags(const Tag *a, const Tag *b) {
if (a == NULL || b == NULL) {
if (a == NULL && b == NULL)
return true;
return false;
}
if (a->type != b->type)
return false;
if (a->type == CUSTOM &&
!compare_string_string(a->custom_tag_name, b->custom_tag_name))
return false;
return true;
}
inline const bool is_void(Tag *tag) { return tag->type < END_OF_VOID_TAGS; }
const bool findTagType(const TagType *tt, TagType toFind) {
for (int i = 0; i < TTNAIP_LEN; i++)
if (tt[i] == toFind)
return true;
return false;
}
const bool findTag(vc_vector *v, Tag *tag) {
for (int i = 0; i < v->count; i++)
if (compareTags(vc_vector_at(v, i), tag))
return true;
return false;
}
inline bool can_contain(const Tag *parent, const Tag *tag) {
TagType child = tag->type;
switch (parent->type) {
case LI:
return child != LI;
case DT:
case DD:
return child != DT && child != DD;
case P:
return !findTagType(TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS, tag->type);
case COLGROUP:
return child == COL;
case RB:
case RT:
case RP:
return child != RB && child != RT && child != RP;
case OPTGROUP:
return child != OPTGROUP;
case TR:
return child != TR;
case TD:
case TH:
return child != TD && child != TH && child != TR;
default:
return true;
}
}
// ------------------------------------------------------------
// ----------------------- Hashmap ---------------------------
/* We need to keep keys and values. */
struct hashmap_element_s {
const char *key;
unsigned key_len;
int in_use;
TagType data;
};
/* A hashmap has some maximum size and current size, as well as the data to
* hold. */
struct hashmap_s {
unsigned table_size;
unsigned size;
struct hashmap_element_s *data;
};
#define HASHMAP_MAX_CHAIN_LENGTH (8)
#if defined(__cplusplus)
extern "C" {
#endif
int hashmap_create(za_Allocator *A, const unsigned initial_size,
struct hashmap_s *const out_hashmap) {
out_hashmap->table_size = initial_size;
out_hashmap->size = 0;
if (0 == initial_size || 0 != (initial_size & (initial_size - 1))) {
return 1;
}
out_hashmap->data = HASHMAP_CAST(
struct hashmap_element_s *,
za_Alloc(A, initial_size * sizeof(struct hashmap_element_s)));
if (!out_hashmap->data) {
return 1;
}
return 0;
}
unsigned hashmap_crc32_helper(const char *const s, const unsigned len) {
unsigned i;
unsigned crc32val = 0;
#if defined(HASHMAP_SSE42)
for (i = 0; i < len; i++) {
crc32val = _mm_crc32_u8(crc32val, HASHMAP_CAST(unsigned char, s[i]));
}
return crc32val;
#else
// Using polynomial 0x11EDC6F41 to match SSE 4.2's crc function.
static const unsigned crc32_tab[] = {
0x00000000U, 0xF26B8303U, 0xE13B70F7U, 0x1350F3F4U, 0xC79A971FU,
0x35F1141CU, 0x26A1E7E8U, 0xD4CA64EBU, 0x8AD958CFU, 0x78B2DBCCU,
0x6BE22838U, 0x9989AB3BU, 0x4D43CFD0U, 0xBF284CD3U, 0xAC78BF27U,
0x5E133C24U, 0x105EC76FU, 0xE235446CU, 0xF165B798U, 0x030E349BU,
0xD7C45070U, 0x25AFD373U, 0x36FF2087U, 0xC494A384U, 0x9A879FA0U,
0x68EC1CA3U, 0x7BBCEF57U, 0x89D76C54U, 0x5D1D08BFU, 0xAF768BBCU,
0xBC267848U, 0x4E4DFB4BU, 0x20BD8EDEU, 0xD2D60DDDU, 0xC186FE29U,
0x33ED7D2AU, 0xE72719C1U, 0x154C9AC2U, 0x061C6936U, 0xF477EA35U,
0xAA64D611U, 0x580F5512U, 0x4B5FA6E6U, 0xB93425E5U, 0x6DFE410EU,
0x9F95C20DU, 0x8CC531F9U, 0x7EAEB2FAU, 0x30E349B1U, 0xC288CAB2U,
0xD1D83946U, 0x23B3BA45U, 0xF779DEAEU, 0x05125DADU, 0x1642AE59U,
0xE4292D5AU, 0xBA3A117EU, 0x4851927DU, 0x5B016189U, 0xA96AE28AU,
0x7DA08661U, 0x8FCB0562U, 0x9C9BF696U, 0x6EF07595U, 0x417B1DBCU,
0xB3109EBFU, 0xA0406D4BU, 0x522BEE48U, 0x86E18AA3U, 0x748A09A0U,
0x67DAFA54U, 0x95B17957U, 0xCBA24573U, 0x39C9C670U, 0x2A993584U,
0xD8F2B687U, 0x0C38D26CU, 0xFE53516FU, 0xED03A29BU, 0x1F682198U,
0x5125DAD3U, 0xA34E59D0U, 0xB01EAA24U, 0x42752927U, 0x96BF4DCCU,
0x64D4CECFU, 0x77843D3BU, 0x85EFBE38U, 0xDBFC821CU, 0x2997011FU,
0x3AC7F2EBU, 0xC8AC71E8U, 0x1C661503U, 0xEE0D9600U, 0xFD5D65F4U,
0x0F36E6F7U, 0x61C69362U, 0x93AD1061U, 0x80FDE395U, 0x72966096U,
0xA65C047DU, 0x5437877EU, 0x4767748AU, 0xB50CF789U, 0xEB1FCBADU,
0x197448AEU, 0x0A24BB5AU, 0xF84F3859U, 0x2C855CB2U, 0xDEEEDFB1U,
0xCDBE2C45U, 0x3FD5AF46U, 0x7198540DU, 0x83F3D70EU, 0x90A324FAU,
0x62C8A7F9U, 0xB602C312U, 0x44694011U, 0x5739B3E5U, 0xA55230E6U,
0xFB410CC2U, 0x092A8FC1U, 0x1A7A7C35U, 0xE811FF36U, 0x3CDB9BDDU,
0xCEB018DEU, 0xDDE0EB2AU, 0x2F8B6829U, 0x82F63B78U, 0x709DB87BU,
0x63CD4B8FU, 0x91A6C88CU, 0x456CAC67U, 0xB7072F64U, 0xA457DC90U,
0x563C5F93U, 0x082F63B7U, 0xFA44E0B4U, 0xE9141340U, 0x1B7F9043U,
0xCFB5F4A8U, 0x3DDE77ABU, 0x2E8E845FU, 0xDCE5075CU, 0x92A8FC17U,
0x60C37F14U, 0x73938CE0U, 0x81F80FE3U, 0x55326B08U, 0xA759E80BU,
0xB4091BFFU, 0x466298FCU, 0x1871A4D8U, 0xEA1A27DBU, 0xF94AD42FU,
0x0B21572CU, 0xDFEB33C7U, 0x2D80B0C4U, 0x3ED04330U, 0xCCBBC033U,
0xA24BB5A6U, 0x502036A5U, 0x4370C551U, 0xB11B4652U, 0x65D122B9U,
0x97BAA1BAU, 0x84EA524EU, 0x7681D14DU, 0x2892ED69U, 0xDAF96E6AU,
0xC9A99D9EU, 0x3BC21E9DU, 0xEF087A76U, 0x1D63F975U, 0x0E330A81U,
0xFC588982U, 0xB21572C9U, 0x407EF1CAU, 0x532E023EU, 0xA145813DU,
0x758FE5D6U, 0x87E466D5U, 0x94B49521U, 0x66DF1622U, 0x38CC2A06U,
0xCAA7A905U, 0xD9F75AF1U, 0x2B9CD9F2U, 0xFF56BD19U, 0x0D3D3E1AU,
0x1E6DCDEEU, 0xEC064EEDU, 0xC38D26C4U, 0x31E6A5C7U, 0x22B65633U,
0xD0DDD530U, 0x0417B1DBU, 0xF67C32D8U, 0xE52CC12CU, 0x1747422FU,
0x49547E0BU, 0xBB3FFD08U, 0xA86F0EFCU, 0x5A048DFFU, 0x8ECEE914U,
0x7CA56A17U, 0x6FF599E3U, 0x9D9E1AE0U, 0xD3D3E1ABU, 0x21B862A8U,
0x32E8915CU, 0xC083125FU, 0x144976B4U, 0xE622F5B7U, 0xF5720643U,
0x07198540U, 0x590AB964U, 0xAB613A67U, 0xB831C993U, 0x4A5A4A90U,
0x9E902E7BU, 0x6CFBAD78U, 0x7FAB5E8CU, 0x8DC0DD8FU, 0xE330A81AU,
0x115B2B19U, 0x020BD8EDU, 0xF0605BEEU, 0x24AA3F05U, 0xD6C1BC06U,
0xC5914FF2U, 0x37FACCF1U, 0x69E9F0D5U, 0x9B8273D6U, 0x88D28022U,
0x7AB90321U, 0xAE7367CAU, 0x5C18E4C9U, 0x4F48173DU, 0xBD23943EU,
0xF36E6F75U, 0x0105EC76U, 0x12551F82U, 0xE03E9C81U, 0x34F4F86AU,
0xC69F7B69U, 0xD5CF889DU, 0x27A40B9EU, 0x79B737BAU, 0x8BDCB4B9U,
0x988C474DU, 0x6AE7C44EU, 0xBE2DA0A5U, 0x4C4623A6U, 0x5F16D052U,
0xAD7D5351U};
for (i = 0; i < len; i++) {
crc32val = crc32_tab[(HASHMAP_CAST(unsigned char, crc32val) ^
HASHMAP_CAST(unsigned char, s[i]))] ^
(crc32val >> 8);
}
return crc32val;
#endif
}
unsigned hashmap_hash_helper_int_helper(const struct hashmap_s *const m,
const char *const keystring,
const unsigned len) {
unsigned key = hashmap_crc32_helper(keystring, len);
/* Robert Jenkins' 32 bit Mix Function */
key += (key << 12);
key ^= (key >> 22);
key += (key << 4);
key ^= (key >> 9);
key += (key << 10);
key ^= (key >> 2);
key += (key << 7);
key ^= (key >> 12);
/* Knuth's Multiplicative Method */
key = (key >> 3) * 2654435761;
return key % m->table_size;
}
int hashmap_match_helper(const struct hashmap_element_s *const element,
const char *const key, const unsigned len) {
return (element->key_len == len) && (0 == memcmp(element->key, key, len));
}
int hashmap_hash_helper(za_Allocator *A, const struct hashmap_s *const m,
const char *const key, const unsigned len,
unsigned *const out_index) {
unsigned int start, curr;
unsigned int i;
int total_in_use;
/* If full, return immediately */
if (m->size >= m->table_size) {
return 0;
}
/* Find the best index */
curr = start = hashmap_hash_helper_int_helper(m, key, len);
/* First linear probe to check if we've already insert the element */
total_in_use = 0;
for (i = 0; i < HASHMAP_MAX_CHAIN_LENGTH; i++) {
const int in_use = m->data[curr].in_use;
total_in_use += in_use;
if (in_use && hashmap_match_helper(&m->data[curr], key, len)) {
*out_index = curr;
return 1;
}
curr = (curr + 1) % m->table_size;
}
curr = start;
/* Second linear probe to actually insert our element (only if there was at
* least one empty entry) */
if (HASHMAP_MAX_CHAIN_LENGTH > total_in_use) {
for (i = 0; i < HASHMAP_MAX_CHAIN_LENGTH; i++) {
if (!m->data[curr].in_use) {
*out_index = curr;
return 1;
}
curr = (curr + 1) % m->table_size;
}
}
return 0;
}
int hashmap_iterate_pairs(za_Allocator *A, struct hashmap_s *const hashmap,
int (*f)(za_Allocator *, void *const,
struct hashmap_element_s *const),
void *const context) {
unsigned int i;
struct hashmap_element_s *p;
int r;
/* Linear probing */
for (i = 0; i < hashmap->table_size; i++) {
p = &hashmap->data[i];
if (p->in_use) {
r = f(A, context, p);
switch (r) {
case -1: /* remove item */
memset(p, 0, sizeof(struct hashmap_element_s));
hashmap->size--;
break;
case 0: /* continue iterating */
break;
default: /* early exit */
return 1;
}
}
}
return 0;
}
void hashmap_destroy(za_Allocator *A, struct hashmap_s *const m) {
/* za_Free(A, m->data); */
/* memset(m, 0, sizeof(struct hashmap_s)); */
}
int hashmap_put(za_Allocator *A, struct hashmap_s *const m,
const char *const key, const unsigned len, TagType value);
int hashmap_rehash_iterator(za_Allocator *A, void *const new_hash,
struct hashmap_element_s *const e) {
int temp = hashmap_put(A, HASHMAP_PTR_CAST(struct hashmap_s *, new_hash),
e->key, e->key_len, e->data);
if (0 < temp) {
return 1;
}
/* clear old value to avoid stale pointers */
return -1;
}
// Doubles the size of the hashmap, and rehashes all the elements
int hashmap_rehash_helper(za_Allocator *A, struct hashmap_s *const m) {
/* If this multiplication overflows hashmap_create will fail. */
unsigned new_size = 2 * m->table_size;
struct hashmap_s new_hash;
int flag = hashmap_create(A, new_size, &new_hash);
if (0 != flag) {
return flag;
}
/* copy the old elements to the new table */
flag = hashmap_iterate_pairs(A, m, hashmap_rehash_iterator,
HASHMAP_PTR_CAST(void *, &new_hash));
if (0 != flag) {
return flag;
}
hashmap_destroy(A, m);
/* put new hash into old hash structure by copying */
memcpy(m, &new_hash, sizeof(struct hashmap_s));
return 0;
}
int hashmap_put(za_Allocator *A, struct hashmap_s *const m,
const char *const key, const unsigned len, TagType value) {
unsigned int index;
/* Find a place to put our value. */
while (!hashmap_hash_helper(A, m, key, len, &index)) {
if (hashmap_rehash_helper(A, m)) {
return 1;
}
}
/* Set the data. */
m->data[index].data = value;
m->data[index].key = key;
m->data[index].key_len = len;
/* If the hashmap element was not already in use, set that it is being used
* and bump our size. */
if (0 == m->data[index].in_use) {
m->data[index].in_use = 1;
m->size++;
}
return 0;
}
TagType hashmap_get(const struct hashmap_s *const m, const char *const key,
const unsigned len) {
unsigned int curr;
unsigned int i;
/* Find data location */
curr = hashmap_hash_helper_int_helper(m, key, len);
/* Linear probing, if necessary */
for (i = 0; i < HASHMAP_MAX_CHAIN_LENGTH; i++) {
if (m->data[curr].in_use) {
if (hashmap_match_helper(&m->data[curr], key, len)) {
return m->data[curr].data;
}
}
curr = (curr + 1) % m->table_size;
}
/* Not found */
return HASHMAP_NULL;
}
// for a name
Tag *for_name(za_Allocator *A, struct hashmap_s *m, const ekstring *name) {
TagType type = hashmap_get(m, name->buf, name->length);
if (type != 0) {
Tag *t = (Tag *)za_Alloc(A, sizeof(Tag));
t->type = type;
t->custom_tag_name = (ekstring){NULL, 0, A};
return t;
} else {
return initTagArgs(A, CUSTOM, *name);
}
}
// init tags-hashmap
static const struct hashmap_s *get_tag_map(za_Allocator *AA) {
struct hashmap_s *data =
(struct hashmap_s *)za_Alloc(AA, sizeof(struct hashmap_s));
int res = hashmap_create(AA, 128, data);
if (res == 0) {
#define TAG(name) hashmap_put(AA, data, (#name), strlen(#name), name)
TAG(AREA);
TAG(BASE);
TAG(BASEFONT);
TAG(BGSOUND);
TAG(BR);
TAG(COL);
TAG(COMMAND);
TAG(EMBED);
TAG(FRAME);
TAG(HR);
TAG(IMAGE);
TAG(IMG);
TAG(INPUT);
TAG(ISINDEX);
TAG(KEYGEN);
TAG(LINK);
TAG(MENUITEM);
TAG(META);
TAG(NEXTID);
TAG(PARAM);
TAG(SOURCE);
TAG(TRACK);
TAG(WBR);
TAG(A);
TAG(ABBR);
TAG(ADDRESS);
TAG(ARTICLE);
TAG(ASIDE);
TAG(AUDIO);
TAG(B);
TAG(BDI);
TAG(BDO);
TAG(BLOCKQUOTE);
TAG(BODY);
TAG(BUTTON);
TAG(CANVAS);
TAG(CAPTION);
TAG(CITE);
TAG(CODE);
TAG(COLGROUP);
TAG(DATA);
TAG(DATALIST);
TAG(DD);
TAG(DEL);
TAG(DETAILS);
TAG(DFN);
TAG(DIALOG);
TAG(DIV);
TAG(DL);
TAG(DT);
TAG(EM);
TAG(FIELDSET);
TAG(FIGCAPTION);
TAG(FIGURE);
TAG(FOOTER);
TAG(FORM);
TAG(H1);
TAG(H2);
TAG(H3);
TAG(H4);
TAG(H5);
TAG(H6);
TAG(HEAD);
TAG(HEADER);
TAG(HGROUP);
TAG(HTML);
TAG(I);
TAG(IFRAME);
TAG(INS);
TAG(KBD);
TAG(LABEL);
TAG(LEGEND);
TAG(LI);
TAG(MAIN);
TAG(MAP);
TAG(MARK);
TAG(MATH);
TAG(MENU);
TAG(METER);
TAG(NAV);
TAG(NOSCRIPT);
TAG(OBJECT);
TAG(OL);
TAG(OPTGROUP);
TAG(OPTION);
TAG(OUTPUT);
TAG(P);
TAG(PICTURE);
TAG(PRE);
TAG(PROGRESS);
TAG(Q);
TAG(RB);
TAG(RP);
TAG(RT);
TAG(RTC);
TAG(RUBY);
TAG(S);
TAG(SAMP);
TAG(SCRIPT);
TAG(SECTION);
TAG(SELECT);
TAG(SLOT);
TAG(SMALL);
TAG(SPAN);
TAG(STRONG);
TAG(STYLE);
TAG(SUB);
TAG(SUMMARY);
TAG(SUP);
TAG(SVG);
TAG(TABLE);
TAG(TBODY);
TAG(TD);
TAG(TEMPLATE);
TAG(TEXTAREA);
TAG(TFOOT);
TAG(TH);
TAG(THEAD);
TAG(TIME);
TAG(TITLE);
TAG(TR);
TAG(U);
TAG(UL);
TAG(VAR);
TAG(VIDEO);
#undef TAG
}
return data;
}
#if defined(__cplusplus)
}
#endif
// -------------------------------------------------------
#endif
| 25.369975 | 80 | 0.635679 | [
"object",
"vector"
] |
d63d6a91d68d2e97ec6f557070c55ccd67425ddd | 30,703 | c | C | contrib/diff/diff.c | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2017-04-06T21:39:15.000Z | 2019-10-09T17:34:14.000Z | contrib/diff/diff.c | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | contrib/diff/diff.c | TrustedBSD/sebsd | fd5de6f587183087cf930779701d5713e8ca64cc | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-01-04T06:36:39.000Z | 2020-01-04T06:36:39.000Z | /* GNU DIFF main routine.
Copyright (C) 1988, 1989, 1992, 1993, 1994 Free Software Foundation, Inc.
This file is part of GNU DIFF.
GNU DIFF is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU DIFF is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU DIFF; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
/* GNU DIFF was written by Mike Haertel, David Hayes,
Richard Stallman, Len Tower, and Paul Eggert. */
/* $FreeBSD: src/contrib/diff/diff.c,v 1.5 2005/06/03 06:46:56 obrien Exp $ */
#define GDIFF_MAIN
#include "diff.h"
#include <signal.h>
#include "getopt.h"
#ifdef __FreeBSD__
#include <locale.h>
#include <fnmatch.h>
#else
#include "fnmatch.h"
#endif
#include "prepend_args.h"
#ifndef DEFAULT_WIDTH
#define DEFAULT_WIDTH 130
#endif
#ifndef GUTTER_WIDTH_MINIMUM
#define GUTTER_WIDTH_MINIMUM 3
#endif
static char const *filetype PARAMS((struct stat const *));
static char *option_list PARAMS((char **, int));
static int add_exclude_file PARAMS((char const *));
static int ck_atoi PARAMS((char const *, int *));
static int compare_files PARAMS((char const *, char const *, char const *, char const *, int));
static int specify_format PARAMS((char **, char *));
static void add_exclude PARAMS((char const *));
static void add_regexp PARAMS((struct regexp_list **, char const *));
static void specify_style PARAMS((enum output_style));
static void try_help PARAMS((char const *));
static void check_stdout PARAMS((void));
static void usage PARAMS((void));
/* Nonzero for -r: if comparing two directories,
compare their common subdirectories recursively. */
static int recursive;
/* For debugging: don't do discard_confusing_lines. */
int no_discards;
#if HAVE_SETMODE
/* I/O mode: nonzero only if using binary input/output. */
static int binary_I_O;
#endif
/* Return a string containing the command options with which diff was invoked.
Spaces appear between what were separate ARGV-elements.
There is a space at the beginning but none at the end.
If there were no options, the result is an empty string.
Arguments: OPTIONVEC, a vector containing separate ARGV-elements, and COUNT,
the length of that vector. */
static char *
option_list (optionvec, count)
char **optionvec; /* Was `vector', but that collides on Alliant. */
int count;
{
int i;
size_t length = 0;
char *result;
for (i = 0; i < count; i++)
length += strlen (optionvec[i]) + 1;
result = xmalloc (length + 1);
result[0] = 0;
for (i = 0; i < count; i++)
{
strcat (result, " ");
strcat (result, optionvec[i]);
}
return result;
}
/* Convert STR to a positive integer, storing the result in *OUT.
If STR is not a valid integer, return -1 (otherwise 0). */
static int
ck_atoi (str, out)
char const *str;
int *out;
{
char const *p;
for (p = str; *p; p++)
if (*p < '0' || *p > '9')
return -1;
*out = atoi (optarg);
return 0;
}
/* Keep track of excluded file name patterns. */
static char const **exclude;
static int exclude_alloc, exclude_count;
int
excluded_filename (f)
char const *f;
{
int i;
for (i = 0; i < exclude_count; i++)
if (fnmatch (exclude[i], f, 0) == 0)
return 1;
return 0;
}
static void
add_exclude (pattern)
char const *pattern;
{
if (exclude_alloc <= exclude_count)
exclude = (char const **)
(exclude_alloc == 0
? xmalloc ((exclude_alloc = 64) * sizeof (*exclude))
: xrealloc (exclude, (exclude_alloc *= 2) * sizeof (*exclude)));
exclude[exclude_count++] = pattern;
}
static int
add_exclude_file (name)
char const *name;
{
struct file_data f;
char *p, *q, *lim;
f.name = optarg;
f.desc = (strcmp (optarg, "-") == 0
? STDIN_FILENO
: open (optarg, O_RDONLY, 0));
if (f.desc < 0 || fstat (f.desc, &f.stat) != 0)
return -1;
sip (&f, 1);
slurp (&f);
for (p = f.buffer, lim = p + f.buffered_chars; p < lim; p = q)
{
q = (char *) memchr (p, '\n', lim - p);
if (!q)
q = lim;
*q++ = 0;
add_exclude (p);
}
return close (f.desc);
}
/* The numbers 129- that appear in the fourth element of some entries
tell the big switch in `main' how to process those options. */
static struct option const longopts[] =
{
{"ignore-blank-lines", 0, 0, 'B'},
{"context", 2, 0, 'C'},
{"ifdef", 1, 0, 'D'},
{"show-function-line", 1, 0, 'F'},
{"speed-large-files", 0, 0, 'H'},
{"ignore-matching-lines", 1, 0, 'I'},
{"label", 1, 0, 'L'},
{"file-label", 1, 0, 'L'}, /* An alias, no longer recommended */
{"new-file", 0, 0, 'N'},
{"entire-new-file", 0, 0, 'N'}, /* An alias, no longer recommended */
{"unidirectional-new-file", 0, 0, 'P'},
{"starting-file", 1, 0, 'S'},
{"initial-tab", 0, 0, 'T'},
{"width", 1, 0, 'W'},
{"text", 0, 0, 'a'},
{"ascii", 0, 0, 'a'}, /* An alias, no longer recommended */
{"ignore-space-change", 0, 0, 'b'},
{"minimal", 0, 0, 'd'},
{"ed", 0, 0, 'e'},
{"forward-ed", 0, 0, 'f'},
{"ignore-case", 0, 0, 'i'},
{"paginate", 0, 0, 'l'},
{"print", 0, 0, 'l'}, /* An alias, no longer recommended */
{"rcs", 0, 0, 'n'},
{"show-c-function", 0, 0, 'p'},
{"brief", 0, 0, 'q'},
{"recursive", 0, 0, 'r'},
{"report-identical-files", 0, 0, 's'},
{"expand-tabs", 0, 0, 't'},
{"version", 0, 0, 'v'},
{"ignore-all-space", 0, 0, 'w'},
{"exclude", 1, 0, 'x'},
{"exclude-from", 1, 0, 'X'},
{"side-by-side", 0, 0, 'y'},
{"unified", 2, 0, 'U'},
{"left-column", 0, 0, 129},
{"suppress-common-lines", 0, 0, 130},
{"sdiff-merge-assist", 0, 0, 131},
{"old-line-format", 1, 0, 132},
{"new-line-format", 1, 0, 133},
{"unchanged-line-format", 1, 0, 134},
{"line-format", 1, 0, 135},
{"old-group-format", 1, 0, 136},
{"new-group-format", 1, 0, 137},
{"unchanged-group-format", 1, 0, 138},
{"changed-group-format", 1, 0, 139},
{"horizon-lines", 1, 0, 140},
{"help", 0, 0, 141},
{"binary", 0, 0, 142},
{0, 0, 0, 0}
};
int
main (argc, argv)
int argc;
char *argv[];
{
int val;
int c;
int prev = -1;
int width = DEFAULT_WIDTH;
int show_c_function = 0;
#ifdef __FreeBSD__
setlocale(LC_ALL, "");
#endif
/* Do our initializations. */
initialize_main (&argc, &argv);
program_name = argv[0];
output_style = OUTPUT_NORMAL;
context = -1;
prepend_default_options (getenv ("DIFF_OPTIONS"), &argc, &argv);
/* Decode the options. */
while ((c = getopt_long (argc, argv,
"0123456789abBcC:dD:efF:hHiI:lL:nNopPqrsS:tTuU:vwW:x:X:y",
longopts, 0)) != EOF)
{
switch (c)
{
/* All digits combine in decimal to specify the context-size. */
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
if (context == -1)
context = 0;
/* If a context length has already been specified,
more digits allowed only if they follow right after the others.
Reject two separate runs of digits, or digits after -C. */
else if (prev < '0' || prev > '9')
fatal ("context length specified twice");
context = context * 10 + c - '0';
break;
case 'a':
/* Treat all files as text files; never treat as binary. */
always_text_flag = 1;
break;
case 'b':
/* Ignore changes in amount of white space. */
ignore_space_change_flag = 1;
ignore_some_changes = 1;
ignore_some_line_changes = 1;
break;
case 'B':
/* Ignore changes affecting only blank lines. */
ignore_blank_lines_flag = 1;
ignore_some_changes = 1;
break;
case 'C': /* +context[=lines] */
case 'U': /* +unified[=lines] */
if (optarg)
{
if (context >= 0)
fatal ("context length specified twice");
if (ck_atoi (optarg, &context))
fatal ("invalid context length argument");
}
/* Falls through. */
case 'c':
/* Make context-style output. */
specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
break;
case 'd':
/* Don't discard lines. This makes things slower (sometimes much
slower) but will find a guaranteed minimal set of changes. */
no_discards = 1;
break;
case 'D':
/* Make merged #ifdef output. */
specify_style (OUTPUT_IFDEF);
{
int i, err = 0;
static char const C_ifdef_group_formats[] =
"#ifndef %s\n%%<#endif /* not %s */\n%c#ifdef %s\n%%>#endif /* %s */\n%c%%=%c#ifndef %s\n%%<#else /* %s */\n%%>#endif /* %s */\n";
char *b = xmalloc (sizeof (C_ifdef_group_formats)
+ 7 * strlen(optarg) - 14 /* 7*"%s" */
- 8 /* 5*"%%" + 3*"%c" */);
sprintf (b, C_ifdef_group_formats,
optarg, optarg, 0,
optarg, optarg, 0, 0,
optarg, optarg, optarg);
for (i = 0; i < 4; i++)
{
err |= specify_format (&group_format[i], b);
b += strlen (b) + 1;
}
if (err)
error ("conflicting #ifdef formats", 0, 0);
}
break;
case 'e':
/* Make output that is a valid `ed' script. */
specify_style (OUTPUT_ED);
break;
case 'f':
/* Make output that looks vaguely like an `ed' script
but has changes in the order they appear in the file. */
specify_style (OUTPUT_FORWARD_ED);
break;
case 'F':
/* Show, for each set of changes, the previous line that
matches the specified regexp. Currently affects only
context-style output. */
add_regexp (&function_regexp_list, optarg);
break;
case 'h':
/* Split the files into chunks of around 1500 lines
for faster processing. Usually does not change the result.
This currently has no effect. */
break;
case 'H':
/* Turn on heuristics that speed processing of large files
with a small density of changes. */
heuristic = 1;
break;
case 'i':
/* Ignore changes in case. */
ignore_case_flag = 1;
ignore_some_changes = 1;
ignore_some_line_changes = 1;
break;
case 'I':
/* Ignore changes affecting only lines that match the
specified regexp. */
add_regexp (&ignore_regexp_list, optarg);
ignore_some_changes = 1;
break;
case 'l':
/* Pass the output through `pr' to paginate it. */
paginate_flag = 1;
#if !defined(SIGCHLD) && defined(SIGCLD)
#define SIGCHLD SIGCLD
#endif
#ifdef SIGCHLD
/* Pagination requires forking and waiting, and
System V fork+wait does not work if SIGCHLD is ignored. */
signal (SIGCHLD, SIG_DFL);
#endif
break;
case 'L':
/* Specify file labels for `-c' output headers. */
if (!file_label[0])
file_label[0] = optarg;
else if (!file_label[1])
file_label[1] = optarg;
else
fatal ("too many file label options");
break;
case 'n':
/* Output RCS-style diffs, like `-f' except that each command
specifies the number of lines affected. */
specify_style (OUTPUT_RCS);
break;
case 'N':
/* When comparing directories, if a file appears only in one
directory, treat it as present but empty in the other. */
entire_new_file_flag = 1;
break;
case 'o':
/* Output in the old tradition style. */
specify_style (OUTPUT_NORMAL);
break;
case 'p':
/* Make context-style output and show name of last C function. */
show_c_function = 1;
add_regexp (&function_regexp_list, "^[_a-zA-Z$]");
break;
case 'P':
/* When comparing directories, if a file appears only in
the second directory of the two,
treat it as present but empty in the other. */
unidirectional_new_file_flag = 1;
break;
case 'q':
no_details_flag = 1;
break;
case 'r':
/* When comparing directories,
recursively compare any subdirectories found. */
recursive = 1;
break;
case 's':
/* Print a message if the files are the same. */
print_file_same_flag = 1;
break;
case 'S':
/* When comparing directories, start with the specified
file name. This is used for resuming an aborted comparison. */
dir_start_file = optarg;
break;
case 't':
/* Expand tabs to spaces in the output so that it preserves
the alignment of the input files. */
tab_expand_flag = 1;
break;
case 'T':
/* Use a tab in the output, rather than a space, before the
text of an input line, so as to keep the proper alignment
in the input line without changing the characters in it. */
tab_align_flag = 1;
break;
case 'u':
/* Output the context diff in unidiff format. */
specify_style (OUTPUT_UNIFIED);
break;
case 'v':
printf ("diff - GNU diffutils version %s\n", version_string);
exit (0);
case 'w':
/* Ignore horizontal white space when comparing lines. */
ignore_all_space_flag = 1;
ignore_some_changes = 1;
ignore_some_line_changes = 1;
break;
case 'x':
add_exclude (optarg);
break;
case 'X':
if (add_exclude_file (optarg) != 0)
pfatal_with_name (optarg);
break;
case 'y':
/* Use side-by-side (sdiff-style) columnar output. */
specify_style (OUTPUT_SDIFF);
break;
case 'W':
/* Set the line width for OUTPUT_SDIFF. */
if (ck_atoi (optarg, &width) || width <= 0)
fatal ("column width must be a positive integer");
break;
case 129:
sdiff_left_only = 1;
break;
case 130:
sdiff_skip_common_lines = 1;
break;
case 131:
/* sdiff-style columns output. */
specify_style (OUTPUT_SDIFF);
sdiff_help_sdiff = 1;
break;
case 132:
case 133:
case 134:
specify_style (OUTPUT_IFDEF);
if (specify_format (&line_format[c - 132], optarg) != 0)
error ("conflicting line format", 0, 0);
break;
case 135:
specify_style (OUTPUT_IFDEF);
{
int i, err = 0;
for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
err |= specify_format (&line_format[i], optarg);
if (err)
error ("conflicting line format", 0, 0);
}
break;
case 136:
case 137:
case 138:
case 139:
specify_style (OUTPUT_IFDEF);
if (specify_format (&group_format[c - 136], optarg) != 0)
error ("conflicting group format", 0, 0);
break;
case 140:
if (ck_atoi (optarg, &horizon_lines) || horizon_lines < 0)
fatal ("horizon must be a nonnegative integer");
break;
case 141:
usage ();
check_stdout ();
exit (0);
case 142:
/* Use binary I/O when reading and writing data.
On Posix hosts, this has no effect. */
#if HAVE_SETMODE
binary_I_O = 1;
setmode (STDOUT_FILENO, O_BINARY);
#endif
break;
default:
try_help (0);
}
prev = c;
}
if (argc - optind != 2)
try_help (argc - optind < 2 ? "missing operand" : "extra operand");
{
/*
* We maximize first the half line width, and then the gutter width,
* according to the following constraints:
* 1. Two half lines plus a gutter must fit in a line.
* 2. If the half line width is nonzero:
* a. The gutter width is at least GUTTER_WIDTH_MINIMUM.
* b. If tabs are not expanded to spaces,
* a half line plus a gutter is an integral number of tabs,
* so that tabs in the right column line up.
*/
int t = tab_expand_flag ? 1 : TAB_WIDTH;
int off = (width + t + GUTTER_WIDTH_MINIMUM) / (2*t) * t;
sdiff_half_width = max (0, min (off - GUTTER_WIDTH_MINIMUM, width - off)),
sdiff_column2_offset = sdiff_half_width ? off : width;
}
if (show_c_function && output_style != OUTPUT_UNIFIED)
specify_style (OUTPUT_CONTEXT);
if (output_style != OUTPUT_CONTEXT && output_style != OUTPUT_UNIFIED)
context = 0;
else if (context == -1)
/* Default amount of context for -c. */
context = 3;
if (output_style == OUTPUT_IFDEF)
{
/* Format arrays are char *, not char const *,
because integer formats are temporarily modified.
But it is safe to assign a constant like "%=" to a format array,
since "%=" does not format any integers. */
int i;
for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
if (!line_format[i])
line_format[i] = "%l\n";
if (!group_format[OLD])
group_format[OLD]
= group_format[UNCHANGED] ? group_format[UNCHANGED] : "%<";
if (!group_format[NEW])
group_format[NEW]
= group_format[UNCHANGED] ? group_format[UNCHANGED] : "%>";
if (!group_format[UNCHANGED])
group_format[UNCHANGED] = "%=";
if (!group_format[CHANGED])
group_format[CHANGED] = concat (group_format[OLD],
group_format[NEW], "");
}
no_diff_means_no_output =
(output_style == OUTPUT_IFDEF ?
(!*group_format[UNCHANGED]
|| (strcmp (group_format[UNCHANGED], "%=") == 0
&& !*line_format[UNCHANGED]))
: output_style == OUTPUT_SDIFF ? sdiff_skip_common_lines : 1);
switch_string = option_list (argv + 1, optind - 1);
val = compare_files (0, argv[optind], 0, argv[optind + 1], 0);
/* Print any messages that were saved up for last. */
print_message_queue ();
check_stdout ();
exit (val);
return val;
}
/* Add the compiled form of regexp PATTERN to REGLIST. */
static void
add_regexp (reglist, pattern)
struct regexp_list **reglist;
char const *pattern;
{
struct regexp_list *r;
char const *m;
r = (struct regexp_list *) xmalloc (sizeof (*r));
bzero (r, sizeof (*r));
r->buf.fastmap = xmalloc (256);
m = re_compile_pattern (pattern, strlen (pattern), &r->buf);
if (m != 0)
error ("%s: %s", pattern, m);
/* Add to the start of the list, since it's easier than the end. */
r->next = *reglist;
*reglist = r;
}
static void
try_help (reason)
char const *reason;
{
if (reason)
error ("%s", reason, 0);
error ("Try `%s --help' for more information.", program_name, 0);
exit (2);
}
static void
check_stdout ()
{
if (ferror (stdout) || fclose (stdout) != 0)
fatal ("write error");
}
static char const * const option_help[] = {
"-i --ignore-case Consider upper- and lower-case to be the same.",
"-w --ignore-all-space Ignore all white space.",
"-b --ignore-space-change Ignore changes in the amount of white space.",
"-B --ignore-blank-lines Ignore changes whose lines are all blank.",
"-I RE --ignore-matching-lines=RE Ignore changes whose lines all match RE.",
#if HAVE_SETMODE
"--binary Read and write data in binary mode.",
#endif
"-a --text Treat all files as text.\n",
"-c -C NUM --context[=NUM] Output NUM (default 2) lines of copied context.",
"-u -U NUM --unified[=NUM] Output NUM (default 2) lines of unified context.",
" -NUM Use NUM context lines.",
" -L LABEL --label LABEL Use LABEL instead of file name.",
" -p --show-c-function Show which C function each change is in.",
" -F RE --show-function-line=RE Show the most recent line matching RE.",
"-q --brief Output only whether files differ.",
"-e --ed Output an ed script.",
"-n --rcs Output an RCS format diff.",
"-y --side-by-side Output in two columns.",
" -W NUM --width=NUM Output at most NUM (default 130) characters per line.",
" --left-column Output only the left column of common lines.",
" --suppress-common-lines Do not output common lines.",
"-DNAME --ifdef=NAME Output merged file to show `#ifdef NAME' diffs.",
"--GTYPE-group-format=GFMT Similar, but format GTYPE input groups with GFMT.",
"--line-format=LFMT Similar, but format all input lines with LFMT.",
"--LTYPE-line-format=LFMT Similar, but format LTYPE input lines with LFMT.",
" LTYPE is `old', `new', or `unchanged'. GTYPE is LTYPE or `changed'.",
" GFMT may contain:",
" %< lines from FILE1",
" %> lines from FILE2",
" %= lines common to FILE1 and FILE2",
" %[-][WIDTH][.[PREC]]{doxX}LETTER printf-style spec for LETTER",
" LETTERs are as follows for new group, lower case for old group:",
" F first line number",
" L last line number",
" N number of lines = L-F+1",
" E F-1",
" M L+1",
" LFMT may contain:",
" %L contents of line",
" %l contents of line, excluding any trailing newline",
" %[-][WIDTH][.[PREC]]{doxX}n printf-style spec for input line number",
" Either GFMT or LFMT may contain:",
" %% %",
" %c'C' the single character C",
" %c'\\OOO' the character with octal code OOO\n",
"-l --paginate Pass the output through `pr' to paginate it.",
"-t --expand-tabs Expand tabs to spaces in output.",
"-T --initial-tab Make tabs line up by prepending a tab.\n",
"-r --recursive Recursively compare any subdirectories found.",
"-N --new-file Treat absent files as empty.",
"-P --unidirectional-new-file Treat absent first files as empty.",
"-s --report-identical-files Report when two files are the same.",
"-x PAT --exclude=PAT Exclude files that match PAT.",
"-X FILE --exclude-from=FILE Exclude files that match any pattern in FILE.",
"-S FILE --starting-file=FILE Start with FILE when comparing directories.\n",
"--horizon-lines=NUM Keep NUM lines of the common prefix and suffix.",
"-d --minimal Try hard to find a smaller set of changes.",
"-H --speed-large-files Assume large files and many scattered small changes.\n",
"-v --version Output version info.",
"--help Output this help.",
0
};
static void
usage ()
{
char const * const *p;
printf ("Usage: %s [OPTION]... FILE1 FILE2\n\n", program_name);
for (p = option_help; *p; p++)
printf (" %s\n", *p);
printf ("\nIf FILE1 or FILE2 is `-', read standard input.\n");
}
static int
specify_format (var, value)
char **var;
char *value;
{
int err = *var ? strcmp (*var, value) : 0;
*var = value;
return err;
}
static void
specify_style (style)
enum output_style style;
{
output_style = style;
}
static char const *
filetype (st)
struct stat const *st;
{
/* See Posix.2 section 4.17.6.1.1 and Table 5-1 for these formats.
To keep diagnostics grammatical, the returned string must start
with a consonant. */
if (S_ISREG (st->st_mode))
{
if (st->st_size == 0)
return "regular empty file";
/* Posix.2 section 5.14.2 seems to suggest that we must read the file
and guess whether it's C, Fortran, etc., but this is somewhat useless
and doesn't reflect historical practice. We're allowed to guess
wrong, so we don't bother to read the file. */
return "regular file";
}
if (S_ISDIR (st->st_mode)) return "directory";
/* other Posix.1 file types */
#ifdef S_ISBLK
if (S_ISBLK (st->st_mode)) return "block special file";
#endif
#ifdef S_ISCHR
if (S_ISCHR (st->st_mode)) return "character special file";
#endif
#ifdef S_ISFIFO
if (S_ISFIFO (st->st_mode)) return "fifo";
#endif
/* other Posix.1b file types */
#ifdef S_TYPEISMQ
if (S_TYPEISMQ (st)) return "message queue";
#endif
#ifdef S_TYPEISSEM
if (S_TYPEISSEM (st)) return "semaphore";
#endif
#ifdef S_TYPEISSHM
if (S_TYPEISSHM (st)) return "shared memory object";
#endif
/* other popular file types */
/* S_ISLNK is impossible with `fstat' and `stat'. */
#ifdef S_ISSOCK
if (S_ISSOCK (st->st_mode)) return "socket";
#endif
return "weird file";
}
/* Compare two files (or dirs) with specified names
DIR0/NAME0 and DIR1/NAME1, at level DEPTH in directory recursion.
(if DIR0 is 0, then the name is just NAME0, etc.)
This is self-contained; it opens the files and closes them.
Value is 0 if files are the same, 1 if different,
2 if there is a problem opening them. */
static int
compare_files (dir0, name0, dir1, name1, depth)
char const *dir0, *dir1;
char const *name0, *name1;
int depth;
{
struct file_data inf[2];
register int i;
int val;
int same_files;
int failed = 0;
char *free0 = 0, *free1 = 0;
/* If this is directory comparison, perhaps we have a file
that exists only in one of the directories.
If so, just print a message to that effect. */
if (! ((name0 != 0 && name1 != 0)
|| (unidirectional_new_file_flag && name1 != 0)
|| entire_new_file_flag))
{
char const *name = name0 == 0 ? name1 : name0;
char const *dir = name0 == 0 ? dir1 : dir0;
message ("Only in %s: %s\n", dir, name);
/* Return 1 so that diff_dirs will return 1 ("some files differ"). */
return 1;
}
bzero (inf, sizeof (inf));
/* Mark any nonexistent file with -1 in the desc field. */
/* Mark unopened files (e.g. directories) with -2. */
inf[0].desc = name0 == 0 ? -1 : -2;
inf[1].desc = name1 == 0 ? -1 : -2;
/* Now record the full name of each file, including nonexistent ones. */
if (name0 == 0)
name0 = name1;
if (name1 == 0)
name1 = name0;
inf[0].name = dir0 == 0 ? name0 : (free0 = dir_file_pathname (dir0, name0));
inf[1].name = dir1 == 0 ? name1 : (free1 = dir_file_pathname (dir1, name1));
/* Stat the files. Record whether they are directories. */
for (i = 0; i <= 1; i++)
{
if (inf[i].desc != -1)
{
int stat_result;
if (i && filename_cmp (inf[i].name, inf[0].name) == 0)
{
inf[i].stat = inf[0].stat;
stat_result = 0;
}
else if (strcmp (inf[i].name, "-") == 0)
{
inf[i].desc = STDIN_FILENO;
stat_result = fstat (STDIN_FILENO, &inf[i].stat);
if (stat_result == 0 && S_ISREG (inf[i].stat.st_mode))
{
off_t pos = lseek (STDIN_FILENO, (off_t) 0, SEEK_CUR);
if (pos == -1)
stat_result = -1;
else
{
if (pos <= inf[i].stat.st_size)
inf[i].stat.st_size -= pos;
else
inf[i].stat.st_size = 0;
/* Posix.2 4.17.6.1.4 requires current time for stdin. */
time (&inf[i].stat.st_mtime);
}
}
}
else
stat_result = stat (inf[i].name, &inf[i].stat);
if (stat_result != 0)
{
perror_with_name (inf[i].name);
failed = 1;
}
else
{
inf[i].dir_p = S_ISDIR (inf[i].stat.st_mode) && inf[i].desc != 0;
if (inf[1 - i].desc == -1)
{
inf[1 - i].dir_p = inf[i].dir_p;
inf[1 - i].stat.st_mode = inf[i].stat.st_mode;
}
}
}
}
if (! failed && depth == 0 && inf[0].dir_p != inf[1].dir_p)
{
/* If one is a directory, and it was specified in the command line,
use the file in that dir with the other file's basename. */
int fnm_arg = inf[0].dir_p;
int dir_arg = 1 - fnm_arg;
char const *fnm = inf[fnm_arg].name;
char const *dir = inf[dir_arg].name;
char const *p = filename_lastdirchar (fnm);
char const *filename = inf[dir_arg].name
= dir_file_pathname (dir, p ? p + 1 : fnm);
if (strcmp (fnm, "-") == 0)
fatal ("can't compare - to a directory");
if (stat (filename, &inf[dir_arg].stat) != 0)
{
perror_with_name (filename);
failed = 1;
}
else
inf[dir_arg].dir_p = S_ISDIR (inf[dir_arg].stat.st_mode);
}
if (failed)
{
/* If either file should exist but does not, return 2. */
val = 2;
}
else if ((same_files = inf[0].desc != -1 && inf[1].desc != -1
&& 0 < same_file (&inf[0].stat, &inf[1].stat))
&& no_diff_means_no_output)
{
/* The two named files are actually the same physical file.
We know they are identical without actually reading them. */
val = 0;
}
else if (inf[0].dir_p & inf[1].dir_p)
{
if (output_style == OUTPUT_IFDEF)
fatal ("-D option not supported with directories");
/* If both are directories, compare the files in them. */
if (depth > 0 && !recursive)
{
/* But don't compare dir contents one level down
unless -r was specified. */
message ("Common subdirectories: %s and %s\n",
inf[0].name, inf[1].name);
val = 0;
}
else
{
val = diff_dirs (inf, compare_files, depth);
}
}
else if ((inf[0].dir_p | inf[1].dir_p)
|| (depth > 0
&& (! S_ISREG (inf[0].stat.st_mode)
|| ! S_ISREG (inf[1].stat.st_mode))))
{
/* Perhaps we have a subdirectory that exists only in one directory.
If so, just print a message to that effect. */
if (inf[0].desc == -1 || inf[1].desc == -1)
{
if ((inf[0].dir_p | inf[1].dir_p)
&& recursive
&& (entire_new_file_flag
|| (unidirectional_new_file_flag && inf[0].desc == -1)))
val = diff_dirs (inf, compare_files, depth);
else
{
char const *dir = (inf[0].desc == -1) ? dir1 : dir0;
/* See Posix.2 section 4.17.6.1.1 for this format. */
message ("Only in %s: %s\n", dir, name0);
val = 1;
}
}
else
{
/* We have two files that are not to be compared. */
/* See Posix.2 section 4.17.6.1.1 for this format. */
message5 ("File %s is a %s while file %s is a %s\n",
inf[0].name, filetype (&inf[0].stat),
inf[1].name, filetype (&inf[1].stat));
/* This is a difference. */
val = 1;
}
}
else if ((no_details_flag & ~ignore_some_changes)
&& inf[0].stat.st_size != inf[1].stat.st_size
&& (inf[0].desc == -1 || S_ISREG (inf[0].stat.st_mode))
&& (inf[1].desc == -1 || S_ISREG (inf[1].stat.st_mode)))
{
message ("Files %s and %s differ\n", inf[0].name, inf[1].name);
val = 1;
}
else
{
/* Both exist and neither is a directory. */
/* Open the files and record their descriptors. */
if (inf[0].desc == -2)
if ((inf[0].desc = open (inf[0].name, O_RDONLY, 0)) < 0)
{
perror_with_name (inf[0].name);
failed = 1;
}
if (inf[1].desc == -2)
if (same_files)
inf[1].desc = inf[0].desc;
else if ((inf[1].desc = open (inf[1].name, O_RDONLY, 0)) < 0)
{
perror_with_name (inf[1].name);
failed = 1;
}
#if HAVE_SETMODE
if (binary_I_O)
for (i = 0; i <= 1; i++)
if (0 <= inf[i].desc)
setmode (inf[i].desc, O_BINARY);
#endif
/* Compare the files, if no error was found. */
val = failed ? 2 : diff_2_files (inf, depth);
/* Close the file descriptors. */
if (inf[0].desc >= 0 && close (inf[0].desc) != 0)
{
perror_with_name (inf[0].name);
val = 2;
}
if (inf[1].desc >= 0 && inf[0].desc != inf[1].desc
&& close (inf[1].desc) != 0)
{
perror_with_name (inf[1].name);
val = 2;
}
}
/* Now the comparison has been done, if no error prevented it,
and VAL is the value this function will return. */
if (val == 0 && !inf[0].dir_p)
{
if (print_file_same_flag)
message ("Files %s and %s are identical\n",
inf[0].name, inf[1].name);
}
else
fflush (stdout);
if (free0)
free (free0);
if (free1)
free (free1);
return val;
}
| 27.364528 | 137 | 0.613393 | [
"object",
"vector"
] |
d63e9a48b041559fbc95a26004551eb4d91ebbd3 | 2,880 | h | C | deps/mozjs/src/jit/PerfSpewer.h | ktrzeciaknubisa/jxcore-binary-packaging | 5759df084be10a259a4a4f1b38c214c6084a7c0f | [
"Apache-2.0"
] | 2,494 | 2015-02-11T04:34:13.000Z | 2022-03-31T14:21:47.000Z | deps/mozjs/src/jit/PerfSpewer.h | ktrzeciaknubisa/jxcore-binary-packaging | 5759df084be10a259a4a4f1b38c214c6084a7c0f | [
"Apache-2.0"
] | 685 | 2015-02-11T17:14:26.000Z | 2021-04-13T09:58:39.000Z | deps/mozjs/src/jit/PerfSpewer.h | ktrzeciaknubisa/jxcore-binary-packaging | 5759df084be10a259a4a4f1b38c214c6084a7c0f | [
"Apache-2.0"
] | 442 | 2015-02-12T13:45:46.000Z | 2022-03-21T05:28:05.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef jit_PerfSpewer_h
#define jit_PerfSpewer_h
#ifdef JS_ION_PERF
# include <stdio.h>
# include "jit/IonMacroAssembler.h"
#endif
namespace js {
namespace jit {
class MBasicBlock;
class MacroAssembler;
#ifdef JS_ION_PERF
void CheckPerf();
bool PerfBlockEnabled();
bool PerfFuncEnabled();
static inline bool PerfEnabled() {
return PerfBlockEnabled() || PerfFuncEnabled();
}
#else
static inline void CheckPerf() {}
static inline bool PerfBlockEnabled() { return false; }
static inline bool PerfFuncEnabled() { return false; }
static inline bool PerfEnabled() { return false; }
#endif
#ifdef JS_ION_PERF
struct Record {
const char *filename;
unsigned lineNumber;
unsigned columnNumber;
uint32_t id;
Label start, end;
size_t startOffset, endOffset;
Record(const char *filename,
unsigned lineNumber,
unsigned columnNumber,
uint32_t id)
: filename(filename), lineNumber(lineNumber),
columnNumber(columnNumber), id(id),
startOffset(0u), endOffset(0u)
{}
};
typedef Vector<Record, 1, SystemAllocPolicy> BasicBlocksVector;
class PerfSpewer
{
protected:
static uint32_t nextFunctionIndex;
public:
Label endInlineCode;
protected:
BasicBlocksVector basicBlocks_;
public:
virtual bool startBasicBlock(MBasicBlock *blk, MacroAssembler &masm);
bool endBasicBlock(MacroAssembler &masm);
bool noteEndInlineCode(MacroAssembler &masm);
void writeProfile(JSScript *script, JitCode *code, MacroAssembler &masm);
};
void writePerfSpewerBaselineProfile(JSScript *script, JitCode *code);
void writePerfSpewerJitCodeProfile(JitCode *code, const char *msg);
class AsmJSPerfSpewer : public PerfSpewer
{
public:
bool startBasicBlock(MBasicBlock *blk, MacroAssembler &masm);
void noteBlocksOffsets();
BasicBlocksVector &basicBlocks() { return basicBlocks_; }
};
void writePerfSpewerAsmJSFunctionMap(uintptr_t base, uintptr_t size, const char *filename,
unsigned lineno, unsigned colIndex, const char *funcName);
void writePerfSpewerAsmJSBlocksMap(uintptr_t baseAddress, size_t funcStartOffset,
size_t funcStartOOLOffset, size_t funcSize,
const char *filename, const char *funcName,
const BasicBlocksVector &basicBlocks);
void writePerfSpewerAsmJSEntriesAndExits(uintptr_t base, size_t size);
#endif // JS_ION_PERF
} // namespace jit
} // namespace js
#endif /* jit_PerfSpewer_h */
| 27.692308 | 95 | 0.702778 | [
"vector"
] |
d64371d009b6f4d190a09d9d91fd7d96dfd6ec27 | 1,040 | h | C | RealTournament/include/RealTournament/Weapon.h | willcassella/RealTournament | 70ed3c0d5cbb67938ec8f86eec7b4d98a26e25f3 | [
"MIT"
] | null | null | null | RealTournament/include/RealTournament/Weapon.h | willcassella/RealTournament | 70ed3c0d5cbb67938ec8f86eec7b4d98a26e25f3 | [
"MIT"
] | null | null | null | RealTournament/include/RealTournament/Weapon.h | willcassella/RealTournament | 70ed3c0d5cbb67938ec8f86eec7b4d98a26e25f3 | [
"MIT"
] | null | null | null | // Weapon.h - Copyright 2013-2016 Will Cassella, All Rights Reserved
#pragma once
#include <Core/Reflection/SubClassOf.h>
#include <Engine/Handle.h>
#include <Engine/Entity.h>
#include <Engine/Components/Rendering/StaticMeshComponent.h>
#include <Engine/Components/Rendering/AnimationComponent.h>
namespace real_tournament
{
using namespace willow;
class Weapon : public Entity
{
///////////////////////
/// Information ///
public:
REFLECTABLE_CLASS
EXTENDS(Entity)
//////////////////
/// Fields ///
public:
/** The model to use for the weapon. */
Handle<StaticMeshComponent> model;
/** Animation to use for the weapon. */
Handle<AnimationComponent> animation;
/** The type of projectile to fire. */
SubClassOf<Entity> projectile;
/** The ammount of ammo this weapon can contain. */
uint32 magazine_size = 32;
/** The ammount of ammo currently loaded in this weapon. */
uint32 ammo = magazine_size;
//////////////////
/// Fields ///
public:
virtual void fire() = 0;
};
}
| 21.22449 | 68 | 0.653846 | [
"model"
] |
d64820a2f74d0cd3d5b0df8a5b2da2a78fdf7eb9 | 1,061 | h | C | src/BinaryGraphWalker.h | xptree/NetSMF | 550da916b04b393de499e2ca5b13733d6a5e496d | [
"MIT"
] | 129 | 2019-02-25T15:24:38.000Z | 2022-01-20T07:50:34.000Z | src/classification/NetSMF/src/BinaryGraphWalker.h | fahrbach/faster-graph-embeddings | c139c53a57e8888561c7965f3879d5896f92eba0 | [
"MIT"
] | 6 | 2019-06-19T20:14:41.000Z | 2020-05-28T08:58:27.000Z | src/BinaryGraphWalker.h | xptree/NetSMF | 550da916b04b393de499e2ca5b13733d6a5e496d | [
"MIT"
] | 26 | 2019-05-14T01:19:38.000Z | 2021-03-23T05:39:21.000Z | #pragma once
#include "GraphWalker.h"
class BinaryGraphWalker : public GraphWalker {
public:
static BinaryGraphWalker* getWalker(const std::string& name, int T);
BinaryGraphWalker(const std::vector<VertexId>& indices,
const std::vector<VertexId>& indptr, int T,
const std::vector<float>& degree);
void samplePath(VertexId u, VertexId v, int r, unsigned* seed,
std::vector<VertexPair>& sampled_pair) const;
VertexId randomWalk(VertexId u, int step, unsigned* seed) const;
void sampling(int round, int num_threads,
const std::string& machine,
int check_point);
// void transformation();
// void redsvd();
// void merge_to_sparsifier(const std::vector<VertexPairCount>& counter);
// static void dump(const std::string& filename,
// const std::vector<VertexPairCount>& counter);
static float merge(const std::vector<ValuedVertexPair>& counter,
std::vector<ValuedVertexPair>& tmp,
std::vector<VertexPair>& sampled_pairs);
};
| 36.586207 | 77 | 0.666352 | [
"vector"
] |
d64ba6ccf0ee4809ffce675e340484d5a1f58fca | 28,290 | c | C | lightningd/options.c | jl777/lightning | 7a16c90cdb485385e28669a8ec834dc37c91ce60 | [
"MIT"
] | 5 | 2017-12-30T19:20:16.000Z | 2019-06-02T04:47:56.000Z | lightningd/options.c | sg777/lightning | 1fff3a06969eb29d334c729c9c4b7852edf33911 | [
"MIT"
] | 4 | 2017-11-09T09:01:14.000Z | 2019-04-29T17:50:57.000Z | lightningd/options.c | jl777/lightning | 7a16c90cdb485385e28669a8ec834dc37c91ce60 | [
"MIT"
] | 7 | 2017-08-25T01:32:54.000Z | 2019-01-02T20:40:42.000Z | #include <bitcoin/chainparams.h>
#include <ccan/array_size/array_size.h>
#include <ccan/err/err.h>
#include <ccan/mem/mem.h>
#include <ccan/opt/opt.h>
#include <ccan/opt/private.h>
#include <ccan/read_write_all/read_write_all.h>
#include <ccan/short_types/short_types.h>
#include <ccan/tal/grab_file/grab_file.h>
#include <ccan/tal/path/path.h>
#include <ccan/tal/str/str.h>
#include <common/configdir.h>
#include <common/json_escaped.h>
#include <common/memleak.h>
#include <common/version.h>
#include <common/wireaddr.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <lightningd/bitcoind.h>
#include <lightningd/chaintopology.h>
#include <lightningd/jsonrpc.h>
#include <lightningd/lightningd.h>
#include <lightningd/log.h>
#include <lightningd/netaddress.h>
#include <lightningd/opt_time.h>
#include <lightningd/options.h>
#include <lightningd/subd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <wire/wire.h>
bool deprecated_apis = true;
/* Tal wrappers for opt. */
static void *opt_allocfn(size_t size)
{
return tal_alloc_(NULL, size, false, false, TAL_LABEL("opt_allocfn", ""));
}
static void *tal_reallocfn(void *ptr, size_t size)
{
if (!ptr) {
/* realloc(NULL) call is to allocate opt_table */
static bool opt_table_alloced = false;
if (!opt_table_alloced) {
opt_table_alloced = true;
return notleak(opt_allocfn(size));
}
return opt_allocfn(size);
}
tal_resize_(&ptr, 1, size, false);
return ptr;
}
static void tal_freefn(void *ptr)
{
tal_free(ptr);
}
/* FIXME: Put into ccan/time. */
#define TIME_FROM_SEC(sec) { { .tv_nsec = 0, .tv_sec = sec } }
#define TIME_FROM_MSEC(msec) \
{ { .tv_nsec = ((msec) % 1000) * 1000000, .tv_sec = (msec) / 1000 } }
static char *opt_set_u64(const char *arg, u64 *u)
{
char *endp;
unsigned long long l;
assert(arg != NULL);
/* This is how the manpage says to do it. Yech. */
errno = 0;
l = strtoull(arg, &endp, 0);
if (*endp || !arg[0])
return tal_fmt(NULL, "'%s' is not a number", arg);
*u = l;
if (errno || *u != l)
return tal_fmt(NULL, "'%s' is out of range", arg);
return NULL;
}
static char *opt_set_u32(const char *arg, u32 *u)
{
char *endp;
unsigned long l;
assert(arg != NULL);
/* This is how the manpage says to do it. Yech. */
errno = 0;
l = strtoul(arg, &endp, 0);
if (*endp || !arg[0])
return tal_fmt(NULL, "'%s' is not a number", arg);
*u = l;
if (errno || *u != l)
return tal_fmt(NULL, "'%s' is out of range", arg);
return NULL;
}
static char *opt_set_u16(const char *arg, u16 *u)
{
char *endp;
unsigned long l;
assert(arg != NULL);
/* This is how the manpage says to do it. Yech. */
errno = 0;
l = strtoul(arg, &endp, 0);
if (*endp || !arg[0])
return tal_fmt(NULL, "'%s' is not a number", arg);
*u = l;
if (errno || *u != l)
return tal_fmt(NULL, "'%s' is out of range", arg);
return NULL;
}
static char *opt_set_s32(const char *arg, s32 *u)
{
char *endp;
long l;
assert(arg != NULL);
/* This is how the manpage says to do it. Yech. */
errno = 0;
l = strtol(arg, &endp, 0);
if (*endp || !arg[0])
return tal_fmt(NULL, "'%s' is not a number", arg);
*u = l;
if (errno || *u != l)
return tal_fmt(NULL, "'%s' is out of range", arg);
return NULL;
}
static char *opt_add_ipaddr(const char *arg, struct lightningd *ld)
{
size_t n = tal_count(ld->wireaddrs);
char const *err_msg;
assert(arg != NULL);
tal_resize(&ld->wireaddrs, n+1);
if (!parse_wireaddr(arg, &ld->wireaddrs[n], ld->portnum, &err_msg)) {
return tal_fmt(NULL, "Unable to parse IP address '%s': %s", arg, err_msg);
}
return NULL;
}
static void opt_show_u64(char buf[OPT_SHOW_LEN], const u64 *u)
{
snprintf(buf, OPT_SHOW_LEN, "%"PRIu64, *u);
}
static void opt_show_u32(char buf[OPT_SHOW_LEN], const u32 *u)
{
snprintf(buf, OPT_SHOW_LEN, "%"PRIu32, *u);
}
static void opt_show_s32(char buf[OPT_SHOW_LEN], const s32 *u)
{
snprintf(buf, OPT_SHOW_LEN, "%"PRIi32, *u);
}
static void opt_show_u16(char buf[OPT_SHOW_LEN], const u16 *u)
{
snprintf(buf, OPT_SHOW_LEN, "%u", *u);
}
static char *opt_set_network(const char *arg, struct lightningd *ld)
{
assert(arg != NULL);
ld->topology->bitcoind->chainparams = chainparams_for_network(arg);
if (!ld->topology->bitcoind->chainparams)
return tal_fmt(NULL, "Unknown network name '%s'", arg);
return NULL;
}
static void opt_show_network(char buf[OPT_SHOW_LEN],
const struct lightningd *ld)
{
snprintf(buf, OPT_SHOW_LEN, "%s", get_chainparams(ld)->network_name);
}
static char *opt_set_rgb(const char *arg, struct lightningd *ld)
{
assert(arg != NULL);
ld->rgb = tal_free(ld->rgb);
/* BOLT #7:
*
* the first byte of `rgb` is the red value, the second byte is the
* green value and the last byte is the blue value */
ld->rgb = tal_hexdata(ld, arg, strlen(arg));
if (!ld->rgb || tal_len(ld->rgb) != 3)
return tal_fmt(NULL, "rgb '%s' is not six hex digits", arg);
return NULL;
}
static char *opt_set_alias(const char *arg, struct lightningd *ld)
{
assert(arg != NULL);
ld->alias = tal_free(ld->alias);
/* BOLT #7:
*
* * [`32`:`alias`]
*...
* It MUST set `alias` to a valid UTF-8 string, with any `alias` bytes
* following equal to zero.
*/
if (strlen(arg) > 32)
return tal_fmt(NULL, "Alias '%s' is over 32 characters", arg);
ld->alias = tal_arrz(ld, u8, 33);
strncpy((char*)ld->alias, arg, 32);
return NULL;
}
static char *opt_set_fee_rates(const char *arg, struct chain_topology *topo)
{
tal_free(topo->override_fee_rate);
topo->override_fee_rate = tal_arr(topo, u32, 3);
for (size_t i = 0; i < tal_count(topo->override_fee_rate); i++) {
char *endp;
char term;
if (i == tal_count(topo->override_fee_rate)-1)
term = '\0';
else
term = '/';
topo->override_fee_rate[i] = strtol(arg, &endp, 10);
if (endp == arg || *endp != term)
return tal_fmt(NULL,
"Feerates must be <num>/<num>/<num>");
arg = endp + 1;
}
return NULL;
}
static char *opt_set_offline(struct lightningd *ld)
{
ld->portnum = 0;
ld->no_reconnect = true;
return NULL;
}
static void config_register_opts(struct lightningd *ld)
{
opt_register_noarg("--daemon", opt_set_bool, &ld->daemon,
"Run in the background, suppress stdout/stderr");
opt_register_arg("--ignore-fee-limits", opt_set_bool_arg, opt_show_bool,
&ld->config.ignore_fee_limits,
"(DANGEROUS) allow peer to set any feerate");
opt_register_arg("--locktime-blocks", opt_set_u32, opt_show_u32,
&ld->config.locktime_blocks,
"Blocks before peer can unilaterally spend funds");
opt_register_arg("--max-locktime-blocks", opt_set_u32, opt_show_u32,
&ld->config.locktime_max,
"Maximum blocks a peer can lock up our funds");
opt_register_arg("--anchor-onchain", opt_set_u32, opt_show_u32,
&ld->config.anchor_onchain_wait,
"Blocks before we give up on pending anchor transaction");
opt_register_arg("--anchor-confirms", opt_set_u32, opt_show_u32,
&ld->config.anchor_confirms,
"Confirmations required for anchor transaction");
opt_register_arg("--max-anchor-confirms", opt_set_u32, opt_show_u32,
&ld->config.anchor_confirms_max,
"Maximum confirmations other side can wait for anchor transaction");
opt_register_arg("--commit-fee-min=<percent>", opt_set_u32, opt_show_u32,
&ld->config.commitment_fee_min_percent,
"Minimum percentage of fee to accept for commitment");
opt_register_arg("--commit-fee-max=<percent>", opt_set_u32, opt_show_u32,
&ld->config.commitment_fee_max_percent,
"Maximum percentage of fee to accept for commitment (0 for unlimited)");
opt_register_arg("--commit-fee=<percent>", opt_set_u32, opt_show_u32,
&ld->config.commitment_fee_percent,
"Percentage of fee to request for their commitment");
opt_register_arg("--override-fee-rates", opt_set_fee_rates, NULL,
ld->topology,
"Force a specific rates (immediate/normal/slow) in satoshis per kw regardless of estimated fees");
opt_register_arg("--default-fee-rate", opt_set_u32, opt_show_u32,
&ld->topology->default_fee_rate,
"Satoshis per kw if can't estimate fees");
opt_register_arg("--cltv-delta", opt_set_u32, opt_show_u32,
&ld->config.cltv_expiry_delta,
"Number of blocks for ctlv_expiry_delta");
opt_register_arg("--cltv-final", opt_set_u32, opt_show_u32,
&ld->config.cltv_final,
"Number of blocks for final ctlv_expiry");
opt_register_arg("--max-htlc-expiry", opt_set_u32, opt_show_u32,
&ld->config.max_htlc_expiry,
"Maximum number of blocks to accept an HTLC before expiry");
opt_register_arg("--bitcoind-poll", opt_set_time, opt_show_time,
&ld->config.poll_time,
"Time between polling for new transactions");
opt_register_arg("--commit-time", opt_set_time, opt_show_time,
&ld->config.commit_time,
"Time after changes before sending out COMMIT");
opt_register_arg("--fee-base", opt_set_u32, opt_show_u32,
&ld->config.fee_base,
"Millisatoshi minimum to charge for HTLC");
opt_register_arg("--fee-per-satoshi", opt_set_s32, opt_show_s32,
&ld->config.fee_per_satoshi,
"Microsatoshi fee for every satoshi in HTLC");
opt_register_arg("--ipaddr", opt_add_ipaddr, NULL,
ld,
"Set the IP address (v4 or v6) to announce to the network for incoming connections");
opt_register_noarg("--offline", opt_set_offline, ld,
"Start in offline-mode (do not automatically reconnect and do not accept incoming connections");
opt_register_early_arg("--network", opt_set_network, opt_show_network,
ld,
"Select the network parameters (bitcoin, testnet,"
" regtest, litecoin or litecoin-testnet)");
opt_register_arg("--allow-deprecated-apis",
opt_set_bool_arg, opt_show_bool,
&deprecated_apis,
"Enable deprecated options, JSONRPC commands, fields, etc.");
opt_register_arg("--debug-subdaemon-io",
opt_set_charp, NULL, &ld->debug_subdaemon_io,
"Enable full peer IO logging in subdaemons ending in this string (can also send SIGUSR1 to toggle)");
opt_register_arg("--autocleaninvoice-cycle",
opt_set_u64, opt_show_u64,
&ld->ini_autocleaninvoice_cycle,
"Perform cleanup of expired invoices every given seconds, or do not autoclean if 0");
opt_register_arg("--autocleaninvoice-expired-by",
opt_set_u64, opt_show_u64,
&ld->ini_autocleaninvoice_cycle,
"If expired invoice autoclean enabled, invoices that have expired for at least this given seconds are cleaned");
}
#if DEVELOPER
static char *opt_set_hsm_seed(const char *arg, struct lightningd *ld)
{
assert(arg != NULL);
ld->dev_hsm_seed = tal_hexdata(ld, arg, strlen(arg));
if (ld->dev_hsm_seed)
return NULL;
return tal_fmt(NULL, "bad hex string '%s'", arg);
}
static void dev_register_opts(struct lightningd *ld)
{
opt_register_noarg("--dev-no-reconnect", opt_set_bool,
&ld->no_reconnect,
"Disable automatic reconnect attempts");
opt_register_noarg("--dev-fail-on-subdaemon-fail", opt_set_bool,
&ld->dev_subdaemon_fail, opt_hidden);
opt_register_arg("--dev-debugger=<subdaemon>", opt_subd_debug, NULL,
ld, "Wait for gdb attach at start of <subdaemon>");
opt_register_arg("--dev-broadcast-interval=<ms>", opt_set_uintval,
opt_show_uintval, &ld->config.broadcast_interval,
"Time between gossip broadcasts in milliseconds");
opt_register_arg("--dev-disconnect=<filename>", opt_subd_dev_disconnect,
NULL, ld, "File containing disconnection points");
opt_register_arg("--dev-hsm-seed=<seed>", opt_set_hsm_seed,
NULL, ld, "Hex-encoded seed for HSM");
}
#endif
static const struct config testnet_config = {
/* 6 blocks to catch cheating attempts. */
.locktime_blocks = 6,
/* They can have up to 3 days. */
.locktime_max = 3 * 6 * 24,
/* Testnet can have long runs of empty blocks. */
.anchor_onchain_wait = 100,
/* We're fairly trusting, under normal circumstances. */
.anchor_confirms = 1,
/* More than 10 confirms seems overkill. */
.anchor_confirms_max = 10,
/* Testnet fees are crazy, allow infinite feerange. */
.commitment_fee_min_percent = 0,
.commitment_fee_max_percent = 0,
/* We offer to pay 5 times 2-block fee */
.commitment_fee_percent = 500,
/* Be aggressive on testnet. */
.cltv_expiry_delta = 6,
.cltv_final = 6,
/* Don't lock up channel for more than 5 days. */
.max_htlc_expiry = 5 * 6 * 24,
/* How often to bother bitcoind. */
.poll_time = TIME_FROM_SEC(1),
/* Send commit 10msec after receiving; almost immediately. */
.commit_time = TIME_FROM_MSEC(10),
/* Allow dust payments */
.fee_base = 1,
/* Take 0.001% */
.fee_per_satoshi = 1,
/* BOLT #7:
* Each node SHOULD flush outgoing announcements once every 60 seconds */
.broadcast_interval = 60000,
/* Send a keepalive update at least every week, prune every twice that */
.channel_update_interval = 1209600/2,
/* Testnet sucks */
.ignore_fee_limits = true,
};
/* aka. "Dude, where's my coins?" */
static const struct config mainnet_config = {
/* ~one day to catch cheating attempts. */
.locktime_blocks = 6 * 60 * 24,
/* They can have up to 3 days. */
.locktime_max = 3 * 6 * 60 * 24,
/* You should get in within 10 blocks. */
.anchor_onchain_wait = 10,
/* We're fairly trusting, under normal circumstances. */
.anchor_confirms = 3,
/* More than 10 confirms seems overkill. */
.anchor_confirms_max = 10,
/* Insist between 2 and 20 times the 2-block fee. */
.commitment_fee_min_percent = 200,
.commitment_fee_max_percent = 2000,
/* We offer to pay 5 times 2-block fee */
.commitment_fee_percent = 500,
/* BOLT #2:
*
* The `cltv_expiry_delta` for channels. `3R+2G+2S` */
/* R = 2, G = 1, S = 3 */
.cltv_expiry_delta = 14,
/* BOLT #2:
*
* The minimum `cltv_expiry` we will accept for terminal payments: the
* worst case for the terminal node C lower at `2R+G+S` blocks */
.cltv_final = 8,
/* Don't lock up channel for more than 5 days. */
.max_htlc_expiry = 5 * 6 * 60 * 24,
/* How often to bother bitcoind. */
.poll_time = TIME_FROM_SEC(1),
/* Send commit 10msec after receiving; almost immediately. */
.commit_time = TIME_FROM_MSEC(5),
/* Discourage dust payments */
.fee_base = 1000,
/* Take 0.001% */
.fee_per_satoshi = 1,
/* BOLT #7:
* Each node SHOULD flush outgoing announcements once every 60 seconds */
.broadcast_interval = 60000,
/* Send a keepalive update at least every week, prune every twice that */
.channel_update_interval = 1209600/2,
/* Mainnet should have more stable fees */
.ignore_fee_limits = false,
};
static void check_config(struct lightningd *ld)
{
/* We do this by ensuring it's less than the minimum we would accept. */
if (ld->config.commitment_fee_max_percent != 0
&& ld->config.commitment_fee_max_percent
< ld->config.commitment_fee_min_percent)
fatal("Commitment fee invalid min-max %u-%u",
ld->config.commitment_fee_min_percent,
ld->config.commitment_fee_max_percent);
if (ld->config.anchor_confirms == 0)
fatal("anchor-confirms must be greater than zero");
}
static void setup_default_config(struct lightningd *ld)
{
if (get_chainparams(ld)->testnet)
ld->config = testnet_config;
else
ld->config = mainnet_config;
/* Set default PID file name to be per-network */
tal_free(ld->pidfile);
ld->pidfile = tal_fmt(ld, "lightningd-%s.pid", get_chainparams(ld)->network_name);
}
/* FIXME: make this nicer! */
static int config_parse_line_number = 0;
static void config_log_stderr_exit(const char *fmt, ...)
{
char *msg;
va_list ap;
va_start(ap, fmt);
/* This is the format we expect:*/
if (streq(fmt, "%s: %.*s: %s")) {
const char *argv0 = va_arg(ap, const char *);
unsigned int len = va_arg(ap, unsigned int);
const char *arg = va_arg(ap, const char *);
const char *problem = va_arg(ap, const char *);
assert(argv0 != NULL);
assert(arg != NULL);
assert(problem != NULL);
/*mangle it to remove '--' and add the line number.*/
msg = tal_fmt(NULL, "%s line %d: %.*s: %s",
argv0, config_parse_line_number, len-2, arg+2, problem);
} else {
msg = tal_vfmt(NULL, fmt, ap);
}
va_end(ap);
fatal("%s", msg);
}
/* We turn the config file into cmdline arguments. */
static void opt_parse_from_config(struct lightningd *ld)
{
char *contents, **lines;
char **all_args; /*For each line: either argument string or NULL*/
char *argv[3];
int i, argc;
contents = grab_file(ld, "config");
/* Doesn't have to exist. */
if (!contents) {
if (errno != ENOENT)
fatal("Opening and reading config: %s",
strerror(errno));
/* Now we can set up defaults, since no config file. */
setup_default_config(ld);
return;
}
lines = tal_strsplit(contents, contents, "\r\n", STR_NO_EMPTY);
/* We have to keep all_args around, since opt will point into it */
all_args = tal_arr(ld, char *, tal_count(lines) - 1);
for (i = 0; i < tal_count(lines) - 1; i++) {
if (strstarts(lines[i], "#")) {
all_args[i] = NULL;
}
else {
/* Only valid forms are "foo" and "foo=bar" */
all_args[i] = tal_fmt(all_args, "--%s", lines[i]);
}
}
/*
For each line we construct a fake argc,argv commandline.
argv[1] is the only element that changes between iterations.
*/
argc = 2;
argv[0] = "lightning config file";
argv[argc] = NULL;
for (i = 0; i < tal_count(all_args); i++) {
if(all_args[i] != NULL) {
config_parse_line_number = i + 1;
argv[1] = all_args[i];
opt_early_parse(argc, argv, config_log_stderr_exit);
}
}
/* Now we can set up defaults, depending on whether testnet or not */
setup_default_config(ld);
for (i = 0; i < tal_count(all_args); i++) {
if(all_args[i] != NULL) {
config_parse_line_number = i + 1;
argv[1] = all_args[i];
opt_parse(&argc, argv, config_log_stderr_exit);
argc = 2; /* opt_parse might have changed it */
}
}
tal_free(contents);
}
static char *test_daemons_and_exit(struct lightningd *ld)
{
test_daemons(ld);
exit(0);
return NULL;
}
void register_opts(struct lightningd *ld)
{
opt_set_alloc(opt_allocfn, tal_reallocfn, tal_freefn);
opt_register_early_noarg("--help|-h", opt_usage_and_exit,
"\n"
"A bitcoin lightning daemon.",
"Print this message.");
opt_register_early_noarg("--test-daemons-only",
test_daemons_and_exit,
ld, opt_hidden);
/* --port needs to be an early arg to force it being parsed
* before --ipaddr which may depend on it */
opt_register_early_arg("--port", opt_set_u16, opt_show_u16, &ld->portnum,
"Port to bind to (0 means don't listen)");
opt_register_arg("--bitcoin-datadir", opt_set_talstr, NULL,
&ld->topology->bitcoind->datadir,
"-datadir arg for bitcoin-cli");
opt_register_arg("--rgb", opt_set_rgb, NULL, ld,
"RRGGBB hex color for node");
opt_register_arg("--alias", opt_set_alias, NULL, ld,
"Up to 32-byte alias for node");
opt_register_arg("--bitcoin-cli", opt_set_talstr, NULL,
&ld->topology->bitcoind->cli,
"bitcoin-cli pathname");
opt_register_arg("--bitcoin-rpcuser", opt_set_talstr, NULL,
&ld->topology->bitcoind->rpcuser,
"bitcoind RPC username");
opt_register_arg("--bitcoin-rpcpassword", opt_set_talstr, NULL,
&ld->topology->bitcoind->rpcpass,
"bitcoind RPC password");
opt_register_arg("--bitcoin-rpcconnect", opt_set_talstr, NULL,
&ld->topology->bitcoind->rpcconnect,
"bitcoind RPC host to connect to");
opt_register_arg("--bitcoin-rpcport", opt_set_talstr, NULL,
&ld->topology->bitcoind->rpcport,
"bitcoind RPC port");
opt_register_arg("--pid-file=<file>", opt_set_talstr, opt_show_charp,
&ld->pidfile,
"Specify pid file");
opt_register_arg(
"--channel-update-interval=<s>", opt_set_u32, opt_show_u32,
&ld->config.channel_update_interval,
"Time in seconds between channel updates for our own channels.");
opt_register_logging(ld);
opt_register_version();
configdir_register_opts(ld, &ld->config_dir, &ld->rpc_filename);
config_register_opts(ld);
#if DEVELOPER
dev_register_opts(ld);
#endif
}
/* Names stolen from https://github.com/ternus/nsaproductgenerator/blob/master/nsa.js */
static const char *codename_adjective[]
= { "LOUD", "RED", "BLUE", "GREEN", "YELLOW", "IRATE", "ANGRY", "PEEVED",
"HAPPY", "SLIMY", "SLEEPY", "JUNIOR", "SLICKER", "UNITED", "SOMBER",
"BIZARRE", "ODD", "WEIRD", "WRONG", "LATENT", "CHILLY", "STRANGE", "LOUD",
"SILENT", "HOPPING", "ORANGE", "VIOLET", "VIOLENT", "LIGHTNING" };
static const char *codename_noun[]
= { "WHISPER", "FELONY", "MOON", "SUCKER", "PENGUIN", "WAFFLE", "MAESTRO",
"NIGHT", "TRINITY", "DEITY", "MONKEY", "ARK", "SQUIRREL", "IRON", "BOUNCE",
"FARM", "CHEF", "TROUGH", "NET", "TRAWL", "GLEE", "WATER", "SPORK", "PLOW",
"FEED", "SOUFFLE", "ROUTE", "BAGEL", "MONTANA", "ANALYST", "AUTO", "WATCH",
"PHOTO", "YARD", "SOURCE", "MONKEY", "SEAGULL", "TOLL", "SPAWN", "GOPHER",
"CHIPMUNK", "SET", "CALENDAR", "ARTIST", "CHASER", "SCAN", "TOTE", "BEAM",
"ENTOURAGE", "GENESIS", "WALK", "SPATULA", "RAGE", "FIRE", "MASTER" };
void setup_color_and_alias(struct lightningd *ld)
{
u8 der[PUBKEY_DER_LEN];
pubkey_to_der(der, &ld->id);
if (!ld->rgb)
/* You can't get much red by default */
ld->rgb = tal_dup_arr(ld, u8, der, 3, 0);
if (!ld->alias) {
u64 adjective, noun;
char *name;
memcpy(&adjective, der+3, sizeof(adjective));
memcpy(&noun, der+3+sizeof(adjective), sizeof(noun));
noun %= ARRAY_SIZE(codename_noun);
adjective %= ARRAY_SIZE(codename_adjective);
/* Only use 32 characters */
name = tal_fmt(ld, "%s%s-",
codename_adjective[adjective],
codename_noun[noun]);
#if DEVELOPER
assert(strlen(name) < 32);
int taillen = 32 - strlen(name);
if (taillen > strlen(version()))
taillen = strlen(version());
/* Fit as much of end of version() as possible */
tal_append_fmt(&name, "%s",
version() + strlen(version()) - taillen);
#endif
assert(strlen(name) <= 32);
ld->alias = tal_arrz(ld, u8, 33);
strcpy((char*)ld->alias, name);
tal_free(name);
}
}
bool handle_opts(struct lightningd *ld, int argc, char *argv[])
{
bool newdir = false;
/* Load defaults first, so that --help (in early options) has something
* to display. The actual values loaded here, will be overwritten later
* by opt_parse_from_config. */
setup_default_config(ld);
/* Get any configdir/testnet options first. */
opt_early_parse(argc, argv, opt_log_stderr_exit);
/* Move to config dir, to save ourselves the hassle of path manip. */
if (chdir(ld->config_dir) != 0) {
log_unusual(ld->log, "Creating configuration directory %s",
ld->config_dir);
if (mkdir(ld->config_dir, 0700) != 0)
fatal("Could not make directory %s: %s",
ld->config_dir, strerror(errno));
if (chdir(ld->config_dir) != 0)
fatal("Could not change directory %s: %s",
ld->config_dir, strerror(errno));
newdir = true;
}
/* Now look for config file */
opt_parse_from_config(ld);
opt_parse(&argc, argv, opt_log_stderr_exit);
if (argc != 1)
errx(1, "no arguments accepted");
check_config(ld);
if (ld->portnum && tal_count(ld->wireaddrs) == 0)
guess_addresses(ld);
else
log_debug(ld->log, "Not guessing addresses: %s",
ld->portnum ? "manually set" : "port set to zero");
#if DEVELOPER
if (ld->dev_hsm_seed) {
int fd;
unlink("hsm_secret");
fd = open("hsm_secret", O_CREAT|O_WRONLY, 0400);
if (fd < 0 ||
!write_all(fd, ld->dev_hsm_seed, tal_len(ld->dev_hsm_seed))
|| fsync(fd) != 0)
fatal("dev-hsm-seed: Could not write file: %s",
strerror(errno));
close(fd);
}
#endif
return newdir;
}
/* FIXME: This is a hack! Expose somehow in ccan/opt.*/
/* Returns string after first '-'. */
static const char *first_name(const char *names, unsigned *len)
{
*len = strcspn(names + 1, "|= ");
return names + 1;
}
static const char *next_name(const char *names, unsigned *len)
{
names += *len;
if (names[0] == ' ' || names[0] == '=' || names[0] == '\0')
return NULL;
return first_name(names + 1, len);
}
static void add_config(struct lightningd *ld,
struct json_result *response,
const struct opt_table *opt,
const char *name, size_t len)
{
char *name0 = tal_strndup(response, name, len);
const char *answer = NULL;
if (opt->type & OPT_NOARG) {
if (opt->cb == (void *)opt_usage_and_exit
|| opt->cb == (void *)version_and_exit
|| opt->cb == (void *)opt_set_offline /* will show up as port=0 and --no-reconnect */
|| opt->cb == (void *)test_daemons_and_exit) {
/* These are not important */
} else if (opt->cb == (void *)opt_set_bool) {
const bool *b = opt->u.carg;
answer = tal_fmt(name0, "%s", *b ? "true" : "false");
} else {
/* Insert more decodes here! */
abort();
}
} else if (opt->type & OPT_HASARG) {
if (opt->show) {
char *buf = tal_arr(name0, char, OPT_SHOW_LEN+1);
opt->show(buf, opt->u.carg);
if (streq(buf, "true") || streq(buf, "false")
|| strspn(buf, "0123456789.") == strlen(buf)) {
/* Let pure numbers and true/false through as
* literals. */
json_add_literal(response, name0,
buf, strlen(buf));
return;
}
/* opt_show_charp surrounds with "", strip them */
if (strstarts(buf, "\"")) {
buf[strlen(buf)-1] = '\0';
answer = buf + 1;
} else
answer = buf;
} else if (opt->cb_arg == (void *)opt_set_talstr
|| opt->cb_arg == (void *)opt_set_charp) {
const char *arg = *(char **)opt->u.carg;
if (arg)
answer = tal_fmt(name0, "%s", arg);
} else if (opt->cb_arg == (void *)opt_set_rgb) {
if (ld->rgb)
answer = tal_hexstr(name0, ld->rgb, 3);
} else if (opt->cb_arg == (void *)opt_set_alias) {
answer = (const char *)ld->alias;
} else if (opt->cb_arg == (void *)arg_log_to_file) {
answer = ld->logfile;
} else if (opt->cb_arg == (void *)opt_set_fee_rates) {
struct chain_topology *topo = ld->topology;
if (topo->override_fee_rate)
answer = tal_fmt(name0, "%u/%u/%u",
topo->override_fee_rate[0],
topo->override_fee_rate[1],
topo->override_fee_rate[2]);
} else if (opt->cb_arg == (void *)opt_add_ipaddr) {
/* This is a bit weird, we can have multiple args */
for (size_t i = 0; i < tal_count(ld->wireaddrs); i++) {
json_add_string(response,
name0,
fmt_wireaddr(name0,
ld->wireaddrs+i));
}
return;
#if DEVELOPER
} else if (strstarts(name, "dev-")) {
/* Ignore dev settings */
#endif
} else {
/* Insert more decodes here! */
abort();
}
}
if (answer) {
struct json_escaped *esc = json_escape(NULL, answer);
json_add_escaped_string(response, name0, take(esc));
}
tal_free(name0);
}
static void json_listconfigs(struct command *cmd,
const char *buffer, const jsmntok_t *params)
{
size_t i;
struct json_result *response = new_json_result(cmd);
jsmntok_t *configtok;
bool found = false;
if (!json_get_params(cmd, buffer, params, "?config", &configtok, NULL)) {
return;
}
json_object_start(response, NULL);
if (!configtok)
json_add_string(response, "# version", version());
for (i = 0; i < opt_count; i++) {
unsigned int len;
const char *name;
/* FIXME: Print out comment somehow? */
if (opt_table[i].type == OPT_SUBTABLE)
continue;
for (name = first_name(opt_table[i].names, &len);
name;
name = next_name(name, &len)) {
/* Skips over first -, so just need to look for one */
if (name[0] != '-')
continue;
if (configtok
&& !memeq(buffer + configtok->start,
configtok->end - configtok->start,
name + 1, len - 1))
continue;
found = true;
add_config(cmd->ld, response, &opt_table[i],
name+1, len-1);
}
}
json_object_end(response);
if (configtok && !found) {
command_fail(cmd, "Unknown config option '%.*s'",
configtok->end - configtok->start,
buffer + configtok->start);
return;
}
command_success(cmd, response);
}
static const struct json_command listconfigs_command = {
"listconfigs",
json_listconfigs,
"List all configuration options, or with [config], just that one.",
.verbose = "listconfigs [config]\n"
"Outputs an object, with each field a config options\n"
"(Option names which start with # are comments)\n"
"With [config], object only has that field"
};
AUTODATA(json_command, &listconfigs_command);
| 29.747634 | 116 | 0.670201 | [
"object"
] |
d64ccd043133bb6a20b09c5d743a36db6c4c9000 | 5,496 | h | C | src/bls/baseBLS.h | jonspock/tessa | 1a1b64b05510dffa8221b193b014dc7ccb9fbe4a | [
"Apache-2.0",
"MIT"
] | null | null | null | src/bls/baseBLS.h | jonspock/tessa | 1a1b64b05510dffa8221b193b014dc7ccb9fbe4a | [
"Apache-2.0",
"MIT"
] | null | null | null | src/bls/baseBLS.h | jonspock/tessa | 1a1b64b05510dffa8221b193b014dc7ccb9fbe4a | [
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018 The TessaChain developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Why base-BLS instead of standard base-64 encoding?
* - Don't want 0OIl characters that look the same in some fonts and
* could be used to create visually identical looking account numbers.
* - A string with non-alphanumeric characters is not as easily accepted as an account number.
* - E-mail usually won't line-break if there's no punctuation to break at.
* - Double-clicking selects the whole number as one word if it's all alphanumeric.
*/
#pragma once
#include "bls/key.h"
#include "bls/privkey.h"
#include "bls/pubkey.h"
#include "chainparams.h"
#include "script/script.h"
#include "script/standard.h"
#include "support/allocators/zeroafterfree.h"
#include <string>
#include <vector>
/**
* Encode a byte sequence as a baseBLS-encoded string.
* pbegin and pend cannot be nullptr, unless both are.
*/
std::string EncodeBaseBLS(const uint8_t* pbegin, const uint8_t* pend);
/**
* Encode a byte vector as a baseBLS-encoded string
*/
std::string EncodeBaseBLS(const std::vector<uint8_t>& vch);
/**
* Decode a baseBLS-encoded string (psz) into a byte vector (vchRet).
* return true if decoding is successful.
* psz cannot be nullptr.
*/
bool DecodeBaseBLS(const char* psz, std::vector<uint8_t>& vchRet);
/**
* Decode a baseBLS-encoded string (psz) into a string.
* psz cannot be nullptr.
*/
std::string DecodeBaseBLS(const char* psz);
/**
* Decode a baseBLS-encoded string (str) into a byte vector (vchRet).
* return true if decoding is successful.
*/
bool DecodeBaseBLS(const std::string& str, std::vector<uint8_t>& vchRet);
/**
* Encode a byte vector into a baseBLS-encoded string, including checksum
*/
std::string EncodeBaseBLSCheck(const std::vector<uint8_t>& vchIn);
/**
* Decode a baseBLS-encoded string (psz) that includes a checksum into a byte
* vector (vchRet), return true if decoding is successful
*/
inline bool DecodeBaseBLSCheck(const char* psz, std::vector<uint8_t>& vchRet);
/**
* Decode a baseBLS-encoded string (str) that includes a checksum into a byte
* vector (vchRet), return true if decoding is successful
*/
inline bool DecodeBaseBLSCheck(const std::string& str, std::vector<uint8_t>& vchRet);
/**
* Base class for all baseBLS-encoded data
*/
class CBaseBLSData {
protected:
//! the version byte(s)
std::vector<uint8_t> vchVersion;
//! the actually encoded data
typedef std::vector<uint8_t, zero_after_free_allocator<uint8_t> > vector_uchar;
vector_uchar vchData;
CBaseBLSData();
void SetData(const std::vector<uint8_t>& vchVersionIn, const void* pdata, size_t nSize);
void SetData(const std::vector<uint8_t>& vchVersionIn, const uint8_t* pbegin, const uint8_t* pend);
public:
bool SetString(const char* psz, unsigned int nVersionBytes = 1);
bool SetString(const std::string& str);
std::string ToString() const;
int CompareTo(const CBaseBLSData& bBLS) const;
bool operator==(const CBaseBLSData& bBLS) const { return CompareTo(bBLS) == 0; }
bool operator<=(const CBaseBLSData& bBLS) const { return CompareTo(bBLS) <= 0; }
bool operator>=(const CBaseBLSData& bBLS) const { return CompareTo(bBLS) >= 0; }
bool operator<(const CBaseBLSData& bBLS) const { return CompareTo(bBLS) < 0; }
bool operator>(const CBaseBLSData& bBLS) const { return CompareTo(bBLS) > 0; }
};
/** baseBLS-encoded Tessa addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CTessaAddress : public CBaseBLSData {
public:
bool Set(const bls::CKeyID& id);
bool Set(const CScriptID& id);
bool Set(const CTxDestination& dest);
bool IsValid() const;
bool IsValid(const CChainParams& params) const;
CTessaAddress() {}
CTessaAddress(const CTxDestination& dest) { Set(dest); }
CTessaAddress(const std::string& strAddress) { SetString(strAddress); }
CTessaAddress(const char* pszAddress) { SetString(pszAddress); }
CTxDestination Get() const;
bool GetKeyID(bls::CKeyID& keyID) const;
bool IsScript() const;
};
/**
* A baseBLS-encoded secret key
*/
class CTessaSecret : public CBaseBLSData {
public:
void SetKey(const bls::CKey& vchSecret);
bls::CKey GetKey();
bool IsValid() const;
bool SetString(const char* pszSecret);
bool SetString(const std::string& strSecret);
CTessaSecret(const bls::CKey& vchSecret) { SetKey(vchSecret); }
CTessaSecret() {}
};
template <typename K, int Size, CChainParams::BaseType Type> class CTessaExtKeyBase : public CBaseBLSData {
public:
void SetKey(const K& key) {
uint8_t vch[Size];
key.Encode(vch);
SetData(Params().Prefix(Type), vch, vch + Size);
}
K GetKey() {
K ret;
ret.Decode(&vchData[0], &vchData[Size]);
return ret;
}
CTessaExtKeyBase(const K& key) { SetKey(key); }
CTessaExtKeyBase() {}
};
typedef CTessaExtKeyBase<bls::CExtKey, 74, CChainParams::EXT_SECRET_KEY> CTessaExtKey;
typedef CTessaExtKeyBase<bls::CExtPubKey, 74, CChainParams::EXT_PUBLIC_KEY> CTessaExtPubKey;
| 32.91018 | 107 | 0.72671 | [
"vector"
] |
d656081f11ea9171904619103f857dd6d6c4d4c6 | 2,372 | h | C | ui/message_center/public/cpp/notifier_id.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | ui/message_center/public/cpp/notifier_id.h | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | ui/message_center/public/cpp/notifier_id.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_MESSAGE_CENTER_PUBLIC_CPP_NOTIFIER_ID_H_
#define UI_MESSAGE_CENTER_PUBLIC_CPP_NOTIFIER_ID_H_
#include <stddef.h>
#include <string>
#include <vector>
#include "base/macros.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/image/image.h"
#include "ui/message_center/public/cpp/message_center_public_export.h"
#include "url/gurl.h"
namespace message_center {
// This enum is being used for histogram reporting and the elements should not
// be re-ordered.
enum class NotifierType : int {
APPLICATION = 0,
ARC_APPLICATION = 1,
WEB_PAGE = 2,
SYSTEM_COMPONENT = 3,
CROSTINI_APPLICATION = 4,
PHONE_HUB = 5,
kMaxValue = PHONE_HUB,
};
// A struct that identifies the source of notifications. For example, a web page
// might send multiple notifications but they'd all have the same NotifierId.
struct MESSAGE_CENTER_PUBLIC_EXPORT NotifierId {
// Default constructor needed for generated mojom files and tests.
NotifierId();
// Constructor for non WEB_PAGE type.
NotifierId(NotifierType type, const std::string& id);
// Constructor for WEB_PAGE type.
explicit NotifierId(const GURL& url);
// Constructor for WEB_PAGE type. The |title| must only be populated when a
// trust relationship has been established, and it is appropriate to display
// this instead of the |url|'s origin for attribution.
NotifierId(const GURL& url, absl::optional<std::u16string> title);
NotifierId(const NotifierId& other);
~NotifierId();
bool operator==(const NotifierId& other) const;
// Allows NotifierId to be used as a key in std::map.
bool operator<(const NotifierId& other) const;
NotifierType type;
// The identifier of the app notifier. Empty if it's WEB_PAGE.
std::string id;
// The URL pattern of the notifier.
GURL url;
// The title provided by the app identifier. This is used by desktop web
// applications.
absl::optional<std::u16string> title;
// The identifier of the profile where the notification is created. This is
// used for ChromeOS multi-profile support and can be empty.
std::string profile_id;
};
} // namespace message_center
#endif // UI_MESSAGE_CENTER_PUBLIC_CPP_NOTIFIER_ID_H_
| 30.805195 | 80 | 0.747892 | [
"vector"
] |
9615b8b6933f6c4b5221416713e40e7dc606f566 | 50,198 | c | C | cupsfilters/pdftops.c | Bhavna2020/cups-filters | a431ad4fa8a03479729e499e6570eb4f42f5510b | [
"Apache-2.0"
] | 1 | 2021-03-17T07:37:07.000Z | 2021-03-17T07:37:07.000Z | cupsfilters/pdftops.c | Bhavna2020/cups-filters | a431ad4fa8a03479729e499e6570eb4f42f5510b | [
"Apache-2.0"
] | null | null | null | cupsfilters/pdftops.c | Bhavna2020/cups-filters | a431ad4fa8a03479729e499e6570eb4f42f5510b | [
"Apache-2.0"
] | null | null | null | /*
* PDF-to-PostScript filter function for cups-filters.
*
* Copyright 2011-2020 by Till Kamppeter
* Copyright 2007-2011 by Apple Inc.
* Copyright 1997-2006 by Easy Software Products.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more
* information.
*
* Contents:
*
* parsePDFTOPDFComment() - Check whether we are executed after pdftopdf
* remove_options() - Remove unwished entries from an option list
* log_command_line() - Log the command line of a program which we call
* pdftops() - pdftops filter function
*/
/*
* Include necessary headers...
*/
#include "filter.h"
#include "pdf.h"
#include <config.h>
#include <cups/cups.h>
#include <ppd/ppd.h>
#include <cups/file.h>
#include <signal.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <cupsfilters/filter.h>
#include <cupsfilters/image-private.h>
#define MAX_CHECK_COMMENT_LINES 20
/*
* Type definitions
*/
typedef unsigned renderer_t;
enum renderer_e {GS = 0, PDFTOPS = 1, ACROREAD = 2, PDFTOCAIRO = 3, MUPDF = 4,
HYBRID = 5};
/*
* When calling the "pstops" filter we exclude the following options from its
* command line as we have applied these options already to the PDF input,
* either on the "pdftops"/Ghostscript call in this filter or by use of the
* "pdftopdf" filter before this filter.
*/
const char *pstops_exclude_general[] = {
"crop-to-fit",
"fill",
"fitplot",
"fit-to-page",
"landscape",
"orientation-requested",
NULL
};
const char *pstops_exclude_page_management[] = {
"brightness",
"Collate",
"cupsEvenDuplex",
"gamma",
"hue",
"ipp-attribute-fidelity",
"MirrorPrint",
"mirror",
"multiple-document-handling",
"natural-scaling",
"number-up",
"number-up-layout",
"OutputOrder",
"page-border",
"page-bottom",
"page-label",
"page-left",
"page-ranges",
"page-right",
"page-set",
"page-top",
"position",
"saturation",
"scaling",
NULL
};
/*
* Check whether we were called after the "pdftopdf" filter and extract
* parameters passed over by "pdftopdf" in the header comments of the PDF
* file
*/
static void parsePDFTOPDFComment(char *filename, /* I - Input file */
int *pdftopdfapplied, /* O - Does the input
data come from
pdftopdf filter?*/
char *deviceCopies, /* O - Number of copies
(hardware) */
int *deviceCollate, /* O - Hardware collate*/
filter_logfunc_t log, /* I - Log function */
void *ld) /* I - Aux. data for
log function */
{
char buf[4096];
int i;
FILE *fp;
if ((fp = fopen(filename,"rb")) == NULL) {
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Cannot open input file \"%s\"",
filename);
return;
}
/* skip until PDF start header */
while (fgets(buf,sizeof(buf),fp) != 0) {
if (strncmp(buf,"%PDF",4) == 0) {
break;
}
}
for (i = 0;i < MAX_CHECK_COMMENT_LINES;i++) {
if (fgets(buf,sizeof(buf),fp) == 0) break;
if (strncmp(buf,"%%PDFTOPDFNumCopies",19) == 0) {
char *p;
p = strchr(buf+19,':') + 1;
while (*p == ' ' || *p == '\t') p++;
strncpy(deviceCopies, p, 31);
deviceCopies[31] = '\0';
p = deviceCopies + strlen(deviceCopies) - 1;
while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p--;
*(p + 1) = '\0';
*pdftopdfapplied = 1;
} else if (strncmp(buf,"%%PDFTOPDFCollate",17) == 0) {
char *p;
p = strchr(buf+17,':') + 1;
while (*p == ' ' || *p == '\t') p++;
if (strncasecmp(p,"true",4) == 0) {
*deviceCollate = 1;
} else {
*deviceCollate = 0;
}
*pdftopdfapplied = 1;
} else if (strcmp(buf,"% This file was generated by pdftopdf") == 0) {
*pdftopdfapplied = 1;
}
}
fclose(fp);
}
/*
* Check whether given file is empty
*/
int /* O - Result: 1: Empty; 0: Contains pages */
is_empty(char *filename, /* I - Input file */
filter_logfunc_t log, /* I - Log function */
void *ld) /* I - Auxiliary data for log function */
{
FILE *fp = NULL;
fp = fopen(filename, "rb");
if (fp == NULL)
{
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Cannot open input file \"%s\"",
filename);
return 1;
}
else
{
char buf[1];
rewind(fp);
if (fread(buf, 1, 1, fp) == 0) {
fclose(fp);
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Input is empty, outputting empty file.");
return 1;
}
fclose(fp);
int pages = pdf_pages(filename);
if (pages == 0) {
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: No pages left, outputting empty file.");
return 1;
}
if (pages > 0)
return 0;
return 1;
}
}
/*
* Before calling any command line utility, log its command line in CUPS'
* debug mode
*/
void
log_command_line(const char* file, /* I - Program to be executed */
char *const argv[], /* I - Argument list */
filter_logfunc_t log, /* I - Log function */
void *ld) /* I - Auxiliary data for log function */
{
int i;
char *apos;
char buf[32768];
if (log == NULL)
return;
/* Debug output: Full command line of program to be called */
snprintf(buf, sizeof(buf) - 1, "pdftops: Running command line for %s:",
(file ? file : argv[0]));
if (file)
snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf) - 1,
" %s", file);
for (i = (file ? 1 : 0); argv[i]; i ++) {
if ((strchr(argv[i],' ')) || (strchr(argv[i],'\t')))
apos = "'";
else
apos = "";
snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf) - 1,
" %s%s%s", apos, argv[i], apos);
}
buf[sizeof(buf) - 1] = '\0';
log(ld, FILTER_LOGLEVEL_DEBUG, "%s", buf);
}
/*
* 'pdftops()' - Filter function to convert PDF input into
* PostScript to be printed on PostScript printers
*/
int /* O - Error status */
pdftops(int inputfd, /* I - File descriptor input stream */
int outputfd, /* I - File descriptor output stream */
int inputseekable, /* I - Is input stream seekable? (unused) */
filter_data_t *data, /* I - Job and printer data */
void *parameters) /* I - Filter-specific parameters (unused) */
{
renderer_t renderer = CUPS_PDFTOPS_RENDERER; /* Renderer: gs or pdftops
or acroread or pdftocairo
or hybrid */
FILE *inputfp; /* Input file pointer */
int fd = 0; /* Copy file descriptor */
int i, j;
int pdftopdfapplied = 0; /* Input data from pdftopdf filter? */
char deviceCopies[32] = "1"; /* Hardware copies */
int deviceCollate = 0; /* Hardware collate */
char make_model[128] = ""; /* Printer make and model (for quirks)*/
char *filename, /* PDF file to convert */
tempfile[1024]; /* Temporary file */
char buffer[8192]; /* Copy buffer */
int bytes; /* Bytes copied */
int num_options, /* Number of options */
num_pstops_options; /* Number of options for pstops */
cups_option_t *options, /* Options */
*pstops_options, /* Options for pstops filter function */
*option;
const char *exclude;
filter_data_t pstops_filter_data;
int ret;
const char *val; /* Option value */
ppd_file_t *ppd; /* PPD file */
char resolution[128] = ""; /* Output resolution */
int xres = 0, yres = 0, /* resolution values */
mres, res,
maxres = CUPS_PDFTOPS_MAX_RESOLUTION,
/* Maximum image rendering resolution */
numvalues; /* Number of values actually read */
ppd_choice_t *choice;
ppd_attr_t *attr;
cups_page_header2_t header;
cups_file_t *fp; /* Post-processing input file */
int pdf_pid, /* Process ID for pdftops/gs */
pdf_argc = 0, /* Number of args for pdftops/gs */
pstops_pid, /* Process ID of pstops filter */
pstops_pipe[2], /* Pipe to pstops filter */
need_post_proc = 0, /* Post-processing needed? */
post_proc_pid = 0, /* Process ID of post-processing */
post_proc_pipe[2], /* Pipe to post-processing */
wait_children, /* Number of child processes left */
wait_pid, /* Process ID from wait() */
wait_status, /* Status from child */
exit_status = 0; /* Exit status */
int gray_output = 0; /* Checking for monochrome/grayscale PostScript output */
char *pdf_argv[100], /* Arguments for pdftops/gs */
*ptr; /* Pointer into value */
int duplex, tumble; /* Duplex settings for PPD-less
printing */
filter_logfunc_t log = data->logfunc;
void *ld = data->logdata;
filter_iscanceledfunc_t iscanceled = data->iscanceledfunc;
void *icd = data->iscanceleddata;
(void)inputseekable;
(void)parameters;
/*
* Ignore broken pipe signals...
*/
signal(SIGPIPE, SIG_IGN);
/*
* Open the input data stream specified by the inputfd...
*/
if ((inputfp = fdopen(inputfd, "r")) == NULL)
{
if (!iscanceled || !iscanceled(icd))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Unable to open input data stream.");
}
return (1);
}
/*
* Copy input into temporary file ...
*/
if ((fd = cupsTempFd(tempfile, sizeof(tempfile))) < 0)
{
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to copy PDF file: %s", strerror(errno));
return (1);
}
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Copying input to temp file \"%s\"",
tempfile);
while ((bytes = fread(buffer, 1, sizeof(buffer), inputfp)) > 0)
bytes = write(fd, buffer, bytes);
if (inputfd)
{
fclose(inputfp);
close(inputfd);
}
close(fd);
filename = tempfile;
/*
* Stop on empty or zero-pages files without error, perhaps we eliminated
* all pages via the "page-ranges" option and a previous filter
*/
if (is_empty(filename, log, ld))
{
unlink(tempfile);
return 0;
}
/*
* Read out copy counts and collate setting passed over by pdftopdf
*/
parsePDFTOPDFComment(filename, &pdftopdfapplied, deviceCopies,
&deviceCollate, log, ld);
/*
* CUPS option list
*/
num_options = data->num_options;
options = data->options;
ppd = data->ppd;
/*
* Process job options...
*/
if ((val = cupsGetOption("make-and-model", num_options, options)) != NULL)
{
strncpy(make_model, val, sizeof(make_model) - 1);
if (strlen(val) > 127)
make_model[127] = '\0';
for (ptr = make_model; *ptr; ptr ++)
if (*ptr == '-') *ptr = ' ';
}
else if (ppd)
{
snprintf(make_model, sizeof(make_model), "%s %s", ppd->manufacturer,
ppd->product + 1);
make_model[strlen(make_model) - 1] = '\0';
}
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Printer make and model: %s", make_model);
/*
* Select the PDF renderer: Ghostscript (gs), Poppler (pdftops),
* Adobe Reader (arcoread), Poppler with Cairo (pdftocairo), or
* Hybrid (hybrid, Poppler for Brother, Minolta, Konica Minolta, Dell, and
* old HP LaserJets and Ghostscript otherwise)
*/
if ((val = cupsGetOption("pdftops-renderer", num_options, options)) != NULL)
{
if (strcasecmp(val, "gs") == 0)
renderer = GS;
else if (strcasecmp(val, "pdftops") == 0)
renderer = PDFTOPS;
else if (strcasecmp(val, "acroread") == 0)
renderer = ACROREAD;
else if (strcasecmp(val, "pdftocairo") == 0)
renderer = PDFTOCAIRO;
else if (strcasecmp(val, "mupdf") == 0)
renderer = MUPDF;
else if (strcasecmp(val, "hybrid") == 0)
renderer = HYBRID;
else
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Invalid value for \"pdftops-renderer\": \"%s\"",
val);
}
if (renderer == HYBRID)
{
if (make_model[0] &&
(!strncasecmp(make_model, "Brother", 7) ||
!strncasecmp(make_model, "Dell", 4) ||
strcasestr(make_model, "Minolta") ||
(!strncasecmp(make_model, "Apple", 5) &&
(ptr = strcasestr(make_model, "LaserWriter")) &&
((ptr = strcasestr(ptr + 11, "4")) ||
(ptr = strcasestr(ptr + 11, "12")) ||
(ptr = strcasestr(ptr + 11, "16"))) &&
((ptr = strcasestr(ptr + 2, "600")) ||
(ptr = strcasestr(ptr + 2, "640")) ||
(ptr = strcasestr(ptr + 2, "660"))))))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Switching to Poppler's pdftops instead of "
"Ghostscript for Brother, Minolta, Konica Minolta, Dell, "
"and Apple LaserWriter 16/600, 4/600, 12/640, 12/600, "
"12/660 to work around bugs in the printer's PS "
"interpreters");
renderer = PDFTOPS;
}
else
renderer = GS;
/*
* Use Poppler instead of Ghostscript for old HP LaserJet printers due to
* a bug in their PS interpreters. They are very slow with Ghostscript.
* A LaserJet is considered old if its model number does not have a letter
* in the beginning, like LaserJet 3 or LaserJet 4000, not LaserJet P2015.
* See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=742765
*/
if (make_model[0] &&
((!strncasecmp(make_model, "HP", 2) ||
!strncasecmp(make_model, "Hewlett-Packard", 15) ||
!strncasecmp(make_model, "Hewlett Packard", 15)) &&
(ptr = strcasestr(make_model, "LaserJet"))))
{
for (ptr += 8; *ptr; ptr ++)
{
if (isspace(*ptr)) continue;
if (isdigit(*ptr))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Switching to Poppler's pdftops instead of "
"Ghostscript for old HP LaserJet (\"LaserJet "
"<number>\", no letters before <number>) printers to "
"work around bugs in the printer's PS interpreters");
renderer = PDFTOPS;
}
break;
}
}
}
/*
* Create option list for pstops filter function, stripping options which
* "pstops" does not need to apply any more
*/
num_pstops_options = 0;
pstops_options = NULL;
for (i = num_options, option = options; i > 0; i --, option ++)
{
for (j = 0, exclude = pstops_exclude_general[j]; exclude;
j++, exclude = pstops_exclude_general[j])
if (!strcasecmp(option->name, exclude)) break;
if (exclude) continue;
if (pdftopdfapplied)
{
for (j = 0, exclude = pstops_exclude_page_management[j]; exclude;
j++, exclude = pstops_exclude_page_management[j])
if (!strcasecmp(option->name, exclude)) break;
if (exclude) continue;
}
num_pstops_options = cupsAddOption(option->name,
option->value,
num_pstops_options, &pstops_options);
}
if (pdftopdfapplied && deviceCollate)
{
/*
* Add collate option to the pstops call if pdftopdf has found out that the
* printer does hardware collate.
*/
num_pstops_options = cupsAddOption("Collate",
"True",
num_pstops_options, &pstops_options);
}
/*
* Create data record to call the pstops filter function
*/
pstops_filter_data.job_id = data->job_id;
pstops_filter_data.job_user = data->job_user;
pstops_filter_data.job_title = data->job_title;
if (pdftopdfapplied)
pstops_filter_data.copies = atoi(deviceCopies);
else
pstops_filter_data.copies = data->copies;
pstops_filter_data.job_attrs = NULL;
pstops_filter_data.printer_attrs = NULL;
pstops_filter_data.num_options = num_pstops_options;
pstops_filter_data.options = pstops_options;
pstops_filter_data.ppdfile = NULL;
pstops_filter_data.ppd = ppd;
pstops_filter_data.logfunc = log;
pstops_filter_data.logdata = ld;
pstops_filter_data.iscanceledfunc = iscanceled;
pstops_filter_data.iscanceleddata = icd;
/*
* Force monochrome/grayscale PostScript output
* if job is to be printed in monochrome/grayscale
*/
if (ppd && ppd->color_device == 0) /* Monochrome printer */
gray_output = 1;
else /*Color Printer - user option for Grayscale */
{
if ((val = cupsGetOption("pwg-raster-document-type", num_options,
options)) != NULL ||
(val = cupsGetOption("PwgRasterDocumentType", num_options,
options)) != NULL ||
(val = cupsGetOption("print-color-mode", num_options,
options)) != NULL ||
(val = cupsGetOption("PrintColorMode", num_options,
options)) != NULL ||
(val = cupsGetOption("color-space", num_options,
options)) != NULL ||
(val = cupsGetOption("ColorSpace", num_options,
options)) != NULL ||
(val = cupsGetOption("color-model", num_options,
options)) != NULL ||
(val = cupsGetOption("ColorModel", num_options,
options)) != NULL ||
(val = cupsGetOption("output-mode", num_options,
options)) != NULL ||
(val = cupsGetOption("OutputMode", num_options,
options)) != NULL)
{
if (strcasestr(val, "Black") ||
strcasestr(val, "Gray") ||
strcasestr(val, "Mono"))
gray_output = 1;
}
}
/*
* Build the command-line for the pdftops, gs, mutool, pdftocairo, or
* acroread filter...
*/
if (renderer == PDFTOPS)
{
pdf_argv[0] = (char *)"pdftops";
pdf_argc = 1;
}
else if (renderer == GS)
{
pdf_argv[0] = (char *)"gs";
pdf_argv[1] = (char *)"-q";
pdf_argv[2] = (char *)"-dNOPAUSE";
pdf_argv[3] = (char *)"-dBATCH";
pdf_argv[4] = (char *)"-dSAFER";
pdf_argv[5] = (char *)"-dNOMEDIAATTRS";
pdf_argv[6] = (char *)"-sstdout=%stderr";
# ifdef HAVE_GHOSTSCRIPT_PS2WRITE
pdf_argv[7] = (char *)"-sDEVICE=ps2write";
# else
pdf_argv[7] = (char *)"-sDEVICE=pswrite";
# endif /* HAVE_GHOSTSCRIPT_PS2WRITE */
pdf_argv[8] = (char *)"-dShowAcroForm";
pdf_argv[9] = (char *)"-sOUTPUTFILE=%stdout";
if (gray_output == 1) /* Checking for monochrome/grayscale PostScript
output */
{
pdf_argv[10] = (char *)"-sProcessColorModel=DeviceGray";
pdf_argv[11] = (char *)"-sColorConversionStrategy=Gray";
pdf_argc = 12;
}
else
pdf_argc = 10;
}
else if (renderer == MUPDF)
{
pdf_argv[0] = (char *)"mutool";
pdf_argv[1] = (char *)"draw";
pdf_argv[2] = (char *)"-L";
pdf_argv[3] = (char *)"-smtf";
pdf_argv[4] = (char *)"-Fps";
pdf_argv[5] = (char *)"-o-";
if (gray_output == 1) /* Checking for monochrome/grayscale PostScript
output */
pdf_argv[6] = (char *)"-cgray";
else
pdf_argv[6] = (char *)"-crgb";
pdf_argc = 7;
}
else if (renderer == PDFTOCAIRO)
{
pdf_argv[0] = (char *)"pdftocairo";
pdf_argv[1] = (char *)"-ps";
pdf_argc = 2;
}
else if (renderer == ACROREAD)
{
pdf_argv[0] = (char *)"acroread";
pdf_argv[1] = (char *)"-toPostScript";
pdf_argc = 2;
}
/*
* Set language level and TrueType font handling...
*/
if (ppd)
{
if (ppd->language_level == 1)
{
if (renderer == PDFTOPS)
{
pdf_argv[pdf_argc++] = (char *)"-level1";
pdf_argv[pdf_argc++] = (char *)"-noembtt";
}
else if (renderer == GS)
pdf_argv[pdf_argc++] = (char *)"-dLanguageLevel=1";
else if (renderer == PDFTOCAIRO)
{
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Level 1 PostScript not supported by "
"pdftocairo.");
}
else if (renderer == ACROREAD)
{
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Level 1 PostScript not supported by acroread.");
}
else if (renderer == MUPDF)
{
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Level 1 PostScript not supported by mutool.");
}
}
else if (ppd->language_level == 2)
{
if (renderer == PDFTOPS)
{
pdf_argv[pdf_argc++] = (char *)"-level2";
if (!ppd->ttrasterizer)
pdf_argv[pdf_argc++] = (char *)"-noembtt";
}
else if (renderer == GS)
pdf_argv[pdf_argc++] = (char *)"-dLanguageLevel=2";
else if (renderer != MUPDF) /* MuPDF is PS level 2 only */
/* PDFTOCAIRO, ACROREAD */
pdf_argv[pdf_argc++] = (char *)"-level2";
}
else
{
if (renderer == PDFTOPS)
{
/* Do not emit PS Level 3 with Poppler on Brother and HP PostScript
laser printers as some do not like it.
See https://bugs.launchpad.net/bugs/277404 and
https://bugs.launchpad.net/bugs/1306849 comment #42. */
if (!make_model[0] ||
!strncasecmp(make_model, "Brother", 7) ||
((!strncasecmp(make_model, "HP", 2) ||
!strncasecmp(make_model, "Hewlett-Packard", 15) ||
!strncasecmp(make_model, "Hewlett Packard", 15)) &&
(strcasestr(make_model, "LaserJet"))))
pdf_argv[pdf_argc++] = (char *)"-level2";
else
pdf_argv[pdf_argc++] = (char *)"-level3";
}
else if (renderer == GS)
{
/* Do not emit PS Level 3 with Ghostscript on Brother PostScript
laser printers as some do not like it.
See https://bugs.launchpad.net/bugs/1306849 comment #42. */
if (!make_model[0] ||
!strncasecmp(make_model, "Brother", 7))
pdf_argv[pdf_argc++] = (char *)"-dLanguageLevel=2";
else
pdf_argv[pdf_argc++] = (char *)"-dLanguageLevel=3";
}
else if (renderer == MUPDF)
{
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Level 3 PostScript not supported by mutool.");
}
else /* PDFTOCAIRO || ACROREAD */
pdf_argv[pdf_argc++] = (char *)"-level3";
}
}
else
{
if (renderer == PDFTOPS)
{
/* Do not emit PS Level 3 with Poppler on HP PostScript laser printers
as some do not like it. See https://bugs.launchpad.net/bugs/277404.*/
if (!make_model[0] ||
((!strncasecmp(make_model, "HP", 2) ||
!strncasecmp(make_model, "Hewlett-Packard", 15) ||
!strncasecmp(make_model, "Hewlett Packard", 15)) &&
(strcasestr(make_model, "LaserJet"))))
pdf_argv[pdf_argc++] = (char *)"-level2";
else
pdf_argv[pdf_argc++] = (char *)"-level3";
pdf_argv[pdf_argc++] = (char *)"-noembtt";
}
else if (renderer == GS)
pdf_argv[pdf_argc++] = (char *)"-dLanguageLevel=3";
else if (renderer != MUPDF) /* MuPDF is PS level 2 only */
/* PDFTOCAIRO || ACROREAD */
pdf_argv[pdf_argc++] = (char *)"-level3";
}
#ifdef HAVE_POPPLER_PDFTOPS_WITH_ORIGPAGESIZES
if ((renderer == PDFTOPS) || (renderer == PDFTOCAIRO))
{
/*
* Use the page sizes of the original PDF document, this way documents
* which contain pages of different sizes can be printed correctly
*/
pdf_argv[pdf_argc++] = (char *)"-origpagesizes";
pdf_argv[pdf_argc++] = (char *)"-nocenter";
}
else
#endif /* HAVE_POPPLER_PDFTOPS_WITH_ORIGPAGESIZES */
if (renderer == ACROREAD)
{
/*
* Use the page sizes of the original PDF document, this way documents
* which contain pages of different sizes can be printed correctly
*/
pdf_argv[pdf_argc++] = (char *)"-choosePaperByPDFPageSize";
}
/*
* Set output resolution ...
*/
if (ppd)
{
/* Ignore error exits of ppdRasterInterpretPPD(), if it found a resolution
setting before erroring it is OK for us */
ppdRasterInterpretPPD(&header, ppd, num_options, options, NULL);
/* 100 dpi is default, this means that if we have 100 dpi here this
method failed to find the printing resolution */
if (header.HWResolution[0] > 100 && header.HWResolution[1] > 100)
{
xres = header.HWResolution[0];
yres = header.HWResolution[1];
}
else if ((choice = ppdFindMarkedChoice(ppd, "Resolution")) != NULL)
strncpy(resolution, choice->choice, sizeof(resolution) - 1);
else if ((attr = ppdFindAttr(ppd,"DefaultResolution",NULL)) != NULL)
strncpy(resolution, attr->value, sizeof(resolution) - 1);
resolution[sizeof(resolution)-1] = '\0';
if ((xres == 0) && (yres == 0) &&
((numvalues = sscanf(resolution, "%dx%d", &xres, &yres)) <= 0))
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: No resolution information found in the PPD file.");
}
if ((xres == 0) && (yres == 0))
{
if ((val = cupsGetOption("printer-resolution", num_options,
options)) != NULL ||
(val = cupsGetOption("Resolution", num_options, options)) != NULL)
{
xres = yres = strtol(val, (char **)&ptr, 10);
if (ptr > val && xres > 0)
{
if (*ptr == 'x')
yres = strtol(ptr + 1, (char **)&ptr, 10);
}
if (ptr <= val || xres <= 0 || yres <= 0 || !ptr ||
(*ptr != '\0' &&
strcasecmp(ptr, "dpi") &&
strcasecmp(ptr, "dpc") &&
strcasecmp(ptr, "dpcm")))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Bad resolution value \"%s\".", val);
}
else
{
if (!strcasecmp(ptr, "dpc") ||
!strcasecmp(ptr, "dpcm"))
{
xres = xres * 254 / 100;
yres = yres * 254 / 100;
}
}
}
}
if ((xres > 0) || (yres > 0))
{
if (yres == 0) yres = xres;
if (xres == 0) xres = yres;
if (xres > yres)
res = yres;
else
res = xres;
}
else
res = 300;
/*
* Get the ceiling for the image rendering resolution
*/
if ((val = cupsGetOption("pdftops-max-image-resolution",
num_options, options)) != NULL)
{
if ((numvalues = sscanf(val, "%d", &mres)) > 0)
maxres = mres;
else
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Invalid value for "
"\"pdftops-max-image-resolution\": \"%s\"",
val);
}
/*
* Reduce the image rendering resolution to not exceed a given maximum
* to make processing of jobs by the PDF->PS converter and the printer faster
*
* maxres = 0 means no limit
*/
if (maxres)
while (res > maxres)
res = res / 2;
if ((renderer == PDFTOPS) || (renderer == PDFTOCAIRO))
{
#ifdef HAVE_POPPLER_PDFTOPS_WITH_RESOLUTION
/*
* Set resolution to avoid slow processing by the printer when the
* resolution of embedded images does not match the printer's resolution
*/
pdf_argv[pdf_argc++] = (char *)"-r";
snprintf(resolution, sizeof(resolution), "%d", res);
pdf_argv[pdf_argc++] = resolution;
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Using image rendering resolution %d dpi", res);
#endif /* HAVE_POPPLER_PDFTOPS_WITH_RESOLUTION */
if (gray_output == 1) /* Checking for monochrome/grayscale PostScript
output */
{
/* Poppler does not explicitly support turning colored PDF files into
grayscale PostScript. As a workaround, one could let the "pdftops"
command line utility generate PostScript level 1 output which is
always grayscale, but output files get huge and printing too
slow.
Recommended solution is to not use Poppler as PDF renderer for
printing, especially if one uses a color PostScript printer and
wants to have the possibility to print jobs also in grayscale.
See the use of the "pdftops-renderer" option in the README file. */
/* Example code for PostScript level1 workaround: */
/* pdf_argv[1] = (char *)"-level1";
pdf_argv[pdf_argc++] = (char *)"-optimizecolorspace"; */
/* Issue a warning message when printing a grayscale job with Poppler */
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Grayscale/monochrome printing requested for this "
"job but Poppler is not able to convert to "
"grayscale/monochrome PostScript.");
if (log) log(ld, FILTER_LOGLEVEL_WARN,
"pdftops: Use \"pdftops-renderer\" option (see "
"cups-filters README file) to use Ghostscript or MuPDF for "
"the PDF -> PostScript conversion.");
}
pdf_argv[pdf_argc++] = filename;
pdf_argv[pdf_argc++] = (char *)"-";
}
else if (renderer == GS)
{
/*
* Set resolution to avoid slow processing by the printer when the
* resolution of embedded images does not match the printer's resolution
*/
snprintf(resolution, 127, "-r%d", res);
pdf_argv[pdf_argc++] = resolution;
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Using image rendering resolution %d dpi", res);
/*
* PostScript debug mode: If you send a job with "lpr -o psdebug" Ghostscript
* will not compress the pages, so that the PostScript code can get
* analysed. This is especially important if a PostScript printer errors or
* misbehaves on Ghostscript's output.
* On Kyocera and Utax (uses Kyocera hard- and software) printers we always
* suppress page compression, to avoid slow processing of raster images.
*/
val = cupsGetOption("psdebug", num_options, options);
if ((val && strcasecmp(val, "no") && strcasecmp(val, "off") &&
strcasecmp(val, "false")) ||
(make_model[0] &&
(!strncasecmp(make_model, "Kyocera", 7) ||
!strncasecmp(make_model, "Utax", 4))))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Deactivated compression of pages in "
"Ghostscript's PostScript output (\"psdebug\" debug mode "
"or Kyocera/Utax printer)");
pdf_argv[pdf_argc++] = (char *)"-dCompressPages=false";
}
/*
* The PostScript interpreters on many printers have bugs which make
* the interpreter crash, error out, or otherwise misbehave on too
* heavily compressed input files, especially if code with compressed
* elements is compressed again. Therefore we reduce compression here.
*/
pdf_argv[pdf_argc++] = (char *)"-dCompressFonts=false";
pdf_argv[pdf_argc++] = (char *)"-dNoT3CCITT";
if (make_model[0] &&
!strncasecmp(make_model, "Brother", 7))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Deactivation of Ghostscript's image compression "
"for Brother printers to workarounmd PS interpreter bug");
pdf_argv[pdf_argc++] = (char *)"-dEncodeMonoImages=false";
pdf_argv[pdf_argc++] = (char *)"-dEncodeColorImages=false";
}
/*
* Toshiba's PS interpreters have an issue with how we handle
* TrueType/Type42 fonts, therefore we add command line options to turn
* the TTF outlines into bitmaps, usually Type 3 PostScript fonts, only
* large glyphs into normal image data.
* See https://bugs.launchpad.net/bugs/978120
*/
if (make_model[0] &&
!strncasecmp(make_model, "Toshiba", 7))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: To work around a bug in Toshiba's PS "
"interpreters turn TTF font glyphs into bitmaps, usually "
"Type 3 PS fonts, or images for large characters");
pdf_argv[pdf_argc++] = (char *)"-dHaveTrueTypes=false";
}
pdf_argv[pdf_argc++] = (char *)"-dNOINTERPOLATE";
pdf_argv[pdf_argc++] = (char *)"-c";
if (make_model[0] &&
!strncasecmp(make_model, "Toshiba", 7))
pdf_argv[pdf_argc++] = (char *)"<< /MaxFontItem 500000 >> setuserparams";
pdf_argv[pdf_argc++] = (char *)"save pop";
pdf_argv[pdf_argc++] = (char *)"-f";
pdf_argv[pdf_argc++] = filename;
}
else if (renderer == MUPDF)
{
/*
* Add Resolution option to avoid slow processing by the printer when the
* resolution of embedded images does not match the printer's resolution
*/
snprintf(resolution, 127, "-r%dx%d", res, res);
pdf_argv[pdf_argc++] = resolution;
/*
* Add input file name
*/
pdf_argv[pdf_argc++] = filename;
}
pdf_argv[pdf_argc] = NULL;
log_command_line(NULL, pdf_argv, log, ld);
/*
* Do we need post-processing of the PostScript output to work around bugs
* of the printer's PostScript interpreter?
*/
if ((renderer == PDFTOPS) || (renderer == PDFTOCAIRO) ||
(renderer == MUPDF))
need_post_proc = 0;
else if (renderer == GS)
need_post_proc =
(make_model[0] &&
(!strncasecmp(make_model, "Kyocera", 7) ||
!strncasecmp(make_model, "Utax", 4) ||
!strncasecmp(make_model, "Brother", 7)) ? 1 : 0);
else
need_post_proc = 1;
/*
* Do we need post-processing of the PostScript output to apply option
* settings when doing PPD-less printing?
*/
if (!ppd)
need_post_proc = 1;
/*
* Execute "pdftops/gs/mutool [ | PS post-processing ] | pstops"...
*/
/*
* Create a pipe for each pair of subsequent processes. The variables
* are named by the receiving process.
*/
if (pipe(pstops_pipe))
{
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to create pipe for pstops: %s",
strerror(errno));
exit_status = 1;
goto error;
}
if (need_post_proc)
{
if (pipe(post_proc_pipe))
{
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to create pipe for post-processing: %s",
strerror(errno));
exit_status = 1;
goto error;
}
}
if ((pdf_pid = fork()) == 0)
{
/*
* Child comes here...
*/
if (need_post_proc)
{
dup2(post_proc_pipe[1], 1);
close(post_proc_pipe[0]);
close(post_proc_pipe[1]);
}
else
dup2(pstops_pipe[1], 1);
close(pstops_pipe[0]);
close(pstops_pipe[1]);
if (renderer == PDFTOPS)
{
execvp(CUPS_POPPLER_PDFTOPS, pdf_argv);
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute pdftops program: %s",
strerror(errno));
}
else if (renderer == GS)
{
execvp(CUPS_GHOSTSCRIPT, pdf_argv);
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute gs program: %s",
strerror(errno));
}
else if (renderer == PDFTOCAIRO)
{
execvp(CUPS_POPPLER_PDFTOCAIRO, pdf_argv);
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute pdftocairo program: %s",
strerror(errno));
}
else if (renderer == ACROREAD)
{
/*
* use filename as stdin for acroread to force output to stdout
*/
if ((fd = open(filename, O_RDONLY)))
{
dup2(fd, 0);
close(fd);
}
execvp(CUPS_ACROREAD, pdf_argv);
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute acroread program: %s",
strerror(errno));
}
else if (renderer == MUPDF)
{
execvp(CUPS_MUTOOL, pdf_argv);
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute mutool program: %s",
strerror(errno));
}
exit(1);
}
else if (pdf_pid < 0)
{
/*
* Unable to fork!
*/
if (log)
{
if (renderer == PDFTOPS)
log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute pdftops program: %s",
strerror(errno));
else if (renderer == GS)
log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute gs program: %s",
strerror(errno));
else if (renderer == PDFTOCAIRO)
log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute pdftocairo program: %s",
strerror(errno));
else if (renderer == ACROREAD)
log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute acroread program: %s",
strerror(errno));
else if (renderer == MUPDF)
log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute mutool program: %s",
strerror(errno));
}
exit_status = 1;
goto error;
}
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Started filter %s (PID %d)", pdf_argv[0], pdf_pid);
if (need_post_proc)
{
if ((post_proc_pid = fork()) == 0)
{
/*
* Child comes here...
*/
dup2(post_proc_pipe[0], 0);
close(post_proc_pipe[0]);
close(post_proc_pipe[1]);
dup2(pstops_pipe[1], 1);
close(pstops_pipe[0]);
close(pstops_pipe[1]);
fp = cupsFileStdin();
if (renderer == ACROREAD)
{
/*
* Set %Title and %For from filter arguments since acroread inserts
* garbage for these when using -toPostScript
*/
while ((bytes = cupsFileGetLine(fp, buffer, sizeof(buffer))) > 0 &&
strncmp(buffer, "%%BeginProlog", 13))
{
if (strncmp(buffer, "%%Title", 7) == 0)
printf("%%%%Title: %s\n", data->job_title);
else if (strncmp(buffer, "%%For", 5) == 0)
printf("%%%%For: %s\n", data->job_user);
else
printf("%s", buffer);
}
/*
* Copy the rest of the file
*/
while ((bytes = cupsFileRead(fp, buffer, sizeof(buffer))) > 0)
fwrite(buffer, 1, bytes, stdout);
}
else
{
/*
* Copy everything until after initial comments (Prolog section)
*/
while ((bytes = cupsFileGetLine(fp, buffer, sizeof(buffer))) > 0 &&
strncmp(buffer, "%%BeginProlog", 13) &&
strncmp(buffer, "%%EndProlog", 11) &&
strncmp(buffer, "%%BeginSetup", 12) &&
strncmp(buffer, "%%Page:", 7))
printf("%s", buffer);
if (bytes > 0)
{
/*
* Insert PostScript interpreter bug fix code in the beginning of
* the Prolog section (before the first active PostScript code)
*/
if (strncmp(buffer, "%%BeginProlog", 13))
{
/* No Prolog section, create one */
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Adding Prolog section for workaround "
"PostScript code");
puts("%%BeginProlog");
}
else
printf("%s", buffer);
if (renderer == GS && make_model[0])
{
/*
* Kyocera (and Utax) printers have a bug in their PostScript
* interpreter making them crashing on PostScript input data
* generated by Ghostscript's "ps2write" output device.
*
* The problem can be simply worked around by preceding the
* PostScript code with some extra bits.
*
* See https://bugs.launchpad.net/bugs/951627
*
* In addition, at least some of Kyocera's PostScript printers are
* very slow on rendering images which request interpolation. So we
* also add some code to eliminate interpolation requests.
*
* See https://bugs.launchpad.net/bugs/1026974
*/
if (!strncasecmp(make_model, "Kyocera", 7) ||
!strncasecmp(make_model, "Utax", 4))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Inserted workaround PostScript code for "
"Kyocera and Utax printers");
puts("% ===== Workaround insertion by pdftops CUPS filter =====");
puts("% Kyocera's/Utax's PostScript interpreter crashes on "
"early name binding,");
puts("% so eliminate all \"bind\"s by redefining \"bind\" to "
"no-op");
puts("/bind {} bind def");
puts("% Some Kyocera and Utax printers have an unacceptably "
"slow implementation");
puts("% of image interpolation.");
puts("/image");
puts("{");
puts(" dup /Interpolate known");
puts(" {");
puts(" dup /Interpolate undef");
puts(" } if");
puts(" systemdict /image get exec");
puts("} def");
puts("% =====");
}
/*
* Brother printers have a bug in their PostScript interpreter
* making them printing one blank page if PostScript input data
* generated by Ghostscript's "ps2write" output device is used.
*
* The problem can be simply worked around by preceding the
* PostScript code with some extra bits.
*
* See https://bugs.launchpad.net/bugs/950713
*/
else if (!strncasecmp(make_model, "Brother", 7))
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Inserted workaround PostScript code for "
"Brother printers");
puts("% ===== Workaround insertion by pdftops CUPS filter =====");
puts("% Brother's PostScript interpreter spits out the current "
"page");
puts("% and aborts the job on the \"currenthalftone\" operator, "
"so redefine");
puts("% it to null");
puts("/currenthalftone {//null} bind def");
puts("/orig.sethalftone systemdict /sethalftone get def");
puts("/sethalftone {dup //null eq not {//orig.sethalftone}{pop} "
"ifelse} bind def");
puts("% =====");
}
}
if (strncmp(buffer, "%%BeginProlog", 13))
{
/* Close newly created Prolog section */
if (strncmp(buffer, "%%EndProlog", 11))
puts("%%EndProlog");
printf("%s", buffer);
}
if (!ppd)
{
/*
* Copy everything until the setup section
*/
while (bytes > 0 &&
strncmp(buffer, "%%BeginSetup", 12) &&
strncmp(buffer, "%%EndSetup", 10) &&
strncmp(buffer, "%%Page:", 7))
{
bytes = cupsFileGetLine(fp, buffer, sizeof(buffer));
if (strncmp(buffer, "%%Page:", 7) &&
strncmp(buffer, "%%EndSetup", 10))
printf("%s", buffer);
}
if (bytes > 0)
{
/*
* Insert option PostScript code in Setup section
*/
if (strncmp(buffer, "%%BeginSetup", 12))
{
/* No Setup section, create one */
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Adding Setup section for option "
"PostScript code");
puts("%%BeginSetup");
}
/*
* Duplex
*/
duplex = 0;
tumble = 0;
if ((val = cupsGetOption("sides",
num_options, options)) != NULL ||
(val = cupsGetOption("Duplex", num_options, options)) != NULL)
{
if (!strcasecmp(val, "On") ||
!strcasecmp(val, "True") || !strcasecmp(val, "Yes") ||
!strncasecmp(val, "two-sided", 9) ||
!strncasecmp(val, "TwoSided", 8) ||
!strncasecmp(val, "Duplex", 6))
{
duplex = 1;
if (!strncasecmp(val, "DuplexTumble", 12))
tumble = 1;
}
}
if ((val = cupsGetOption("sides",
num_options, options)) != NULL ||
(val = cupsGetOption("Tumble", num_options, options)) != NULL)
{
if (!strcasecmp(val, "None") || !strcasecmp(val, "Off") ||
!strcasecmp(val, "False") || !strcasecmp(val, "No") ||
!strcasecmp(val, "one-sided") ||
!strcasecmp(val, "OneSided") ||
!strcasecmp(val, "two-sided-long-edge") ||
!strcasecmp(val, "TwoSidedLongEdge") ||
!strcasecmp(val, "DuplexNoTumble"))
tumble = 0;
else if (!strcasecmp(val, "On") ||
!strcasecmp(val, "True") || !strcasecmp(val, "Yes") ||
!strcasecmp(val, "two-sided-short-edge") ||
!strcasecmp(val, "TwoSidedShortEdge") ||
!strcasecmp(val, "DuplexTumble"))
tumble = 1;
}
if (duplex)
{
if (tumble)
puts("<</Duplex true /Tumble true>> setpagedevice");
else
puts("<</Duplex true /Tumble false>> setpagedevice");
}
else
puts("<</Duplex false>> setpagedevice");
/*
* Resolution
*/
if ((xres > 0) && (yres > 0))
printf("<</HWResolution[%d %d]>> setpagedevice\n", xres, yres);
/*
* InputSlot/MediaSource
*/
if ((val = cupsGetOption("media-position", num_options,
options)) != NULL ||
(val = cupsGetOption("MediaPosition", num_options,
options)) != NULL ||
(val = cupsGetOption("media-source", num_options,
options)) != NULL ||
(val = cupsGetOption("MediaSource", num_options,
options)) != NULL ||
(val = cupsGetOption("InputSlot", num_options,
options)) != NULL)
{
if (!strncasecmp(val, "Auto", 4) ||
!strncasecmp(val, "Default", 7))
puts("<</ManualFeed false /MediaPosition 7>> setpagedevice");
else if (!strcasecmp(val, "Main"))
puts("<</MediaPosition 0 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "Alternate"))
puts("<</MediaPosition 1 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "Manual"))
puts("<</MediaPosition 3 /ManualFeed true>> setpagedevice");
else if (!strcasecmp(val, "Top"))
puts("<</MediaPosition 0 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "Bottom"))
puts("<</MediaPosition 1 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "ByPassTray"))
puts("<</MediaPosition 3 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "Tray1"))
puts("<</MediaPosition 3 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "Tray2"))
puts("<</MediaPosition 0 /ManualFeed false>> setpagedevice");
else if (!strcasecmp(val, "Tray3"))
puts("<</MediaPosition 1 /ManualFeed false>> setpagedevice");
}
/*
* ColorModel
*/
if ((val = cupsGetOption("pwg-raster-document-type", num_options,
options)) != NULL ||
(val = cupsGetOption("PwgRasterDocumentType", num_options,
options)) != NULL ||
(val = cupsGetOption("print-color-mode", num_options,
options)) != NULL ||
(val = cupsGetOption("PrintColorMode", num_options,
options)) != NULL ||
(val = cupsGetOption("color-space", num_options,
options)) != NULL ||
(val = cupsGetOption("ColorSpace", num_options,
options)) != NULL ||
(val = cupsGetOption("color-model", num_options,
options)) != NULL ||
(val = cupsGetOption("ColorModel", num_options,
options)) != NULL)
{
if (!strncasecmp(val, "Black", 5))
puts("<</ProcessColorModel /DeviceGray>> setpagedevice");
else if (!strncasecmp(val, "Cmyk", 4))
puts("<</ProcessColorModel /DeviceCMYK>> setpagedevice");
else if (!strncasecmp(val, "Cmy", 3))
puts("<</ProcessColorModel /DeviceCMY>> setpagedevice");
else if (!strncasecmp(val, "Rgb", 3))
puts("<</ProcessColorModel /DeviceRGB>> setpagedevice");
else if (!strncasecmp(val, "Gray", 4))
puts("<</ProcessColorModel /DeviceGray>> setpagedevice");
else if (!strncasecmp(val, "Color", 5))
puts("<</ProcessColorModel /DeviceRGB>> setpagedevice");
}
if (strncmp(buffer, "%%BeginSetup", 12))
{
/* Close newly created Setup section */
if (strncmp(buffer, "%%EndSetup", 10))
puts("%%EndSetup");
printf("%s", buffer);
}
}
}
/*
* Copy the rest of the file
*/
while ((bytes = cupsFileRead(fp, buffer, sizeof(buffer))) > 0)
fwrite(buffer, 1, bytes, stdout);
}
}
exit(0);
}
else if (post_proc_pid < 0)
{
/*
* Unable to fork!
*/
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute post-processing process: %s",
strerror(errno));
exit_status = 1;
goto error;
}
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Started post-processing (PID %d)", post_proc_pid);
}
if ((pstops_pid = fork()) == 0)
{
/*
* Child comes here...
*/
dup2(pstops_pipe[0], 0);
close(pstops_pipe[0]);
close(pstops_pipe[1]);
if (need_post_proc)
{
close(post_proc_pipe[0]);
close(post_proc_pipe[1]);
}
ret = pstops(0, outputfd, 0, &pstops_filter_data, NULL);
if (ret && log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: pstops filter function failed.");
close(outputfd);
exit(ret);
}
else if (pstops_pid < 0)
{
/*
* Unable to fork!
*/
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: Unable to execute pstops program: %s",
strerror(errno));
exit_status = 1;
goto error;
}
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Started filter pstops (PID %d)", pstops_pid);
close(pstops_pipe[0]);
close(pstops_pipe[1]);
if (need_post_proc)
{
close(post_proc_pipe[0]);
close(post_proc_pipe[1]);
}
/*
* Wait for the child processes to exit...
*/
wait_children = 2 + need_post_proc;
while (wait_children > 0)
{
/*
* Wait until we get a valid process ID or the job is canceled...
*/
while ((wait_pid = wait(&wait_status)) < 0 && errno == EINTR)
{
if (iscanceled && iscanceled(icd))
{
kill(pdf_pid, SIGTERM);
if (need_post_proc)
kill(post_proc_pid, SIGTERM);
kill(pstops_pid, SIGTERM);
}
}
if (wait_pid < 0)
break;
wait_children --;
/*
* Report child status...
*/
if (wait_status)
{
if (WIFEXITED(wait_status))
{
exit_status = WEXITSTATUS(wait_status);
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: PID %d (%s) stopped with status %d!",
wait_pid,
wait_pid == pdf_pid ?
(renderer == PDFTOPS ? "pdftops" :
(renderer == PDFTOCAIRO ? "pdftocairo" :
(renderer == GS ? "gs" :
(renderer == ACROREAD ? "acroread" :
(renderer == MUPDF ? "mutool" :
"Unknown renderer"))))) :
(wait_pid == pstops_pid ? "pstops" :
(wait_pid == post_proc_pid ? "Post-processing" :
"Unknown process")),
exit_status);
}
else if (WTERMSIG(wait_status) == SIGTERM)
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: PID %d (%s) was terminated normally with "
"signal %d!",
wait_pid,
wait_pid == pdf_pid ?
(renderer == PDFTOPS ? "pdftops" :
(renderer == PDFTOCAIRO ? "pdftocairo" :
(renderer == GS ? "gs" :
(renderer == ACROREAD ? "acroread" :
(renderer == MUPDF ? "mutool" :
"Unknown renderer"))))) :
(wait_pid == pstops_pid ? "pstops" :
(wait_pid == post_proc_pid ? "Post-processing" :
"Unknown process")),
exit_status);
}
else
{
exit_status = WTERMSIG(wait_status);
if (log) log(ld, FILTER_LOGLEVEL_ERROR,
"pdftops: PID %d (%s) crashed on signal %d!",
wait_pid,
wait_pid == pdf_pid ?
(renderer == PDFTOPS ? "pdftops" :
(renderer == PDFTOCAIRO ? "pdftocairo" :
(renderer == GS ? "gs" :
(renderer == ACROREAD ? "acroread" :
(renderer == MUPDF ? "mutool" :
"Unknown renderer"))))) :
(wait_pid == pstops_pid ? "pstops" :
(wait_pid == post_proc_pid ? "Post-processing" :
"Unknown process")),
exit_status);
}
}
else
{
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: PID %d (%s) exited with no errors.",
wait_pid,
wait_pid == pdf_pid ?
(renderer == PDFTOPS ? "pdftops" :
(renderer == PDFTOCAIRO ? "pdftocairo" :
(renderer == GS ? "gs" :
(renderer == ACROREAD ? "acroread" :
(renderer == MUPDF ? "mutool" :
"Unknown renderer"))))) :
(wait_pid == pstops_pid ? "pstops" :
(wait_pid == post_proc_pid ? "Post-processing" :
"Unknown process")));
}
}
/*
* Cleanup and exit...
*/
error:
if (log) log(ld, FILTER_LOGLEVEL_DEBUG,
"pdftops: Closing files ...");
close(outputfd);
unlink(tempfile);
return (exit_status);
}
| 29.650325 | 80 | 0.597494 | [
"model"
] |
96195f8e2eae1aaa9187901f010c28ccea0f0916 | 7,862 | h | C | frmts/netcdf/netcdf_cf_constants.h | FeU-aKlos/gdal | bba6781133815248c9329842d365f8812b74c33f | [
"Apache-2.0"
] | null | null | null | frmts/netcdf/netcdf_cf_constants.h | FeU-aKlos/gdal | bba6781133815248c9329842d365f8812b74c33f | [
"Apache-2.0"
] | 1 | 2022-02-26T19:07:05.000Z | 2022-02-27T00:11:45.000Z | frmts/netcdf/netcdf_cf_constants.h | FeU-aKlos/gdal | bba6781133815248c9329842d365f8812b74c33f | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* $Id$
*
* Project: netCDF read/write Driver
* Purpose: GDAL bindings over netCDF library.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2004, Frank Warmerdam
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef NETCDF_CF_CONSTANTS_H_INCLUDED_
#define NETCDF_CF_CONSTANTS_H_INCLUDED_
/* -------------------------------------------------------------------- */
/* CF-1 or NUG (NetCDF User's Guide) defs */
/* -------------------------------------------------------------------- */
/* CF: http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.5/cf-conventions.html */
/* NUG: http://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html#Variables */
#define CF_STD_NAME "standard_name"
#define CF_LNG_NAME "long_name"
#define CF_UNITS "units"
#define CF_ADD_OFFSET "add_offset"
#define CF_SCALE_FACTOR "scale_factor"
/* should be SRS_UL_METER but use meter now for compat with gtiff files */
#define CF_UNITS_M "metre"
#define CF_UNITS_D SRS_UA_DEGREE
#define CF_PROJ_X_VAR_NAME "x"
#define CF_PROJ_Y_VAR_NAME "y"
#define CF_PROJ_X_COORD "projection_x_coordinate"
#define CF_PROJ_Y_COORD "projection_y_coordinate"
#define CF_PROJ_X_COORD_LONG_NAME "x coordinate of projection"
#define CF_PROJ_Y_COORD_LONG_NAME "y coordinate of projection"
#define CF_GRD_MAPPING_NAME "grid_mapping_name"
#define CF_GRD_MAPPING "grid_mapping"
#define CF_COORDINATES "coordinates"
#define CF_LONGITUDE_VAR_NAME "lon"
#define CF_LONGITUDE_STD_NAME "longitude"
#define CF_LONGITUDE_LNG_NAME "longitude"
#define CF_LATITUDE_VAR_NAME "lat"
#define CF_LATITUDE_STD_NAME "latitude"
#define CF_LATITUDE_LNG_NAME "latitude"
#define CF_DEGREES_NORTH "degrees_north" /* recommended */
#define CF_DEGREE_NORTH "degree_north" /* acceptable */
#define CF_DEGREES_N "degrees_N" /* acceptable */
#define CF_DEGREES_EAST "degrees_east" /* recommended */
#define CF_DEGREE_EAST "degree_east" /* acceptable */
#define CF_DEGREES_E "degrees_E" /* acceptable */
#define CF_AXIS "axis"
/* #define CF_BOUNDS "bounds" */
/* #define CF_ORIG_UNITS "original_units" */
/* -------------------------------------------------------------------- */
/* CF-1 convention standard variables related to */
/* mapping & projection - see http://cf-pcmdi.llnl.gov/ */
/* -------------------------------------------------------------------- */
#define CF_PRIME_MERIDIAN_NAME "prime_meridian_name"
#define CF_REFERENCE_ELLIPSOID_NAME "reference_ellipsoid_name"
#define CF_HORIZONTAL_DATUM_NAME "horizontal_datum_name"
#define CF_GEOGRAPHIC_CRS_NAME "geographic_crs_name"
#define CF_PROJECTED_CRS_NAME "projected_crs_name"
/* projection types */
#define CF_PT_AEA "albers_conical_equal_area"
#define CF_PT_AE "azimuthal_equidistant"
#define CF_PT_CEA "cylindrical_equal_area"
#define CF_PT_LAEA "lambert_azimuthal_equal_area"
#define CF_PT_LCEA "lambert_cylindrical_equal_area"
#define CF_PT_LCC "lambert_conformal_conic"
#define CF_PT_TM "transverse_mercator"
#define CF_PT_LATITUDE_LONGITUDE "latitude_longitude"
#define CF_PT_MERCATOR "mercator"
#define CF_PT_ORTHOGRAPHIC "orthographic"
#define CF_PT_POLAR_STEREO "polar_stereographic"
#define CF_PT_STEREO "stereographic"
#define CF_PT_GEOS "geostationary"
#define CF_PT_ROTATED_LATITUDE_LONGITUDE "rotated_latitude_longitude"
/* projection parameters */
#define CF_PP_STD_PARALLEL "standard_parallel"
/* CF uses only "standard_parallel" */
#define CF_PP_STD_PARALLEL_1 "standard_parallel_1"
#define CF_PP_STD_PARALLEL_2 "standard_parallel_2"
#define CF_PP_CENTRAL_MERIDIAN "central_meridian"
#define CF_PP_LONG_CENTRAL_MERIDIAN "longitude_of_central_meridian"
#define CF_PP_LON_PROJ_ORIGIN "longitude_of_projection_origin"
#define CF_PP_LAT_PROJ_ORIGIN "latitude_of_projection_origin"
/* #define PROJ_X_ORIGIN "projection_x_coordinate_origin" */
/* #define PROJ_Y_ORIGIN "projection_y_coordinate_origin" */
#define CF_PP_EARTH_SHAPE "GRIB_earth_shape"
#define CF_PP_EARTH_SHAPE_CODE "GRIB_earth_shape_code"
/* scale_factor is not CF, there are two possible translations */
/* for WKT scale_factor : SCALE_FACTOR_MERIDIAN and SCALE_FACTOR_ORIGIN */
#define CF_PP_SCALE_FACTOR_MERIDIAN "scale_factor_at_central_meridian"
#define CF_PP_SCALE_FACTOR_ORIGIN "scale_factor_at_projection_origin"
#define CF_PP_VERT_LONG_FROM_POLE "straight_vertical_longitude_from_pole"
#define CF_PP_FALSE_EASTING "false_easting"
#define CF_PP_FALSE_NORTHING "false_northing"
#define CF_PP_EARTH_RADIUS "earth_radius"
#define CF_PP_EARTH_RADIUS_OLD "spherical_earth_radius_meters"
#define CF_PP_INVERSE_FLATTENING "inverse_flattening"
#define CF_PP_LONG_PRIME_MERIDIAN "longitude_of_prime_meridian"
#define CF_PP_SEMI_MAJOR_AXIS "semi_major_axis"
#define CF_PP_SEMI_MINOR_AXIS "semi_minor_axis"
#define CF_PP_VERT_PERSP "vertical_perspective" /*not used yet */
#define CF_PP_PERSPECTIVE_POINT_HEIGHT "perspective_point_height"
#define CF_PP_SWEEP_ANGLE_AXIS "sweep_angle_axis"
#define CF_PP_GRID_NORTH_POLE_LONGITUDE "grid_north_pole_longitude"
#define CF_PP_GRID_NORTH_POLE_LATITUDE "grid_north_pole_latitude"
#define CF_PP_NORTH_POLE_GRID_LONGITUDE "north_pole_grid_longitude"
/* Simple Geometries Special Names from CF-1.8 Draft - Chapter 7 section Geometries */
#define CF_SG_GEOMETRY "geometry"
#define CF_SG_GEOMETRY_DIMENSION "geometry_dimension"
#define CF_SG_GEOMETRY_TYPE "geometry_type"
#define CF_SG_INTERIOR_RING "interior_ring"
#define CF_SG_NODES "nodes"
#define CF_SG_NODE_COORDINATES "node_coordinates"
#define CF_SG_NODE_COUNT "node_count"
#define CF_SG_PART_NODE_COUNT "part_node_count"
#define CF_SG_TYPE_LINE "line"
#define CF_SG_TYPE_POINT "point"
#define CF_SG_TYPE_POLY "polygon"
#define CF_SG_X_AXIS "X"
#define CF_SG_Y_AXIS "Y"
#define CF_SG_Z_AXIS "Z"
#endif // NETCDF_CF_CONSTANTS_H_INCLUDED_
| 52.066225 | 86 | 0.675146 | [
"geometry"
] |
9619bc646c085d67d05b334e76f52180d1519324 | 16,236 | h | C | Arduino/snapshots/20140321-r2721-V0p2-Arduino-REV2-beta16-to-install/V0p2_Main/Control.h | opentrv/opentrv-OpenTRV-Arduino-V0p2 | 746753c88ed426c35ee91fa8933264e8bf2529b5 | [
"Apache-2.0"
] | 2 | 2016-11-05T09:59:06.000Z | 2018-12-10T17:33:32.000Z | Arduino/snapshots/20140321-r2721-V0p2-Arduino-REV2-beta16-to-install/V0p2_Main/Control.h | opentrv/opentrv-OpenTRV-Arduino-V0p2 | 746753c88ed426c35ee91fa8933264e8bf2529b5 | [
"Apache-2.0"
] | 2 | 2017-01-12T14:48:13.000Z | 2017-03-13T19:21:49.000Z | Arduino/snapshots/20140321-r2721-V0p2-Arduino-REV2-beta16-to-install/V0p2_Main/Control.h | opentrv/opentrv-OpenTRV-Arduino-V0p2 | 746753c88ed426c35ee91fa8933264e8bf2529b5 | [
"Apache-2.0"
] | 11 | 2016-08-15T10:23:09.000Z | 2021-09-10T12:48:31.000Z | /*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2013--2014
*/
/*
Control/model for TRV and boiler.
*/
#ifndef CONTROL_H
#define CONTROL_H
#include <stdint.h>
#include "V0p2_Main.h"
#include "Temp_Pot.h"
// Minimum and maximum bounds target temperatures; degrees C/Celsius/centigrade, strictly positive.
// Minimum is some way above 0C to avoid freezing pipework even with small measurement errors and non-uniform temperatures.
// Maximum is set a little below boiling/100C for DHW applications for safety.
// Setbacks and uplifts cannot move temperature targets outside this range for safety.
#define MIN_TARGET_C 5 // Minimum temperature setting allowed (to avoid freezing, allowing for offsets at temperature sensor, etc).
#define MAX_TARGET_C 95 // Maximum temperature setting allowed (eg for DHW).
// Default frost (minimum) temperature in degrees C, strictly positive, in range [MIN_TARGET_C,MAX_TARGET_C].
#define BIASECO_FROST MIN_TARGET_C // Target FROST temperature for ECO bias; must be in range [MIN_TARGET_C,BIASCOM_FROST[.
#define BIASCOM_FROST (5+MIN_TARGET_C) // Target FROST temperature for Comfort bias; must be in range ]BIASECO_FROST,MAX_TARGET_C].
#define FROST BIASECO_FROST
#ifndef DHW_TEMPERATURES
// Default warm/comfort room (air) temperature in degrees C; strictly greater than FROST, in range [MIN_TARGET_C,MAX_TARGET_C].
// Control loop effectively targets upper end of this 1C window as of 20130518.
#define BIASECO_WARM 17 // Target WARM temperature for ECO bias; must be in range ]BIASCOM_FROST+1,BIASCOM_WARM[.
#define BIASCOM_WARM 20 // Target WARM temperature for Comfort bias; must be in range ]BIASECO_WARM,MAX_TARGET_C-BAKE_UPLIFT-1].
#define WARM BIASECO_WARM // 17 or 18 good for energy saving at maybe 1C below typical UK room temperatures (~19C in 2012).
#else // Default settings for DHW control.
#define BIASECO_WARM 55 // Target WARM temperature for ECO bias; must be in range [MODECOM_WARM,MAX_TARGET_C].
#define BIASCOM_WARM 65 // Target WARM temperature for Comfort bias; must be in range ]MIN_TARGET_C,MODEECO_WARM].
#define WARM BIASECO_WARM // 55C+ with boost to 60C+ for DHW Legionella control.
#endif
// Raise target by this many degrees in 'BAKE' mode (strictly positive).
#define BAKE_UPLIFT 5
// Maximum 'BAKE' minutes, ie time to crank heating up to BAKE setting (minutes, strictly positive, <255).
#define BAKE_MAX_M 30
// Initial minor setback degrees C (strictly positive). Note that 1C heating setback may result in ~8% saving in UK.
#define SETBACK 1
// Full setback degrees C (strictly positive and significantly, ie several degrees, greater than SETBACK, less than MIN_TARGET_C).
// This must be less than MIN_TARGET_C to avoid problems with unsigned arithmetic.
#define SETBACK_FULL 3
// Prolonged inactivity time deemed to indicate room(s) really unoccupied to trigger full setback (minutes, strictly positive).
#define SETBACK_FULL_M 45
#ifdef LEARN_BUTTON_AVAILABLE
// Period in minutes for simple learned on-time; strictly positive (and less than 256).
#define LEARNED_ON_PERIOD_M 60
// Period in minutes for simple learned on-time with comfort bias; strictly positive (and less than 256).
#define LEARNED_ON_PERIOD_COMFORT_M 120
#endif
// If true (the default) then the system has an 'Eco' energy-saving bias, else it has a 'comfort' bias.
// Several system parameters are adjusted depending on the bias,
// with 'eco' slanted toward saving energy, eg with lower target temperatures and shorter on-times.
// This is determined from user-settable temperature values.
bool hasEcoBias();
// Get dynamically-set thresholds/parameters.
#if defined(SETTABLE_TARGET_TEMPERATURES) || defined(TEMP_POT_AVAILABLE)
// Get 'FROST' protection target in C; no higher than getWARMTargetC() returns, strictly positive, in range [MIN_TARGET_C,MAX_TARGET_C].
// Depends dynamically on current (last-read) temp-pot setting.
uint8_t getFROSTTargetC();
// Get 'WARM' target in C; no lower than getFROSTTargetC() returns, strictly positive, in range [MIN_TARGET_C,MAX_TARGET_C].
// Depends dynamically on current (last-read) temp-pot setting.
uint8_t getWARMTargetC();
#endif
#if defined(SETTABLE_TARGET_TEMPERATURES) && !defined(TEMP_POT_AVAILABLE)
// Set (non-volatile) 'FROST' protection target in C; no higher than getWARMTargetC() returns, strictly positive, in range [MIN_TARGET_C,MAX_TARGET_C].
// Returns false if not set, eg because outside range [MIN_TARGET_C,MAX_TARGET_C], else returns true.
bool setFROSTTargetC(uint8_t tempC);
// Set 'WARM' target in C; no lower than getFROSTTargetC() returns, strictly positive, in range [MIN_TARGET_C,MAX_TARGET_C].
// Returns false if not set, eg because below FROST setting or outside range [MIN_TARGET_C,MAX_TARGET_C], else returns true.
bool setWARMTargetC(uint8_t tempC);
#endif
// Percentage open for local TRV being controlled in range [0,100]; 0 is closed/off and the initial state.
// Not persistent (computed at run-time).
uint8_t getTRVPercentOpen();
// Target temperature in Centigrade for this OpenTRV unit.
// Not persistent (computed at run-time).
uint8_t getTargetTempC();
#ifdef ENABLE_BOILER_HUB
// Get minimum on (and off) time for pointer (minutes); zero if not in hub mode.
uint8_t getMinBoilerOnMinutes();
// Set minimum on (and off) time for pointer (minutes); zero to disable hub mode.
// Suggested minimum of 4 minutes for gas combi; much longer for heat pumps for example.
void setMinBoilerOnMinutes(uint8_t mins);
#else
#define getMinBoilerOnMinutes() (0) // Always disabled.
#define setMinBoilerOnMinutes(mins) {} // Do nothing.
#endif
// True if in central hub/listen mode (possibly with local radiator also).
#define inHubMode() (0 != getMinBoilerOnMinutes())
// Typical minimum valve percentage open to be considered actually/significantly open; [1,100].
// Setting this above 0 delays calling for heat from a central boiler until water is likely able to flow.
// (It may however be possible to scavenge some heat if a particular valve opens below this and the circulation pump is already running, for example.)
// DHD20130522: FHT8V + valve heads I have been using are not typically upen until around 6%.
// Allowing valve to linger at just below this level without calling for heat when shutting
// may allow comfortable bolier pump overrun in older systems with no/poor bypass to avoid overheating.
#define DEFAULT_MIN_VALVE_PC_REALLY_OPEN 10
// Return minimum valve percentage open to be considered actually/significantly open; [1,100].
// At the boiler hub this is also the threshold precentage-open on eavesdropped requests that will call for heat.
// If no override is set then DEFAULT_MIN_VALVE_PC_REALLY_OPEN is used.
uint8_t getMinValvePcReallyOpen();
// Set percent open to be considered really open.
// Applies to local valve and, at hub, to calls for remote calls for heat.
// Any out-of-range value (eg >100) clears the override and DEFAULT_MIN_VALVE_PC_REALLY_OPEN will be used.
void setMinValvePcReallyOpen(uint8_t percent);
// Default maximum time to allow the boiler to run on to allow for lost call-for-heat transmissions etc.
// Should be (much) greater than the gap between transmissions (eg ~2m for FHT8V/FS20).
// Should be greater than the run-on time at the OpenTRV boiler unit and any further pump run-on time.
// Valves may have to linger open at minimum of this plus maybe an extra minute or so for timing skew
// for systems with poor/absent bypass to avoid overheating.
// Having too high a linger time value will cause excessive temperature overshoot.
#define DEFAULT_MAX_RUN_ON_TIME_M 6
// If defined then turn off valve very slowly after stopping call for heat (ie when shutting) which
// may allow comfortable bolier pump overrun in older systems with no/poor bypass to avoid overheating.
// In any case this should help reduce strain on circulation pumps, etc.
#define VALVE_TURN_OFF_LINGER
// True iff the valve(s) (if any) controlled by this unit are really open.
// This waits until, for example, an ACK where appropriate, or at least the command has been sent.
// This also implies open to DEFAULT_MIN_VALVE_PC_REALLY_OPEN or equivalent.
// Must be exactly one definition/implementation supplied at link time.
// If more than one valve is being controlled by this unit,
// then this should return true if anyof the valves are (significantly) open.
bool isControlledValveOpen();
// Compute target temperature.
// Can be called as often as require though may be slow/expensive.
// Will be called by computeCallForHeat().
void computeTargetTemperature();
// Compute target temperature and set heat demand for TRV and boiler.
// CALL APPROXIMATELY ONCE PER MINUTE TO ALLOW SIMPLE TIME-BASED CONTROLS.
// Inputs are inWarmMode(), isRoomLit().
// The inputs must be valid (and recent).
// Values set are targetTempC, TRVPercentOpen.
// This may also prepare data such as TX command sequences for the TRV, boiler, etc.
// This routine may take significant CPU time; no I/O is done, only internal state is updated.
// Returns true if valve target changed and thus messages may need to be recomputed/sent/etc.
bool computeCallForHeat();
// Returns true if system is in 'learn'/smart mode.
// If in 'smart' mode can anticipate user demand to pre-warm rooms, maintain customary temperatures, etc.
bool inSmartMode();
// IF DEFINED: support for general timed and multi-input occupancy detection / use.
#ifdef OCCUPANCY_SUPPORT
// Returns true if the room appears to be likely occupied (with active users) recently.
// This uses the same timer as isLikelyOccupied() (restarted by markAsOccupied())
// but returns to false somewhat sooner for example to allow ramping up more costly occupancy detection methods
// and to allow some simple graduated occupancy responses.
// Do not call from an ISR.
bool isLikelyRecentlyOccupied();
// Returns true if the estimated likelyhood of occupancy is deminishing
// and expending effort above a basic level to check for continuing occupancy is worthwhile.
#define increaseCheckForOccupancy() (!isLikelyRecentlyOccupied() && isLikelyOccupied())
// Returns true if the room appears to be likely occupied (with active users) now or recently.
// Operates on a timeout; calling markAsOccupied() restarts the timer.
// Defaults to false (and API still exists) when OCCUPANCY_SUPPORT not defined.
// Do not call from an ISR.
bool isLikelyOccupied();
// False if room likely currently unoccupied (no active users).
// Defaults to false (and API still exists) when OCCUPANCY_SUPPORT not defined.
// This may require a substantial timeout (many hours) of inactivity to become true.
// This and isLikelyOccupied() cannot be true together; it is possible for neither to be true.
// Do not call from an ISR.
#define isLikelyUnoccupied() (!isLikelyOccupied())
// Call when some strong evidence of room occupation and human activity has occurred.
// Such evidence may include operation of buttons (etc) on the unit or PIR.
// Do not call from (for example) 'on' schedule change.
// Do not call from an ISR.
void markAsOccupied();
// Call when some/weak evidence of room occupation, such as light going on.
// Also use to simulate demand on behalf of user, eg for some part of schedule.
// Do not call from an ISR.
void markAsPossiblyOccupied();
#else
#define markAsOccupied() {} // Defined as NO-OP for convenience when no general occupancy support.
#define markAsPossiblyOccupied() {} // Defined as NO-OP for convenience when no general occupancy support.
#define isLikelyOccupied() (false) // Always false without OCCUPANCY_SUPPORT
#define isLikelyUnoccupied() (false) // Always false without OCCUPANCY_SUPPORT
#endif
// Sample statistics once per hour as background to simple monitoring and adaptive behaviour.
// Call this once per hour with fullSample==true, as near the end of the hour as possible;
// this will update the non-volatile stats record for the current hour.
// Optionally call this at a small (2--10) even number of evenly-spaced number of other times thoughout the hour
// with fullSample=false to sub-sample (and these may receive lower weighting or be ignored).
// (EEPROM wear should not be an issue at this update rate in normal use.)
void sampleStats(bool fullSample);
// Clear all collected statistics, eg when moving device to a new room or at a major time change.
// Requires 1.8ms per byte for each byte that actually needs erasing.
// * maxBytesToErase limit the number of bytes erased to this; strictly positive, else 0 to allow 65536
// Returns true if finished with all bytes erased.
bool zapStats(uint16_t maxBytesToErase = 0);
// Get raw stats value for hour HH [0,23] from stats set N from non-volatile (EEPROM) store.
// A value of 0xff (255) means unset (or out of range); other values depend on which stats set is being used.
uint8_t getByHourStat(uint8_t hh, uint8_t statsSet);
// 'Unset'/invalid values for byte (eg raw EEPROM byte) and int (eg after decompression).
#define STATS_UNSET_BYTE 0xff
#define STATS_UNSET_INT 0x7fff
// Returns true iff room likely to be occupied and need warming at the specified hour's sample point based on collected stats.
// Used for predictively warming a room in smart mode and for choosing setback depths.
// Returns false if no good evidence to warm the room at the given time based on past history over about one week.
// * hh hour to check for predictive warming [0,23]
bool shouldBeWarmedAtHour(const uint_least8_t hh);
#ifdef UNIT_TESTS
// Compute new linearly-smoothed value given old smoothed value and new value.
// Guaranteed not to produce a value higher than the max of the old smoothed value and the new value.
// Uses stochastic rounding to nearest to allow nominally sub-lsb values to have an effect over time.
// Usually only made public for unit testing.
uint8_t smoothStatsValue(uint8_t oldSmoothed, uint8_t newValue);
#endif
// Range-compress an signed int 16ths-Celsius temperature to a unsigned single-byte value < 0xff.
// This preserves at least the first bit after the binary point for all values,
// and three bits after binary point for values in the most interesting mid range around normal room temperatures,
// with transitions at whole degrees Celsius.
// Input values below 0C are treated as 0C, and above 100C as 100C, thus allowing air and DHW temperature values.
#define COMPRESSION_C16_FLOOR_VAL 0 // Floor input value to compression.
#define COMPRESSION_C16_LOW_THRESHOLD (16<<4) // Values in range [COMPRESSION_LOW_THRESHOLD_C16,COMPRESSION_HIGH_THRESHOLD_C16[ have maximum precision.
#define COMPRESSION_C16_LOW_THR_AFTER (COMPRESSION_C16_LOW_THRESHOLD>>3) // Low threshold after compression.
#define COMPRESSION_C16_HIGH_THRESHOLD (24<<4)
#define COMPRESSION_C16_HIGH_THR_AFTER (COMPRESSION_C16_LOW_THR_AFTER + ((COMPRESSION_C16_HIGH_THRESHOLD-COMPRESSION_C16_LOW_THRESHOLD)>>1)) // High threshold after compression.
#define COMPRESSION_C16_CEIL_VAL (100<<4) // Ceiling input value to compression.
#define COMPRESSION_C16_CEIL_VAL_AFTER (COMPRESSION_C16_HIGH_THR_AFTER + ((COMPRESSION_C16_CEIL_VAL-COMPRESSION_C16_HIGH_THRESHOLD) >> 3)) // Ceiling input value after compression.
uint8_t compressTempC16(int tempC16);
// Reverses range compression done by compressTempC16(); results in range [0,100], with varying precision based on original value.
// 0xff (or other invalid) input results in STATS_UNSET_INT.
int expandTempC16(uint8_t cTemp);
// Maximum valid encoded/compressed stats values.
#define MAX_STATS_TEMP COMPRESSION_C16_CEIL_VAL_AFTER // Maximum valid compressed temperature value in stats.
#define MAX_STATS_AMBLIGHT 254 // Maximum valid ambient light value in stats (very top of range is compressed).
#endif
| 55.037288 | 180 | 0.783198 | [
"model"
] |
96200c3481e609d346a2f5162163f9ab49bd9b7f | 847 | h | C | NumLib/Function/ISpatialFunction.h | norihiro-w/ogs | ac990b1aa06a583dba3e32efa3009ef0c6f46ae4 | [
"BSD-4-Clause"
] | null | null | null | NumLib/Function/ISpatialFunction.h | norihiro-w/ogs | ac990b1aa06a583dba3e32efa3009ef0c6f46ae4 | [
"BSD-4-Clause"
] | 25 | 2015-02-04T20:34:21.000Z | 2018-12-10T20:19:57.000Z | NumLib/Function/ISpatialFunction.h | norihiro-w/ogs | ac990b1aa06a583dba3e32efa3009ef0c6f46ae4 | [
"BSD-4-Clause"
] | null | null | null | /**
* \author Norihiro Watanabe
* \date 2013-08-13
*
* \copyright
* Copyright (c) 2012-2016, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#ifndef ISPATIALFUNCTION_H_
#define ISPATIALFUNCTION_H_
#include <vector>
#include "MathLib/Point3d.h"
namespace NumLib
{
/**
* \brief Interface class for any functions of spatial coordinates \f$f(x,y,z)\f$
*/
class ISpatialFunction
{
public:
virtual ~ISpatialFunction(){}
/**
* return a value at the given point
* \param pnt a point object
* \return evaluated value
*/
virtual double operator()(const MathLib::Point3d& pnt) const = 0;
};
} // NumLib
#endif //ISPATIALFUNCTION_H_
| 19.697674 | 81 | 0.656434 | [
"object",
"vector"
] |
9623de7b47067986ec51571cdca16e400280f44c | 12,655 | h | C | packages/seacas/libraries/ioss/src/Ioss_Utils.h | ibaned/seacas | 8d0c2b6dd4c90654b1cb0f0d288a5ab6e8b59d87 | [
"Zlib",
"MIT",
"NetCDF",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | packages/seacas/libraries/ioss/src/Ioss_Utils.h | ibaned/seacas | 8d0c2b6dd4c90654b1cb0f0d288a5ab6e8b59d87 | [
"Zlib",
"MIT",
"NetCDF",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | packages/seacas/libraries/ioss/src/Ioss_Utils.h | ibaned/seacas | 8d0c2b6dd4c90654b1cb0f0d288a5ab6e8b59d87 | [
"Zlib",
"MIT",
"NetCDF",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // Copyright(C) 1999-2017 National Technology & Engineering Solutions
// of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
// NTESS, the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of NTESS nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef IOSS_Ioss_Utils_h
#define IOSS_Ioss_Utils_h
#include <Ioss_CodeTypes.h>
#include <Ioss_Field.h>
#include <algorithm> // for sort, lower_bound, copy, etc
#include <cassert>
#include <cstddef> // for size_t
#include <cstdint> // for int64_t
#include <cstdlib> // for nullptrr
#include <iostream> // for ostringstream, etcstream, etc
#include <stdexcept> // for runtime_error
#include <string> // for string
#include <vector> // for vector
namespace Ioss {
class Field;
} // namespace Ioss
namespace Ioss {
class GroupingEntity;
class Region;
class SideBlock;
class PropertyManager;
struct MeshCopyOptions;
} // namespace Ioss
#if __cplusplus > 199711L
#define TOPTR(x) x.data()
#else
#define TOPTR(x) (x.empty() ? nullptr : &x[0])
#endif
#define IOSS_ERROR(errmsg) throw std::runtime_error(errmsg.str())
#define IOSS_WARNING std::cerr
namespace {
// SEE: http://lemire.me/blog/2017/04/10/removing-duplicates-from-lists-quickly
template <typename T> size_t unique(std::vector<T> &out, bool skip_first)
{
if (out.empty())
return 0;
size_t i = 1;
size_t pos = 1;
T oldv = out[0];
if (skip_first) {
i = 2;
pos = 2;
oldv = out[1];
}
for (; i < out.size(); ++i) {
T newv = out[i];
out[pos] = newv;
pos += (newv != oldv);
oldv = newv;
}
return pos;
}
} // namespace
namespace Ioss {
/* \brief Utility methods.
*/
class Utils
{
public:
Utils() = default;
~Utils() = default;
// Assignment operator
// Copy constructor
static void check_dynamic_cast(const void *ptr)
{
if (ptr == nullptr) {
std::cerr << "INTERNAL ERROR: Invalid dynamic cast returned nullptr\n";
exit(EXIT_FAILURE);
}
}
template <typename T> static void uniquify(std::vector<T> &vec, bool skip_first = false)
{
auto it = vec.begin();
if (skip_first) {
it++;
}
std::sort(it, vec.end());
vec.resize(unique(vec, skip_first));
vec.shrink_to_fit();
}
template <typename T> static void generate_index(std::vector<T> &index)
{
T sum = 0;
for (size_t i = 0; i < index.size() - 1; i++) {
T cnt = index[i];
index[i] = sum;
sum += cnt;
}
index.back() = sum;
}
template <typename T> static T find_index_location(T node, const std::vector<T> &index)
{
// 0-based node numbering
// index[p] = first node (0-based) on processor p
#if 1
// Assume data coherence. I.e., a new search will be close to the
// previous search.
static size_t prev = 1;
size_t nproc = index.size();
if (prev < nproc && index[prev - 1] <= node && index[prev] > node) {
return prev - 1;
}
for (size_t p = 1; p < nproc; p++) {
if (index[p] > node) {
prev = p;
return p - 1;
}
}
std::cerr << "FATAL ERROR: find_index_location. Searching for " << node << " in:\n";
for (auto idx : index) {
std::cerr << idx << ", ";
}
std::cerr << "\n";
assert(1 == 0); // Cannot happen...
return 0;
#else
return std::distance(index.begin(), std::upper_bound(index.begin(), index.end(), node)) - 1;
#endif
}
template <typename T> static void clear(std::vector<T> &vec)
{
vec.clear();
vec.shrink_to_fit();
assert(vec.capacity() == 0);
}
inline static int power_2(int count)
{
// Return the power of two which is equal to or greater than 'count'
// count = 15 -> returns 16
// count = 16 -> returns 16
// count = 17 -> returns 32
// Use brute force...
int pow2 = 1;
while (pow2 < count) {
pow2 *= 2;
}
return pow2;
}
template <typename T> static bool check_block_order(const std::vector<T *> &blocks)
{
#ifndef NDEBUG
// Verify that element blocks are defined in sorted offset order...
typename std::vector<T *>::const_iterator I;
int64_t eb_offset = -1;
for (I = blocks.begin(); I != blocks.end(); ++I) {
int64_t this_off = (*I)->get_offset();
if (this_off < eb_offset) {
{
{
return false;
}
}
}
eb_offset = this_off;
}
#endif
return true;
}
static int log_power_2(uint64_t value);
static char **get_name_array(size_t count, int size);
static void delete_name_array(char **names, int count);
// Fill time_string and date_string with current time and date
// formatted as "HH:MM:SS" for time and "yy/mm/dd" or "yyyy/mm/dd"
// for date
static void time_and_date(char *time_string, char *date_string, size_t length);
static std::string decode_filename(const std::string &filename, int processor,
int num_processors);
static size_t get_number(const std::string &suffix);
static int64_t extract_id(const std::string &name_id);
static std::string encode_entity_name(const std::string &entity_type, int64_t id);
// Convert 'name' to lowercase and convert spaces to '_'
static void fixup_name(char *name);
static void fixup_name(std::string &name);
// Check whether property 'prop_name' exists and if so, set 'prop_value'
// based on the property value. Either "TRUE", "YES", "ON", or 1 for true;
// or "FALSE", "NO", "OFF", or not equal to 1 for false.
// Returns true/false depending on whether property found and value set.
// Does not set 'prop_val' if 'prop_name' does not exist.
static bool check_set_bool_property(const Ioss::PropertyManager &properties,
const std::string &prop_name, bool &prop_value);
// Returns true if the property "omitted" exists on "block"
static bool block_is_omitted(Ioss::GroupingEntity *block);
// Process the base element type 'base' which has
// 'nodes_per_element' nodes and a spatial dimension of 'spatial'
// into a form that the IO system can (hopefully) recognize.
// Lowercases the name; converts spaces to '_', adds
// nodes_per_element at end of name (if not already there), and
// does some other transformations to remove some exodusII ambiguity.
static std::string fixup_type(const std::string &base, int nodes_per_element, int spatial);
static std::string uppercase(std::string name);
static std::string lowercase(std::string name);
static void check_non_null(void *ptr, const char *type, const std::string &name,
const std::string &func);
static int case_strcmp(const std::string &s1, const std::string &s2);
// Return a string containing information about the current :
// computing platform. This is used as information data in the
// created results file to help in tracking when/where/... the file
// was created.
static std::string platform_information();
// Return amount of memory being used on this processor
static size_t get_memory_info();
static size_t get_hwm_memory_info();
// Return a filename relative to the specified working directory (if any)
// of the current execution. Working_directory must end with '/' or be empty.
static std::string local_filename(const std::string &relative_filename, const std::string &type,
const std::string &working_directory);
static void get_fields(int64_t entity_count, char **names, size_t num_names,
Ioss::Field::RoleType fld_role, bool enable_field_recognition,
char suffix_separator, int *local_truth,
std::vector<Ioss::Field> &fields);
static int field_warning(const Ioss::GroupingEntity *ge, const Ioss::Field &field,
const std::string &inout);
static void calculate_sideblock_membership(IntVector &face_is_member, const SideBlock *ef_blk,
size_t int_byte_size, const void *element,
const void *sides, int64_t number_sides,
const Region *region);
// And yet another idiosyncrasy of sidesets...
// The side of an element (especially shells) can be
// either a face or an edge in the same sideset. The
// ordinal of an edge is (local_edge_number+#faces) on the
// database, but needs to be (local_edge_number) for
// Sierra...
//
// If the sideblock has a "parent_element_topology" and a
// "topology", then we can determine whether to offset the
// side ordinals...
static int64_t get_side_offset(const Ioss::SideBlock *sb);
static unsigned int hash(const std::string &name);
static double timer();
// Return a vector of strings containing the lines of the input file.
// Should only be called by a single processor or each processor will
// be accessing the file at the same time...
static void input_file(const std::string &file_name, std::vector<std::string> *lines,
size_t max_line_length = 0);
template <class T> static std::string to_string(const T &t) { return std::to_string(t); }
// Many databases have a maximum length for variable names which can
// cause a problem with variable name length.
//
// This routine tries to shorten long variable names to an acceptable
// length ('max_var_len' characters max). If the name is already less than this
// length, it is returned unchanged...
//
// Since there is a (good) chance that two shortened names will match,
// a 2-letter 'hash' code is appended to the end of the variable name.
//
// So, we shorten the name to a maximum of 'max_var_len'-3 characters and append a
// 2 character hash+separator.
//
// It also converts name to lowercase and converts spaces to '_'
static std::string variable_name_kluge(const std::string &name, size_t component_count,
size_t copies, size_t max_var_len);
// The model for a history file is a single sphere element (1 node, 1 element)
// This is needed for some applications that read this file that require a "mesh"
// even though a history file is just a collection of global variables with no
// real mesh. This routine will add the mesh portion to a history file.
static void generate_history_mesh(Ioss::Region *region);
// Copy the mesh in 'region' to 'output_region'. Behavior can be controlled
// via options in 'options'
static void copy_database(Ioss::Region ®ion, Ioss::Region &output_region,
Ioss::MeshCopyOptions &options);
};
} // namespace Ioss
#endif
| 37.220588 | 100 | 0.637298 | [
"mesh",
"vector",
"model"
] |
962412c79b91709d7fa0bd28943c2b15603d1831 | 14,382 | c | C | drivers/staging/media/rockchip/vpu/rockchip_vpu_drv.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/staging/media/rockchip/vpu/rockchip_vpu_drv.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/staging/media/rockchip/vpu/rockchip_vpu_drv.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: GPL-2.0
/*
* Rockchip VPU codec driver
*
* Copyright (C) 2018 Collabora, Ltd.
* Copyright 2018 Google LLC.
* Tomasz Figa <tfiga@chromium.org>
*
* Based on s5p-mfc driver by Samsung Electronics Co., Ltd.
* Copyright (C) 2011 Samsung Electronics Co., Ltd.
*/
#include <linux/clk.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <linux/workqueue.h>
#include <media/v4l2-event.h>
#include <media/v4l2-mem2mem.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-vmalloc.h>
#include "rockchip_vpu_common.h"
#include "rockchip_vpu.h"
#include "rockchip_vpu_hw.h"
#define DRIVER_NAME "rockchip-vpu"
int rockchip_vpu_debug;
module_param_named(debug, rockchip_vpu_debug, int, 0644);
MODULE_PARM_DESC(debug,
"Debug level - higher value produces more verbose messages");
static void rockchip_vpu_job_finish(struct rockchip_vpu_dev *vpu,
struct rockchip_vpu_ctx *ctx,
unsigned int bytesused,
enum vb2_buffer_state result)
{
struct vb2_v4l2_buffer *src, *dst;
size_t avail_size;
pm_runtime_mark_last_busy(vpu->dev);
pm_runtime_put_autosuspend(vpu->dev);
clk_bulk_disable(vpu->variant->num_clocks, vpu->clocks);
src = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx);
dst = v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx);
if (WARN_ON(!src))
return;
if (WARN_ON(!dst))
return;
src->sequence = ctx->sequence_out++;
dst->sequence = ctx->sequence_cap++;
dst->field = src->field;
if (src->flags & V4L2_BUF_FLAG_TIMECODE)
dst->timecode = src->timecode;
dst->vb2_buf.timestamp = src->vb2_buf.timestamp;
dst->flags &= ~(V4L2_BUF_FLAG_TSTAMP_SRC_MASK |
V4L2_BUF_FLAG_TIMECODE);
dst->flags |= src->flags & (V4L2_BUF_FLAG_TSTAMP_SRC_MASK |
V4L2_BUF_FLAG_TIMECODE);
avail_size = vb2_plane_size(&dst->vb2_buf, 0) -
ctx->vpu_dst_fmt->header_size;
if (bytesused <= avail_size) {
if (ctx->bounce_buf) {
memcpy(vb2_plane_vaddr(&dst->vb2_buf, 0) +
ctx->vpu_dst_fmt->header_size,
ctx->bounce_buf, bytesused);
}
dst->vb2_buf.planes[0].bytesused =
ctx->vpu_dst_fmt->header_size + bytesused;
} else {
result = VB2_BUF_STATE_ERROR;
}
v4l2_m2m_buf_done(src, result);
v4l2_m2m_buf_done(dst, result);
v4l2_m2m_job_finish(vpu->m2m_dev, ctx->fh.m2m_ctx);
}
void rockchip_vpu_irq_done(struct rockchip_vpu_dev *vpu,
unsigned int bytesused,
enum vb2_buffer_state result)
{
struct rockchip_vpu_ctx *ctx =
v4l2_m2m_get_curr_priv(vpu->m2m_dev);
/*
* If cancel_delayed_work returns false
* the timeout expired. The watchdog is running,
* and will take care of finishing the job.
*/
if (cancel_delayed_work(&vpu->watchdog_work))
rockchip_vpu_job_finish(vpu, ctx, bytesused, result);
}
void rockchip_vpu_watchdog(struct work_struct *work)
{
struct rockchip_vpu_dev *vpu;
struct rockchip_vpu_ctx *ctx;
vpu = container_of(to_delayed_work(work),
struct rockchip_vpu_dev, watchdog_work);
ctx = v4l2_m2m_get_curr_priv(vpu->m2m_dev);
if (ctx) {
vpu_err("frame processing timed out!\n");
ctx->codec_ops->reset(ctx);
rockchip_vpu_job_finish(vpu, ctx, 0, VB2_BUF_STATE_ERROR);
}
}
static void device_run(void *priv)
{
struct rockchip_vpu_ctx *ctx = priv;
int ret;
ret = clk_bulk_enable(ctx->dev->variant->num_clocks, ctx->dev->clocks);
if (ret)
goto err_cancel_job;
ret = pm_runtime_get_sync(ctx->dev->dev);
if (ret < 0)
goto err_cancel_job;
ctx->codec_ops->run(ctx);
return;
err_cancel_job:
rockchip_vpu_job_finish(ctx->dev, ctx, 0, VB2_BUF_STATE_ERROR);
}
static struct v4l2_m2m_ops vpu_m2m_ops = {
.device_run = device_run,
};
static int
enc_queue_init(void *priv, struct vb2_queue *src_vq, struct vb2_queue *dst_vq)
{
struct rockchip_vpu_ctx *ctx = priv;
int ret;
src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
src_vq->io_modes = VB2_MMAP | VB2_DMABUF;
src_vq->drv_priv = ctx;
src_vq->ops = &rockchip_vpu_enc_queue_ops;
src_vq->mem_ops = &vb2_dma_contig_memops;
/*
* Driver does mostly sequential access, so sacrifice TLB efficiency
* for faster allocation. Also, no CPU access on the source queue,
* so no kernel mapping needed.
*/
src_vq->dma_attrs = DMA_ATTR_ALLOC_SINGLE_PAGES |
DMA_ATTR_NO_KERNEL_MAPPING;
src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
src_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
src_vq->lock = &ctx->dev->vpu_mutex;
src_vq->dev = ctx->dev->v4l2_dev.dev;
ret = vb2_queue_init(src_vq);
if (ret)
return ret;
/*
* The CAPTURE queue doesn't need dma memory,
* as the CPU needs to create the JPEG frames,
* from the hardware-produced JPEG payload.
*
* For the DMA destination buffer, we use
* a bounce buffer.
*/
dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
dst_vq->io_modes = VB2_MMAP | VB2_DMABUF;
dst_vq->drv_priv = ctx;
dst_vq->ops = &rockchip_vpu_enc_queue_ops;
dst_vq->mem_ops = &vb2_vmalloc_memops;
dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
dst_vq->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY;
dst_vq->lock = &ctx->dev->vpu_mutex;
dst_vq->dev = ctx->dev->v4l2_dev.dev;
return vb2_queue_init(dst_vq);
}
static int rockchip_vpu_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct rockchip_vpu_ctx *ctx;
ctx = container_of(ctrl->handler,
struct rockchip_vpu_ctx, ctrl_handler);
vpu_debug(1, "s_ctrl: id = %d, val = %d\n", ctrl->id, ctrl->val);
switch (ctrl->id) {
case V4L2_CID_JPEG_COMPRESSION_QUALITY:
ctx->jpeg_quality = ctrl->val;
break;
default:
return -EINVAL;
}
return 0;
}
static const struct v4l2_ctrl_ops rockchip_vpu_ctrl_ops = {
.s_ctrl = rockchip_vpu_s_ctrl,
};
static int rockchip_vpu_ctrls_setup(struct rockchip_vpu_dev *vpu,
struct rockchip_vpu_ctx *ctx)
{
v4l2_ctrl_handler_init(&ctx->ctrl_handler, 1);
if (vpu->variant->codec & RK_VPU_CODEC_JPEG) {
v4l2_ctrl_new_std(&ctx->ctrl_handler, &rockchip_vpu_ctrl_ops,
V4L2_CID_JPEG_COMPRESSION_QUALITY,
5, 100, 1, 50);
if (ctx->ctrl_handler.error) {
vpu_err("Adding JPEG control failed %d\n",
ctx->ctrl_handler.error);
v4l2_ctrl_handler_free(&ctx->ctrl_handler);
return ctx->ctrl_handler.error;
}
}
return v4l2_ctrl_handler_setup(&ctx->ctrl_handler);
}
/*
* V4L2 file operations.
*/
static int rockchip_vpu_open(struct file *filp)
{
struct rockchip_vpu_dev *vpu = video_drvdata(filp);
struct video_device *vdev = video_devdata(filp);
struct rockchip_vpu_ctx *ctx;
int ret;
/*
* We do not need any extra locking here, because we operate only
* on local data here, except reading few fields from dev, which
* do not change through device's lifetime (which is guaranteed by
* reference on module from open()) and V4L2 internal objects (such
* as vdev and ctx->fh), which have proper locking done in respective
* helper functions used here.
*/
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->dev = vpu;
if (vdev == vpu->vfd_enc)
ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(vpu->m2m_dev, ctx,
&enc_queue_init);
else
ctx->fh.m2m_ctx = ERR_PTR(-ENODEV);
if (IS_ERR(ctx->fh.m2m_ctx)) {
ret = PTR_ERR(ctx->fh.m2m_ctx);
kfree(ctx);
return ret;
}
v4l2_fh_init(&ctx->fh, vdev);
filp->private_data = &ctx->fh;
v4l2_fh_add(&ctx->fh);
if (vdev == vpu->vfd_enc) {
rockchip_vpu_enc_reset_dst_fmt(vpu, ctx);
rockchip_vpu_enc_reset_src_fmt(vpu, ctx);
}
ret = rockchip_vpu_ctrls_setup(vpu, ctx);
if (ret) {
vpu_err("Failed to set up controls\n");
goto err_fh_free;
}
ctx->fh.ctrl_handler = &ctx->ctrl_handler;
return 0;
err_fh_free:
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
kfree(ctx);
return ret;
}
static int rockchip_vpu_release(struct file *filp)
{
struct rockchip_vpu_ctx *ctx =
container_of(filp->private_data, struct rockchip_vpu_ctx, fh);
/*
* No need for extra locking because this was the last reference
* to this file.
*/
v4l2_m2m_ctx_release(ctx->fh.m2m_ctx);
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
v4l2_ctrl_handler_free(&ctx->ctrl_handler);
kfree(ctx);
return 0;
}
static const struct v4l2_file_operations rockchip_vpu_fops = {
.owner = THIS_MODULE,
.open = rockchip_vpu_open,
.release = rockchip_vpu_release,
.poll = v4l2_m2m_fop_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = v4l2_m2m_fop_mmap,
};
static const struct of_device_id of_rockchip_vpu_match[] = {
{ .compatible = "rockchip,rk3399-vpu", .data = &rk3399_vpu_variant, },
{ .compatible = "rockchip,rk3288-vpu", .data = &rk3288_vpu_variant, },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, of_rockchip_vpu_match);
static int rockchip_vpu_video_device_register(struct rockchip_vpu_dev *vpu)
{
const struct of_device_id *match;
struct video_device *vfd;
int function, ret;
match = of_match_node(of_rockchip_vpu_match, vpu->dev->of_node);
vfd = video_device_alloc();
if (!vfd) {
v4l2_err(&vpu->v4l2_dev, "Failed to allocate video device\n");
return -ENOMEM;
}
vfd->fops = &rockchip_vpu_fops;
vfd->release = video_device_release;
vfd->lock = &vpu->vpu_mutex;
vfd->v4l2_dev = &vpu->v4l2_dev;
vfd->vfl_dir = VFL_DIR_M2M;
vfd->device_caps = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_M2M_MPLANE;
vfd->ioctl_ops = &rockchip_vpu_enc_ioctl_ops;
snprintf(vfd->name, sizeof(vfd->name), "%s-enc", match->compatible);
vpu->vfd_enc = vfd;
video_set_drvdata(vfd, vpu);
ret = video_register_device(vfd, VFL_TYPE_GRABBER, 0);
if (ret) {
v4l2_err(&vpu->v4l2_dev, "Failed to register video device\n");
goto err_free_dev;
}
v4l2_info(&vpu->v4l2_dev, "registered as /dev/video%d\n", vfd->num);
function = MEDIA_ENT_F_PROC_VIDEO_ENCODER;
ret = v4l2_m2m_register_media_controller(vpu->m2m_dev, vfd, function);
if (ret) {
v4l2_err(&vpu->v4l2_dev, "Failed to init mem2mem media controller\n");
goto err_unreg_video;
}
return 0;
err_unreg_video:
video_unregister_device(vfd);
err_free_dev:
video_device_release(vfd);
return ret;
}
static int rockchip_vpu_probe(struct platform_device *pdev)
{
const struct of_device_id *match;
struct rockchip_vpu_dev *vpu;
struct resource *res;
int i, ret;
vpu = devm_kzalloc(&pdev->dev, sizeof(*vpu), GFP_KERNEL);
if (!vpu)
return -ENOMEM;
vpu->dev = &pdev->dev;
vpu->pdev = pdev;
mutex_init(&vpu->vpu_mutex);
spin_lock_init(&vpu->irqlock);
match = of_match_node(of_rockchip_vpu_match, pdev->dev.of_node);
vpu->variant = match->data;
INIT_DELAYED_WORK(&vpu->watchdog_work, rockchip_vpu_watchdog);
for (i = 0; i < vpu->variant->num_clocks; i++)
vpu->clocks[i].id = vpu->variant->clk_names[i];
ret = devm_clk_bulk_get(&pdev->dev, vpu->variant->num_clocks,
vpu->clocks);
if (ret)
return ret;
res = platform_get_resource(vpu->pdev, IORESOURCE_MEM, 0);
vpu->base = devm_ioremap_resource(vpu->dev, res);
if (IS_ERR(vpu->base))
return PTR_ERR(vpu->base);
vpu->enc_base = vpu->base + vpu->variant->enc_offset;
ret = dma_set_coherent_mask(vpu->dev, DMA_BIT_MASK(32));
if (ret) {
dev_err(vpu->dev, "Could not set DMA coherent mask.\n");
return ret;
}
if (vpu->variant->vepu_irq) {
int irq;
irq = platform_get_irq_byname(vpu->pdev, "vepu");
if (irq <= 0) {
dev_err(vpu->dev, "Could not get vepu IRQ.\n");
return -ENXIO;
}
ret = devm_request_irq(vpu->dev, irq, vpu->variant->vepu_irq,
0, dev_name(vpu->dev), vpu);
if (ret) {
dev_err(vpu->dev, "Could not request vepu IRQ.\n");
return ret;
}
}
ret = vpu->variant->init(vpu);
if (ret) {
dev_err(&pdev->dev, "Failed to init VPU hardware\n");
return ret;
}
pm_runtime_set_autosuspend_delay(vpu->dev, 100);
pm_runtime_use_autosuspend(vpu->dev);
pm_runtime_enable(vpu->dev);
ret = clk_bulk_prepare(vpu->variant->num_clocks, vpu->clocks);
if (ret) {
dev_err(&pdev->dev, "Failed to prepare clocks\n");
return ret;
}
ret = v4l2_device_register(&pdev->dev, &vpu->v4l2_dev);
if (ret) {
dev_err(&pdev->dev, "Failed to register v4l2 device\n");
goto err_clk_unprepare;
}
platform_set_drvdata(pdev, vpu);
vpu->m2m_dev = v4l2_m2m_init(&vpu_m2m_ops);
if (IS_ERR(vpu->m2m_dev)) {
v4l2_err(&vpu->v4l2_dev, "Failed to init mem2mem device\n");
ret = PTR_ERR(vpu->m2m_dev);
goto err_v4l2_unreg;
}
vpu->mdev.dev = vpu->dev;
strlcpy(vpu->mdev.model, DRIVER_NAME, sizeof(vpu->mdev.model));
media_device_init(&vpu->mdev);
vpu->v4l2_dev.mdev = &vpu->mdev;
ret = rockchip_vpu_video_device_register(vpu);
if (ret) {
dev_err(&pdev->dev, "Failed to register encoder\n");
goto err_m2m_rel;
}
ret = media_device_register(&vpu->mdev);
if (ret) {
v4l2_err(&vpu->v4l2_dev, "Failed to register mem2mem media device\n");
goto err_video_dev_unreg;
}
return 0;
err_video_dev_unreg:
if (vpu->vfd_enc) {
video_unregister_device(vpu->vfd_enc);
video_device_release(vpu->vfd_enc);
}
err_m2m_rel:
v4l2_m2m_release(vpu->m2m_dev);
err_v4l2_unreg:
v4l2_device_unregister(&vpu->v4l2_dev);
err_clk_unprepare:
clk_bulk_unprepare(vpu->variant->num_clocks, vpu->clocks);
pm_runtime_disable(vpu->dev);
return ret;
}
static int rockchip_vpu_remove(struct platform_device *pdev)
{
struct rockchip_vpu_dev *vpu = platform_get_drvdata(pdev);
v4l2_info(&vpu->v4l2_dev, "Removing %s\n", pdev->name);
media_device_unregister(&vpu->mdev);
v4l2_m2m_unregister_media_controller(vpu->m2m_dev);
v4l2_m2m_release(vpu->m2m_dev);
media_device_cleanup(&vpu->mdev);
if (vpu->vfd_enc) {
video_unregister_device(vpu->vfd_enc);
video_device_release(vpu->vfd_enc);
}
v4l2_device_unregister(&vpu->v4l2_dev);
clk_bulk_unprepare(vpu->variant->num_clocks, vpu->clocks);
pm_runtime_disable(vpu->dev);
return 0;
}
static const struct dev_pm_ops rockchip_vpu_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
pm_runtime_force_resume)
};
static struct platform_driver rockchip_vpu_driver = {
.probe = rockchip_vpu_probe,
.remove = rockchip_vpu_remove,
.driver = {
.name = DRIVER_NAME,
.of_match_table = of_match_ptr(of_rockchip_vpu_match),
.pm = &rockchip_vpu_pm_ops,
},
};
module_platform_driver(rockchip_vpu_driver);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Alpha Lin <Alpha.Lin@Rock-Chips.com>");
MODULE_AUTHOR("Tomasz Figa <tfiga@chromium.org>");
MODULE_AUTHOR("Ezequiel Garcia <ezequiel@collabora.com>");
MODULE_DESCRIPTION("Rockchip VPU codec driver");
| 26.732342 | 78 | 0.725629 | [
"model"
] |
9626643462172198ef4f28a49f5f1336134b385b | 6,425 | h | C | hardware/probe-test-stm32/lib/defs_base.h | aehparta/gauge | 67f95aa8fcd090473b5d44f0e147a17f8160da11 | [
"MIT"
] | null | null | null | hardware/probe-test-stm32/lib/defs_base.h | aehparta/gauge | 67f95aa8fcd090473b5d44f0e147a17f8160da11 | [
"MIT"
] | null | null | null | hardware/probe-test-stm32/lib/defs_base.h | aehparta/gauge | 67f95aa8fcd090473b5d44f0e147a17f8160da11 | [
"MIT"
] | null | null | null | #pragma once
#include "common.h"
// AUTHOR : Ondrej Hruska
// DATE : 12/2015
// DESCR : Base library file. This file must be included before any other library
// files. This file defines memory map and base addresses of peripherals.
#define FLASH_BASE 0x08000000 // FLASH base address in the alias region
#define SRAM_BASE 0x20000000 // SRAM base address in the alias region
#define PERIPH_BASE 0x40000000 // Peripheral base address in the alias region
#define SRAM_BB_BASE (SRAM_BASE + 0x02000000) // SRAM base address in the bit-band region
#define PERIPH_BB_BASE (PERIPH_BASE + 0x02000000) // Peripheral base address in the bit-band region
// ------------------------- System Config Blocks -----------------------------
#define SCS_BASE 0xE000E000 // System Control Space base
#define SCB (SCS_BASE + 0x0D00) // System Control Block base
#define NVIC (SCS_BASE + 0x0100) // Nested Interrupt Vector Controller base
#define OB_CTRL 0x1FF80000 // FLASH Option Bytes base address
#define AES_BASE 0x50060000 // Encryption module
#define FSMC_BASE 0xA0000000 // External Memory Control base
#define DBGMCU_BASE 0xE0042000 // Debug MCU registers base address
#define INFO_BASE (0x1ff00000U)
// ----------------------------- Peripherals ----------------------------------
// *** Peripheral bus bases ***
#define APB1_BASE PERIPH_BASE // Advanced Peripheral Bus 1 base
#define APB2_BASE (PERIPH_BASE + 0x10000) // Advanced Peripheral Bus 2 base
#define AHB_BASE (PERIPH_BASE + 0x20000) // Advanced High-speed Bus base
// *** Peripheral Bus 1 devices ***
#define TIM2 (APB1_BASE + 0x0000) // Timer bases
#define TIM3 (APB1_BASE + 0x0400)
#define TIM4 (APB1_BASE + 0x0800)
#define TIM5 (APB1_BASE + 0x0C00)
#define TIM6 (APB1_BASE + 0x1000)
#define TIM7 (APB1_BASE + 0x1400)
#define LCD (APB1_BASE + 0x2400) // LCD controller base
#define RTC (APB1_BASE + 0x2800) // RTC base
#define WWDG (APB1_BASE + 0x2C00) // Window Watchdog base
#define IWDG (APB1_BASE + 0x3000) // Independent Watchdog base
#define SPI2 (APB1_BASE + 0x3800) // SPI base
#define SPI3 (APB1_BASE + 0x3C00)
#define USART2 (APB1_BASE + 0x4400) // USART base
#define USART3 (APB1_BASE + 0x4800)
#define UART4 (APB1_BASE + 0x4C00) // UART base (?)
#define UART5 (APB1_BASE + 0x5000)
#define I2C1 (APB1_BASE + 0x5400) // I2C base
#define I2C2 (APB1_BASE + 0x5800)
#define PWR_CTRL (APB1_BASE + 0x7000) // Power Control block base
#define DAC_BASE (APB1_BASE + 0x7400) // D/A config base
#define COMP_BASE (APB1_BASE + 0x7C00) // Analog Comparator base
#define RI_BASE (APB1_BASE + 0x7C04) // Routing Interface base (analog pin connections)
#define OPAMP_BASE (APB1_BASE + 0x7C5C) // OpAmp config base
#define USB_BASE (APB1_BASE + 0x5C00) // USB registers base
// *** Peripheral Bus 2 devices ***
#define TIM9 (APB2_BASE + 0x0800) // Timer base
#define TIM10 (APB2_BASE + 0x0C00)
#define TIM11 (APB2_BASE + 0x1000)
#define SYSCFG_BASE (APB2_BASE + 0x0000) // System config block base
#define EXTI_BASE (APB2_BASE + 0x0400) // External interrupt settings base
#define ADC1_BASE (APB2_BASE + 0x2400) // A/D 1
#define ADCC_BASE (APB2_BASE + 0x2700) // common A/D registers base
#define SDIO (APB2_BASE + 0x2C00) // SD host
#define SPI1 (APB2_BASE + 0x3000) // SPI
#define USART1 (APB2_BASE + 0x3800)
// *** High Speed Bus devices ***
#define GPIO_BASE (AHB_BASE + 0x0000) // GPIO block base
#define CRC_BASE (AHB_BASE + 0x3000) // CRC module base
#define RCC_BASE (AHB_BASE + 0x3800) // Reset and Clock Config base
#define DMA1 (AHB_BASE + 0x6000) // DMA control base
#define DMA2 (AHB_BASE + 0x6400)
#define FLASH_CTRL (AHB_BASE + 0x3C00) // FLASH control base
/* MPU: Memory protection unit */
#define MPU_BASE (SCS_BASE + 0x0D90)
// ----
/* Device Electronic Signature */
#define DESIG_FLASH_SIZE_BASE (INFO_BASE + 0x8004C)
#define DESIG_UNIQUE_ID_BASE (INFO_BASE + 0x80050)
#define DESIG_UNIQUE_ID0 MMIO32(DESIG_UNIQUE_ID_BASE)
#define DESIG_UNIQUE_ID1 MMIO32(DESIG_UNIQUE_ID_BASE + 4)
#define DESIG_UNIQUE_ID2 MMIO32(DESIG_UNIQUE_ID_BASE + 0x14)
/* ST provided factory calibration values @ 3.0V */
//#define ST_VREFINT_CAL MMIO16(0x1FF80078)
//#define ST_TSENSE_CAL1_30C MMIO16(0x1FF8007A)
//#define ST_TSENSE_CAL2_110C MMIO16(0x1FF8007E)
#define ST_VREFINT_CAL MMIO16(0x1FF800F8)
#define ST_TSENSE_CAL1_30C MMIO16(0x1FF800FA)
#define ST_TSENSE_CAL2_110C MMIO16(0x1FF800FE)
// ---- ARMv7M+ only ----
#define PPBI_BASE (0xE0000000U)
/* STE: Software Trigger Interrupt Register */
#define STIR_BASE (SCS_BASE + 0x0F00)
/* ID: ID space */
#define ID_BASE (SCS_BASE + 0x0FD0)
/* ITR: Interrupt Type Register */
#define ITR_BASE (SCS_BASE + 0x0000)
/* ITM: Instrumentation Trace Macrocell */
#define ITM_BASE (PPBI_BASE + 0x0000)
/* DWT: Data Watchpoint and Trace unit */
#define DWT_BASE (PPBI_BASE + 0x1000)
/* FPB: Flash Patch and Breakpoint unit */
#define FPB_BASE (PPBI_BASE + 0x2000)
#define TPIU_BASE (PPBI_BASE + 0x40000)
| 44.310345 | 115 | 0.559533 | [
"vector"
] |
962825920a5c286a6d8555a8fd7a19fa683ba463 | 6,969 | h | C | xcmnlib/include/utility/fast_mutex.h | jjzhang166/zzilla_opencvr | b8914d59908fbb449c1d0359ebcb4788ab1d7c8e | [
"MIT"
] | 2 | 2017-09-16T13:59:15.000Z | 2019-04-24T03:25:36.000Z | xcmnlib/include/utility/fast_mutex.h | jjzhang166/opencvr | b8914d59908fbb449c1d0359ebcb4788ab1d7c8e | [
"MIT"
] | null | null | null | xcmnlib/include/utility/fast_mutex.h | jjzhang166/opencvr | b8914d59908fbb449c1d0359ebcb4788ab1d7c8e | [
"MIT"
] | 1 | 2019-04-24T03:25:40.000Z | 2019-04-24T03:25:40.000Z | /* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*-
Copyright (c) 2010-2012 Marcus Geelnard
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef _FAST_MUTEX_H_
#define _FAST_MUTEX_H_
/// @file
// Which platform are we on?
#if !defined(_TTHREAD_PLATFORM_DEFINED_)
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
#define _TTHREAD_WIN32_
#else
#define _TTHREAD_POSIX_
#endif
#define _TTHREAD_PLATFORM_DEFINED_
#endif
// Check if we can support the assembly language level implementation (otherwise
// revert to the system API)
#if (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) || \
(defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) || \
(defined(__GNUC__) && (defined(__ppc__)))
//#define _FAST_MUTEX_ASM_
#define _FAST_MUTEX_SYS_
#else
#define _FAST_MUTEX_SYS_
#endif
#if defined(_TTHREAD_WIN32_)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#define __UNDEF_LEAN_AND_MEAN
#endif
#include <windows.h>
#ifdef __UNDEF_LEAN_AND_MEAN
#undef WIN32_LEAN_AND_MEAN
#undef __UNDEF_LEAN_AND_MEAN
#endif
#else
#ifdef _FAST_MUTEX_ASM_
#include <sched.h>
#else
#include <pthread.h>
#endif
#endif
namespace tthread {
/// Fast mutex class.
/// This is a mutual exclusion object for synchronizing access to shared
/// memory areas for several threads. It is similar to the tthread::mutex class,
/// but instead of using system level functions, it is implemented as an atomic
/// spin lock with very low CPU overhead.
///
/// The \c fast_mutex class is NOT compatible with the \c condition_variable
/// class (however, it IS compatible with the \c lock_guard class). It should
/// also be noted that the \c fast_mutex class typically does not provide
/// as accurate thread scheduling as a the standard \c mutex class does.
///
/// Because of the limitations of the class, it should only be used in
/// situations where the mutex needs to be locked/unlocked very frequently.
///
/// @note The "fast" version of this class relies on inline assembler language,
/// which is currently only supported for 32/64-bit Intel x86/AMD64 and
/// PowerPC architectures on a limited number of compilers (GNU g++ and MS
/// Visual C++).
/// For other architectures/compilers, system functions are used instead.
class fast_mutex {
public:
/// Constructor.
#if defined(_FAST_MUTEX_ASM_)
fast_mutex() : mLock(0) {}
#else
fast_mutex()
{
#if defined(_TTHREAD_WIN32_)
InitializeCriticalSection(&mHandle);
#elif defined(_TTHREAD_POSIX_)
pthread_mutex_init(&mHandle, NULL);
#endif
}
#endif
#if !defined(_FAST_MUTEX_ASM_)
/// Destructor.
~fast_mutex()
{
#if defined(_TTHREAD_WIN32_)
DeleteCriticalSection(&mHandle);
#elif defined(_TTHREAD_POSIX_)
pthread_mutex_destroy(&mHandle);
#endif
}
#endif
/// Lock the mutex.
/// The method will block the calling thread until a lock on the mutex can
/// be obtained. The mutex remains locked until \c unlock() is called.
/// @see lock_guard
inline void lock()
{
#if defined(_FAST_MUTEX_ASM_)
bool gotLock;
do {
gotLock = try_lock();
if(!gotLock)
{
#if defined(_TTHREAD_WIN32_)
Sleep(0);
#elif defined(_TTHREAD_POSIX_)
sched_yield();
#endif
}
} while(!gotLock);
#else
#if defined(_TTHREAD_WIN32_)
EnterCriticalSection(&mHandle);
#elif defined(_TTHREAD_POSIX_)
pthread_mutex_lock(&mHandle);
#endif
#endif
}
/// Try to lock the mutex.
/// The method will try to lock the mutex. If it fails, the function will
/// return immediately (non-blocking).
/// @return \c true if the lock was acquired, or \c false if the lock could
/// not be acquired.
inline bool try_lock()
{
#if defined(_FAST_MUTEX_ASM_)
int oldLock;
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
asm volatile (
"movl $1,%%eax\n\t"
"xchg %%eax,%0\n\t"
"movl %%eax,%1\n\t"
: "=m" (mLock), "=m" (oldLock)
:
: "%eax", "memory"
);
#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
int *ptrLock = &mLock;
__asm {
mov eax,1
mov ecx,ptrLock
xchg eax,[ecx]
mov oldLock,eax
}
#elif defined(__GNUC__) && (defined(__ppc__))
int newLock = 1;
asm volatile (
"\n1:\n\t"
"lwarx %0,0,%1\n\t"
"cmpwi 0,%0,0\n\t"
"bne- 2f\n\t"
"stwcx. %2,0,%1\n\t"
"bne- 1b\n\t"
"isync\n"
"2:\n\t"
: "=&r" (oldLock)
: "r" (&mLock), "r" (newLock)
: "cr0", "memory"
);
#endif
return (oldLock == 0);
#else
#if defined(_TTHREAD_WIN32_)
return TryEnterCriticalSection(&mHandle) ? true : false;
#elif defined(_TTHREAD_POSIX_)
return (pthread_mutex_trylock(&mHandle) == 0) ? true : false;
#endif
#endif
}
/// Unlock the mutex.
/// If any threads are waiting for the lock on this mutex, one of them will
/// be unblocked.
inline void unlock()
{
#if defined(_FAST_MUTEX_ASM_)
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
asm volatile (
"movl $0,%%eax\n\t"
"xchg %%eax,%0\n\t"
: "=m" (mLock)
:
: "%eax", "memory"
);
#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
int *ptrLock = &mLock;
__asm {
mov eax,0
mov ecx,ptrLock
xchg eax,[ecx]
}
#elif defined(__GNUC__) && (defined(__ppc__))
asm volatile (
"sync\n\t" // Replace with lwsync where possible?
: : : "memory"
);
mLock = 0;
#endif
#else
#if defined(_TTHREAD_WIN32_)
LeaveCriticalSection(&mHandle);
#elif defined(_TTHREAD_POSIX_)
pthread_mutex_unlock(&mHandle);
#endif
#endif
}
private:
#if defined(_FAST_MUTEX_ASM_)
int mLock;
#else
#if defined(_TTHREAD_WIN32_)
CRITICAL_SECTION mHandle;
#elif defined(_TTHREAD_POSIX_)
pthread_mutex_t mHandle;
#endif
#endif
};
}
#endif // _FAST_MUTEX_H_
| 27.876 | 80 | 0.652891 | [
"object"
] |
962a748b817ec79f4c415530b5236a39b50853e7 | 1,832 | h | C | Source/UROSBridge/Public/std_msgs/UInt16.h | Funnyach/UROSBridge | 2823e459a03c4bb5b7bd06f835615b5a96aacf58 | [
"BSD-3-Clause"
] | null | null | null | Source/UROSBridge/Public/std_msgs/UInt16.h | Funnyach/UROSBridge | 2823e459a03c4bb5b7bd06f835615b5a96aacf58 | [
"BSD-3-Clause"
] | null | null | null | Source/UROSBridge/Public/std_msgs/UInt16.h | Funnyach/UROSBridge | 2823e459a03c4bb5b7bd06f835615b5a96aacf58 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "ROSBridgeMsg.h"
namespace std_msgs
{
class UInt16 : public FROSBridgeMsg
{
uint16 Data;
public:
UInt16()
{
MsgType = TEXT("std_msgs/UInt16");
}
UInt16(uint16 InData)
:
Data(InData)
{
MsgType = TEXT("std_msgs/UInt16");
}
~UInt16() override {}
// Getters
uint16 GetData() const { return Data; }
// Setters
void SetData(uint16 InData) { Data = InData; }
virtual void FromJson(TSharedPtr<FJsonObject> JsonObject) override
{
Data = JsonObject->GetNumberField(TEXT("data"));
}
virtual void FromBson(TSharedPtr<FBsonObject> BsonObject) override
{
Data = BsonObject->GetNumberField(TEXT("data"));
}
static UInt16 GetFromJson(TSharedPtr<FJsonObject> JsonObject)
{
UInt16 Result;
Result.FromJson(JsonObject);
return Result;
}
static UInt16 GetFromBson(TSharedPtr<FBsonObject> BsonObject)
{
UInt16 Result;
Result.FromBson(BsonObject);
return Result;
}
virtual TSharedPtr<FJsonObject> ToJsonObject() const override
{
TSharedPtr<FJsonObject> Object = MakeShareable<FJsonObject>(new FJsonObject());
Object->SetNumberField(TEXT("data"), Data);
return Object;
}
virtual TSharedPtr<FBsonObject> ToBsonObject() const override
{
TSharedPtr<FBsonObject> Object = MakeShareable<FBsonObject>(new FBsonObject());
Object->SetNumberField(TEXT("data"), Data);
return Object;
}
virtual FString ToString() const override
{
return TEXT("UInt16 { data = ") + FString::FromInt(Data) +
TEXT(" } ");
}
virtual FString ToYamlString() const override
{
FString OutputString;
TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);
FJsonSerializer::Serialize(ToJsonObject().ToSharedRef(), Writer);
return OutputString;
}
};
} | 18.886598 | 84 | 0.68286 | [
"object"
] |
962c91c49bb8d8caefe2bbaa127934f12361f9f8 | 15,816 | h | C | libgpopt/include/gpopt/search/CGroup.h | chrishajas/gporca | 456b2b313efd0e3721db64dc96e601b272c30bbf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/include/gpopt/search/CGroup.h | chrishajas/gporca | 456b2b313efd0e3721db64dc96e601b272c30bbf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/include/gpopt/search/CGroup.h | chrishajas/gporca | 456b2b313efd0e3721db64dc96e601b272c30bbf | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2009 - 2011 EMC Corp.
//
// @filename:
// CGroup.h
//
// @doc:
// Group of equivalent expressions in the Memo structure
//---------------------------------------------------------------------------
#ifndef GPOPT_CGroup_H
#define GPOPT_CGroup_H
#include "gpos/base.h"
#include "naucrates/statistics/CStatistics.h"
#include "gpos/common/CDynamicPtrArray.h"
#include "gpos/common/CSyncHashtable.h"
#include "gpos/common/CSyncList.h"
#include "gpopt/search/CJobQueue.h"
#include "gpopt/operators/CLogical.h"
#include "gpopt/search/CTreeMap.h"
#define GPOPT_INVALID_GROUP_ID gpos::ulong_max
namespace gpopt
{
using namespace gpos;
using namespace gpnaucrates;
// forward declarations
class CGroup;
class CGroupExpression;
class DrvdPropArray;
class CDrvdPropCtxtPlan;
class CGroupProxy;
class COptimizationContext;
class CCostContext;
class CReqdPropPlan;
class CReqdPropRelational;
class CExpression;
// type definitions
// array of groups
typedef CDynamicPtrArray<CGroup, CleanupNULL> CGroupArray;
// map required plan props to cost lower bound of corresponding plan
typedef CHashMap<CReqdPropPlan, CCost, CReqdPropPlan::UlHashForCostBounding, CReqdPropPlan::FEqualForCostBounding,
CleanupRelease<CReqdPropPlan>, CleanupDelete<CCost> > ReqdPropPlanToCostMap;
// optimization levels in ascending order,
// under a given optimization context, group expressions in higher levels
// must be optimized before group expressions in lower levels,
// a group expression sets its level in CGroupExpression::SetOptimizationLevel()
enum EOptimizationLevel
{
EolLow = 0, // low optimization level, this is the default level
EolHigh, // high optimization level
EolSentinel
};
//---------------------------------------------------------------------------
// @class:
// CGroup
//
// @doc:
// Group of equivalent expressions in the Memo structure
//
//---------------------------------------------------------------------------
class CGroup : public CRefCount
{
friend class CGroupProxy;
public:
// type definition of optimization context hash table
typedef
CSyncHashtable<
COptimizationContext, // entry
COptimizationContext /* search key */> ShtOC;
// states of a group
enum EState
{
estUnexplored, // initial state
estExploring, // ongoing exploration
estExplored, // done exploring
estImplementing, // ongoing implementation
estImplemented, // done implementing
estOptimizing, // ongoing optimization
estOptimized, // done optimizing
estSentinel
};
private:
// definition of hash table iter
typedef
CSyncHashtableIter<
COptimizationContext, // entry
COptimizationContext> ShtIter;
// definition of hash table iter accessor
typedef
CSyncHashtableAccessByIter<
COptimizationContext, // entry
COptimizationContext> ShtAccIter;
// definition of hash table accessor
typedef
CSyncHashtableAccessByKey<
COptimizationContext, // entry
COptimizationContext> ShtAcc;
//---------------------------------------------------------------------------
// @class:
// SContextLink
//
// @doc:
// Internal structure to remember processed links in plan enumeration
//
//---------------------------------------------------------------------------
struct SContextLink
{
private:
// cost context in a parent group
CCostContext *m_pccParent;
// index used when treating current group as a child of group expression
ULONG m_ulChildIndex;
// optimization context used to locate group expressions in
// current group to be linked with parent group expression
COptimizationContext *m_poc;
public:
// ctor
SContextLink(CCostContext *pccParent, ULONG child_index, COptimizationContext *poc);
// dtor
virtual
~SContextLink();
// hash function
static
ULONG HashValue(const SContextLink *pclink);
// equality function
static
BOOL Equals
(
const SContextLink *pclink1,
const SContextLink *pclink2
);
}; // struct SContextLink
// map of processed links in TreeMap structure
typedef CHashMap<SContextLink, BOOL, SContextLink::HashValue, SContextLink::Equals,
CleanupDelete<SContextLink>, CleanupDelete<BOOL> > LinkMap;
// map of computed stats objects during costing
typedef CHashMap<COptimizationContext, IStatistics, COptimizationContext::UlHashForStats, COptimizationContext::FEqualForStats,
CleanupRelease<COptimizationContext>, CleanupRelease<IStatistics> > OptCtxtToIStatisticsMap;
// memory pool
CMemoryPool *m_mp;
// id is used when printing memo contents
ULONG m_id;
// true if group hold scalar expressions
BOOL m_fScalar;
// join keys for outer child (only for scalar groups) (used by hash & merge joins)
CExpressionArray *m_pdrgpexprJoinKeysOuter;
// join keys for inner child (only for scalar groups) (used by hash & merge joins)
CExpressionArray *m_pdrgpexprJoinKeysInner;
// list of group expressions
CList<CGroupExpression> m_listGExprs;
// list of duplicate group expressions identified by group merge
CList<CGroupExpression> m_listDupGExprs;
// group derived properties
DrvdPropArray *m_pdp;
// group stats
IStatistics *m_pstats;
// scalar expression for stat derivation
CExpression *m_pexprScalar;
// dummy cost context used in scalar groups for plan enumeration
CCostContext *m_pccDummy;
// pointer to group containing the group expressions
// of all duplicate groups
CGroup *m_pgroupDuplicate;
// map of processed links
LinkMap *m_plinkmap;
// map of computed stats during costing
OptCtxtToIStatisticsMap *m_pstatsmap;
// hashtable of optimization contexts
ShtOC m_sht;
// number of group expressions
ULONG m_ulGExprs;
// map of cost lower bounds
ReqdPropPlanToCostMap *m_pcostmap;
// number of optimization contexts
ULONG_PTR m_ulpOptCtxts;
// current state
EState m_estate;
// maximum optimization level of member group expressions
EOptimizationLevel m_eolMax;
// were new logical operators added to the group?
BOOL m_fHasNewLogicalOperators;
// the id of the CTE producer (if any)
ULONG m_ulCTEProducerId;
// does the group have any CTE consumer
BOOL m_fCTEConsumer;
// exploration job queue
CJobQueue m_jqExploration;
// implementation job queue
CJobQueue m_jqImplementation;
// private copy ctor
CGroup(const CGroup&);
// cleanup optimization contexts on destruction
void CleanupContexts();
// increment number of optimization contexts
ULONG_PTR UlpIncOptCtxts()
{
return m_ulpOptCtxts++;
}
// the following functions are only accessed through group proxy
// setter of group id
void SetId(ULONG id);
// setter of group state
void SetState(EState estNewState);
// set hash join keys
void SetJoinKeys(CExpressionArray *pdrgpexprOuter, CExpressionArray *pdrgpexprInner);
// insert new group expression
void Insert(CGroupExpression *pgexpr);
// move duplicate group expression to duplicates list
void MoveDuplicateGExpr(CGroupExpression *pgexpr);
// initialize group's properties
void InitProperties(DrvdPropArray *pdp);
// initialize group's stats
void InitStats(IStatistics *stats);
// retrieve first group expression
CGroupExpression *PgexprFirst();
// retrieve next group expression
CGroupExpression *PgexprNext(CGroupExpression *pgexpr);
// return true if first promise is better than second promise
BOOL FBetterPromise
(
CMemoryPool *mp,
CLogical::EStatPromise espFst,
CGroupExpression *pgexprFst,
CLogical::EStatPromise espSnd,
CGroupExpression *pgexprSnd
)
const;
// derive stats recursively on child groups
CLogical::EStatPromise EspDerive
(
CMemoryPool *pmpLocal,
CMemoryPool *pmpGlobal,
CGroupExpression *pgexpr,
CReqdPropRelational *prprel,
IStatisticsArray *stats_ctxt,
BOOL fDeriveChildStats
);
// reset computed stats
void ResetStats();
// helper function to add links in child groups
void RecursiveBuildTreeMap
(
CMemoryPool *mp,
COptimizationContext *poc,
CCostContext *pccParent,
CGroupExpression *pgexprCurrent,
ULONG child_index,
CTreeMap<CCostContext, CExpression, CDrvdPropCtxtPlan, CCostContext::HashValue, CCostContext::Equals> *ptmap
);
// print scalar group properties
IOstream &OsPrintGrpScalarProps(IOstream &os, const CHAR *szPrefix);
// print group properties
IOstream &OsPrintGrpProps(IOstream &os, const CHAR *szPrefix);
// print group optimization contexts
IOstream &OsPrintGrpOptCtxts(IOstream &os, const CHAR *szPrefix);
// initialize and return empty stats for this group
IStatistics *PstatsInitEmpty(CMemoryPool *pmpGlobal);
// find the group expression having the best stats promise
CGroupExpression *PgexprBestPromise
(
CMemoryPool *pmpLocal,
CMemoryPool *pmpGlobal,
CReqdPropRelational *prprelInput,
IStatisticsArray *stats_ctxt
);
public:
// ctor
CGroup(CMemoryPool *mp, BOOL fScalar = false);
// dtor
~CGroup();
// id accessor
ULONG Id() const
{
return m_id;
}
// group properties accessor
DrvdPropArray *Pdp() const
{
return m_pdp;
}
// group stats accessor
IStatistics *Pstats() const;
// attempt initializing stats with the given stat object
BOOL FInitStats(IStatistics *stats);
// append given stats object to group stats
void AppendStats(CMemoryPool *mp, IStatistics *stats);
// accessor of maximum optimization level of member group expressions
EOptimizationLevel EolMax() const
{
return m_eolMax;
}
// does group hold scalar expressions ?
BOOL FScalar() const
{
return m_fScalar;
}
// join keys of outer child
CExpressionArray *PdrgpexprJoinKeysOuter() const
{
return m_pdrgpexprJoinKeysOuter;
}
// join keys of inner child
CExpressionArray *PdrgpexprJoinKeysInner() const
{
return m_pdrgpexprJoinKeysInner;
}
// return cached scalar expression
CExpression *PexprScalar() const
{
return m_pexprScalar;
}
// return dummy cost context for scalar group
CCostContext *PccDummy() const
{
GPOS_ASSERT(FScalar());
return m_pccDummy;
}
// hash function
ULONG HashValue() const;
// number of group expressions accessor
ULONG UlGExprs() const
{
return m_ulGExprs;
}
// optimization contexts hash table accessor
ShtOC &Sht()
{
return m_sht;
}
// exploration job queue accessor
CJobQueue *PjqExploration()
{
return &m_jqExploration;
}
// implementation job queue accessor
CJobQueue *PjqImplementation()
{
return &m_jqImplementation;
}
// has group been explored?
BOOL FExplored() const
{
return estExplored <= m_estate;
}
// has group been implemented?
BOOL FImplemented() const
{
return estImplemented <= m_estate;
}
// has group been optimized?
BOOL FOptimized() const
{
return estOptimized <= m_estate;
}
// were new logical operators added to the group?
BOOL FHasNewLogicalOperators() const
{
return m_fHasNewLogicalOperators;
}
// reset has new logical operators flag
void ResetHasNewLogicalOperators()
{
m_fHasNewLogicalOperators = false;
}
// reset group state
void ResetGroupState();
// Check if we need to reset computed stats
BOOL FResetStats();
// returns true if stats can be derived on this group
BOOL FStatsDerivable(CMemoryPool *mp);
// reset group job queues
void ResetGroupJobQueues();
// check if group has duplicates
BOOL FDuplicateGroup() const
{
return NULL != m_pgroupDuplicate;
}
// duplicate group accessor
CGroup *PgroupDuplicate() const
{
return m_pgroupDuplicate;
}
// resolve master duplicate group;
// this is the group that will host all expressions in current group after merging
void ResolveDuplicateMaster();
// add duplicate group
void AddDuplicateGrp(CGroup *pgroup);
// merge group with its duplicate - not thread-safe
void MergeGroup();
// lookup a given context in contexts hash table
COptimizationContext *PocLookup(CMemoryPool *mp, CReqdPropPlan *prpp, ULONG ulSearchStageIndex);
// lookup the best context across all stages for the given required properties
COptimizationContext *PocLookupBest(CMemoryPool *mp, ULONG ulSearchStages, CReqdPropPlan *prpp);
// insert given context into contexts hash table
COptimizationContext *PocInsert(COptimizationContext *poc);
// update the best group cost under the given optimization context
void UpdateBestCost(COptimizationContext *poc, CCostContext *pcc);
// lookup best expression under given optimization context
CGroupExpression *PgexprBest(COptimizationContext *poc);
// materialize a scalar expression for stat derivation if this is a scalar group
void CreateScalarExpression();
// materialize a dummy cost context attached to the first group expression
void CreateDummyCostContext();
// return the CTE producer ID in the group (if any)
ULONG UlCTEProducerId() const
{
return m_ulCTEProducerId;
}
// check if there are any CTE producers in the group
BOOL FHasCTEProducer() const
{
return (gpos::ulong_max != m_ulCTEProducerId);
}
// check if there are any CTE consumers in the group
BOOL FHasAnyCTEConsumer() const
{
return m_fCTEConsumer;
}
// derive statistics recursively on group
IStatistics *PstatsRecursiveDerive
(
CMemoryPool *pmpLocal,
CMemoryPool *pmpGlobal,
CReqdPropRelational *prprel,
IStatisticsArray *stats_ctxt
);
// find group expression with best stats promise and the same given children
CGroupExpression *PgexprBestPromise(CMemoryPool *mp, CGroupExpression *pgexprToMatch);
// link parent group expression to group members
void BuildTreeMap
(
CMemoryPool *mp,
COptimizationContext *poc,
CCostContext *pccParent,
ULONG child_index,
CTreeMap<CCostContext, CExpression, CDrvdPropCtxtPlan, CCostContext::HashValue, CCostContext::Equals> *ptmap
);
// reset link map used in plan enumeration
void ResetLinkMap();
// retrieve the group expression containing a CTE Consumer operator
CGroupExpression *PgexprAnyCTEConsumer();
// compute stats during costing
IStatistics *PstatsCompute(COptimizationContext *poc, CExpressionHandle &exprhdl, CGroupExpression *pgexpr);
// compute cost lower bound for the plan satisfying given required properties
CCost CostLowerBound(CMemoryPool *mp, CReqdPropPlan *prppInput);
// matching of pairs of arrays of groups
static
BOOL FMatchGroups
(
CGroupArray *pdrgpgroupFst,
CGroupArray *pdrgpgroupSnd
);
// matching of pairs of arrays of groups while skipping scalar groups
static
BOOL FMatchNonScalarGroups
(
CGroupArray *pdrgpgroupFst,
CGroupArray *pdrgpgroupSnd
);
// determine if a pair of groups are duplicates
static
BOOL FDuplicateGroups
(
CGroup *pgroupFst,
CGroup *pgroupSnd
);
// print function
IOstream &OsPrint(IOstream &os);
// slink for group list in memo
SLink m_link;
#ifdef GPOS_DEBUG
// debug print; for interactive debugging sessions only
void DbgPrint();
#endif
}; // class CGroup
}
#endif // !GPOPT_CGroup_H
// EOF
| 25.265176 | 130 | 0.693665 | [
"object"
] |
96308e071f3578f8594015ef5af1061123830be5 | 4,205 | h | C | Utils/lcc/src/stab.h | xopr/gigatron-rom | 3db078626c23f259702962488e47184e7feda9e9 | [
"BSD-2-Clause"
] | 172 | 2018-02-26T19:56:11.000Z | 2022-03-31T17:10:16.000Z | Utils/lcc/src/stab.h | xopr/gigatron-rom | 3db078626c23f259702962488e47184e7feda9e9 | [
"BSD-2-Clause"
] | 140 | 2018-01-13T09:57:11.000Z | 2022-02-15T13:22:05.000Z | Utils/lcc/src/stab.h | xopr/gigatron-rom | 3db078626c23f259702962488e47184e7feda9e9 | [
"BSD-2-Clause"
] | 78 | 2018-01-13T01:07:37.000Z | 2022-03-09T07:59:18.000Z | /* @(#)stab.h 1.11 92/05/11 SMI */
/* $Id$ */
/*
* Copyright (c) 1990 by Sun Microsystems, Inc.
*/
/*
* This file gives definitions supplementing <a.out.h>
* for permanent symbol table entries.
* These must have one of the N_STAB bits on,
* and are subject to relocation according to the masks in <a.out.h>.
*/
#ifndef _STAB_H
#define _STAB_H
#if !defined(_a_out_h) && !defined(_A_OUT_H)
/* this file contains fragments of a.out.h and stab.h relevant to
* support of stabX processing within ELF files - see the
* Format of a symbol table entry
*/
struct nlist {
union {
char *n_name; /* for use when in-core */
long n_strx; /* index into file string table */
} n_un;
unsigned char n_type; /* type flag (N_TEXT,..) */
char n_other; /* unused */
short n_desc; /* see <stab.h> */
unsigned long n_value; /* value of symbol (or sdb offset) */
};
/*
* Simple values for n_type.
*/
#define N_UNDF 0x0 /* undefined */
#define N_ABS 0x2 /* absolute */
#define N_TEXT 0x4 /* text */
#define N_DATA 0x6 /* data */
#define N_BSS 0x8 /* bss */
#define N_COMM 0x12 /* common (internal to ld) */
#define N_FN 0x1f /* file name symbol */
#define N_EXT 01 /* external bit, or'ed in */
#define N_TYPE 0x1e /* mask for all the type bits */
#endif
/*
* for symbolic debugger, sdb(1):
*/
#define N_GSYM 0x20 /* global symbol: name,,0,type,0 */
#define N_FNAME 0x22 /* procedure name (f77 kludge): name,,0 */
#define N_FUN 0x24 /* procedure: name,,0,linenumber,address */
#define N_STSYM 0x26 /* static symbol: name,,0,type,address */
#define N_LCSYM 0x28 /* .lcomm symbol: name,,0,type,address */
#define N_MAIN 0x2a /* name of main routine : name,,0,0,0 */
#define N_ROSYM 0x2c /* ro_data objects */
#define N_OBJ 0x38 /* object file path or name */
#define N_OPT 0x3c /* compiler options */
#define N_RSYM 0x40 /* register sym: name,,0,type,register */
#define N_SLINE 0x44 /* src line: 0,,0,linenumber,address */
#define N_FLINE 0x4c /* function start.end */
#define N_SSYM 0x60 /* structure elt: name,,0,type,struct_offset */
#define N_ENDM 0x62 /* last stab emitted for module */
#define N_SO 0x64 /* source file name: name,,0,0,address */
#define N_LSYM 0x80 /* local sym: name,,0,type,offset */
#define N_BINCL 0x82 /* header file: name,,0,0,0 */
#define N_SOL 0x84 /* #included file name: name,,0,0,address */
#define N_PSYM 0xa0 /* parameter: name,,0,type,offset */
#define N_EINCL 0xa2 /* end of include file */
#define N_ENTRY 0xa4 /* alternate entry: name,linenumber,address */
#define N_LBRAC 0xc0 /* left bracket: 0,,0,nesting level,address */
#define N_EXCL 0xc2 /* excluded include file */
#define N_RBRAC 0xe0 /* right bracket: 0,,0,nesting level,address */
#define N_BCOMM 0xe2 /* begin common: name,, */
#define N_ECOMM 0xe4 /* end common: name,, */
#define N_ECOML 0xe8 /* end common (local name): ,,address */
#define N_LENG 0xfe /* second stab entry with length information */
/*
* for the berkeley pascal compiler, pc(1):
*/
#define N_PC 0x30 /* global pascal symbol: name,,0,subtype,line */
#define N_WITH 0xea /* pascal with statement: type,,0,0,offset */
/*
* for code browser only
*/
#define N_BROWS 0x48 /* path to associated .cb file */
/*
* Optional langauge designations for N_SO
*/
#define N_SO_AS 1 /* Assembler */
#define N_SO_C 2 /* C */
#define N_SO_ANSI_C 3 /* ANSI C */
#define N_SO_CC 4 /* C++ */
#define N_SO_FORTRAN 5 /* Fortran 77 */
#define N_SO_PASCAL 6 /* Pascal */
/*
* Floating point type values
*/
#define NF_NONE 0 /* Undefined type */
#define NF_SINGLE 1 /* IEEE 32 bit float */
#define NF_DOUBLE 2 /* IEEE 64 bit float */
#define NF_COMPLEX 3 /* Fortran complex */
#define NF_COMPLEX16 4 /* Fortran double complex */
#define NF_COMPLEX32 5 /* Fortran complex*16 */
#define NF_LDOUBLE 6 /* Long double */
#endif
| 36.565217 | 75 | 0.614507 | [
"object"
] |
963346b7dc01e64ee53940add889ff882aeb7391 | 752,488 | h | C | NSudoDevilMode/MINT.h | geissbuehler/NSudo | 3fc1bddc5a2796e645394de2d1df48fa58e553f9 | [
"MIT"
] | 1 | 2021-01-05T09:46:54.000Z | 2021-01-05T09:46:54.000Z | NSudoDevilMode/MINT.h | geissbuehler/NSudo | 3fc1bddc5a2796e645394de2d1df48fa58e553f9 | [
"MIT"
] | null | null | null | NSudoDevilMode/MINT.h | geissbuehler/NSudo | 3fc1bddc5a2796e645394de2d1df48fa58e553f9 | [
"MIT"
] | null | null | null | /*
* PROJECT: Mouri's Internal NT API Collections (MINT)
* FILE: MINT.h
* PURPOSE: Definition for the Windows Internal API from ntdll.dll,
* samlib.dll and winsta.dll
*
* LICENSE: Relicensed under The MIT License from The CC BY 4.0 License
*
* DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com)
*/
/*
* This file is part of the Process Hacker project - https://processhacker.sf.io/
*
* You can redistribute this file and/or modify it under the terms of the
* Attribution 4.0 International (CC BY 4.0) license.
*
* You must give appropriate credit, provide a link to the license, and
* indicate if changes were made. You may do so in any reasonable manner, but
* not in any way that suggests the licensor endorses you or your use.
*/
#ifndef _MINT_
#define _MINT_
#ifdef __cplusplus
#ifdef MINT_USE_SEPARATE_NAMESPACE
namespace MINT {
#endif
#endif
// This header file provides access to Win32, plus NTSTATUS values and some access mask values.
#include <windows.h>
#include <windowsx.h>
#include <winioctl.h>
#undef STATUS_WAIT_0
#undef STATUS_ABANDONED_WAIT_0
#undef STATUS_USER_APC
#undef STATUS_TIMEOUT
#undef STATUS_PENDING
#undef DBG_EXCEPTION_HANDLED
#undef DBG_CONTINUE
#undef STATUS_SEGMENT_NOTIFICATION
#undef STATUS_FATAL_APP_EXIT
#undef DBG_TERMINATE_THREAD
#undef DBG_TERMINATE_PROCESS
#undef DBG_CONTROL_C
#undef DBG_PRINTEXCEPTION_C
#undef DBG_RIPEXCEPTION
#undef DBG_CONTROL_BREAK
#undef DBG_COMMAND_EXCEPTION
#undef STATUS_GUARD_PAGE_VIOLATION
#undef STATUS_DATATYPE_MISALIGNMENT
#undef STATUS_BREAKPOINT
#undef STATUS_SINGLE_STEP
#undef STATUS_LONGJUMP
#undef STATUS_UNWIND_CONSOLIDATE
#undef DBG_EXCEPTION_NOT_HANDLED
#undef STATUS_ACCESS_VIOLATION
#undef STATUS_IN_PAGE_ERROR
#undef STATUS_INVALID_HANDLE
#undef STATUS_INVALID_PARAMETER
#undef STATUS_NO_MEMORY
#undef STATUS_ILLEGAL_INSTRUCTION
#undef STATUS_NONCONTINUABLE_EXCEPTION
#undef STATUS_INVALID_DISPOSITION
#undef STATUS_ARRAY_BOUNDS_EXCEEDED
#undef STATUS_FLOAT_DENORMAL_OPERAND
#undef STATUS_FLOAT_DIVIDE_BY_ZERO
#undef STATUS_FLOAT_INEXACT_RESULT
#undef STATUS_FLOAT_INVALID_OPERATION
#undef STATUS_FLOAT_OVERFLOW
#undef STATUS_FLOAT_STACK_CHECK
#undef STATUS_FLOAT_UNDERFLOW
#undef STATUS_INTEGER_DIVIDE_BY_ZERO
#undef STATUS_INTEGER_OVERFLOW
#undef STATUS_PRIVILEGED_INSTRUCTION
#undef STATUS_STACK_OVERFLOW
#undef STATUS_DLL_NOT_FOUND
#undef STATUS_ORDINAL_NOT_FOUND
#undef STATUS_ENTRYPOINT_NOT_FOUND
#undef STATUS_CONTROL_C_EXIT
#undef STATUS_DLL_INIT_FAILED
#undef STATUS_FLOAT_MULTIPLE_FAULTS
#undef STATUS_FLOAT_MULTIPLE_TRAPS
#undef STATUS_REG_NAT_CONSUMPTION
#undef STATUS_HEAP_CORRUPTION
#undef STATUS_STACK_BUFFER_OVERRUN
#undef STATUS_INVALID_CRUNTIME_PARAMETER
#undef STATUS_ASSERTION_FAILURE
#undef STATUS_ENCLAVE_VIOLATION
#undef STATUS_SXS_EARLY_DEACTIVATION
#undef STATUS_SXS_INVALID_DEACTIVATION
#undef DBG_REPLY_LATER
#undef DBG_PRINTEXCEPTION_WIDE_C
#undef STATUS_ALREADY_REGISTERED
#undef STATUS_INTERRUPTED
#undef STATUS_THREAD_NOT_RUNNING
#include <ntstatus.h>
typedef double DOUBLE;
typedef GUID *PGUID;
// Desktop access rights
#define DESKTOP_ALL_ACCESS \
(DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | \
DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | \
DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_WRITEOBJECTS | \
STANDARD_RIGHTS_REQUIRED)
#define DESKTOP_GENERIC_READ \
(DESKTOP_ENUMERATE | DESKTOP_READOBJECTS | STANDARD_RIGHTS_READ)
#define DESKTOP_GENERIC_WRITE \
(DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | \
DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | DESKTOP_WRITEOBJECTS | \
STANDARD_RIGHTS_WRITE)
#define DESKTOP_GENERIC_EXECUTE \
(DESKTOP_SWITCHDESKTOP | STANDARD_RIGHTS_EXECUTE)
// Window station access rights
#define WINSTA_GENERIC_READ \
(WINSTA_ENUMDESKTOPS | WINSTA_ENUMERATE | WINSTA_READATTRIBUTES | \
WINSTA_READSCREEN | STANDARD_RIGHTS_READ)
#define WINSTA_GENERIC_WRITE \
(WINSTA_ACCESSCLIPBOARD | WINSTA_CREATEDESKTOP | WINSTA_WRITEATTRIBUTES | \
STANDARD_RIGHTS_WRITE)
#define WINSTA_GENERIC_EXECUTE \
(WINSTA_ACCESSGLOBALATOMS | WINSTA_EXITWINDOWS | STANDARD_RIGHTS_EXECUTE)
// WMI access rights
#define WMIGUID_GENERIC_READ \
(WMIGUID_QUERY | WMIGUID_NOTIFICATION | WMIGUID_READ_DESCRIPTION | \
STANDARD_RIGHTS_READ)
#define WMIGUID_GENERIC_WRITE \
(WMIGUID_SET | TRACELOG_CREATE_REALTIME | TRACELOG_CREATE_ONDISK | \
STANDARD_RIGHTS_WRITE)
#define WMIGUID_GENERIC_EXECUTE \
(WMIGUID_EXECUTE | TRACELOG_GUID_ENABLE | TRACELOG_LOG_EVENT | \
TRACELOG_ACCESS_REALTIME | TRACELOG_REGISTER_GUIDS | \
STANDARD_RIGHTS_EXECUTE)
// This header file provides access to NT APIs.
// Definitions are annotated to indicate their source. If a definition is not annotated, it has been
// retrieved from an official Microsoft source (NT headers, DDK headers, winnt.h).
// * "winbase" indicates that a definition has been reconstructed from a Win32-ized NT definition in
// winbase.h.
// * "rev" indicates that a definition has been reverse-engineered.
// * "dbg" indicates that a definition has been obtained from a debug message or assertion in a
// checked build of the kernel or file.
// Reliability:
// 1. No annotation.
// 2. dbg.
// 3. symbols, private. Types may be incorrect.
// 4. winbase. Names and types may be incorrect.
// 5. rev.
// Version
#include <SDKDDKVer.h>
#pragma comment(lib,"ntdll.lib")
#pragma comment(lib,"samlib.lib")
#pragma comment(lib,"winsta.lib")
// Warnings which disabled for compiling
#if _MSC_VER >= 1200
#pragma warning(push)
// nonstandard extension used : nameless struct/union
#pragma warning(disable:4201)
// 'struct_name' : structure was padded due to __declspec(align())
#pragma warning(disable:4324)
// 'enumeration': a forward declaration of an unscoped enumeration must have an
// underlying type (int assumed)
#pragma warning(disable:4471)
#endif
#ifdef __cplusplus
extern "C" {
#endif
// #include <phnt_ntdef.h>
#ifndef _NTDEF_
#define _NTDEF_
// This header file provides basic NT types not included in Win32. If you have included winnt.h
// (perhaps indirectly), you must use this file instead of ntdef.h.
#ifndef NOTHING
#define NOTHING
#endif
// Basic types
typedef struct _QUAD
{
union
{
__int64 UseThisFieldToCopy;
double DoNotUseThisField;
};
} QUAD, *PQUAD;
// This isn't in NT, but it's useful.
typedef struct DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) _QUAD_PTR
{
ULONG_PTR DoNotUseThisField1;
ULONG_PTR DoNotUseThisField2;
} QUAD_PTR, *PQUAD_PTR;
typedef ULONG LOGICAL;
typedef ULONG *PLOGICAL;
typedef _Success_(return >= 0) LONG NTSTATUS;
typedef NTSTATUS *PNTSTATUS;
// Cardinal types
typedef char CCHAR;
typedef short CSHORT;
typedef ULONG CLONG;
typedef CCHAR *PCCHAR;
typedef CSHORT *PCSHORT;
typedef CLONG *PCLONG;
typedef PCSTR PCSZ;
// Specific
typedef UCHAR KIRQL, *PKIRQL;
typedef LONG KPRIORITY;
typedef USHORT RTL_ATOM, *PRTL_ATOM;
typedef LARGE_INTEGER PHYSICAL_ADDRESS, *PPHYSICAL_ADDRESS;
// NT status macros
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#define NT_INFORMATION(Status) ((((ULONG)(Status)) >> 30) == 1)
#define NT_WARNING(Status) ((((ULONG)(Status)) >> 30) == 2)
#define NT_ERROR(Status) ((((ULONG)(Status)) >> 30) == 3)
#define NT_FACILITY_MASK 0xfff
#define NT_FACILITY_SHIFT 16
#define NT_FACILITY(Status) ((((ULONG)(Status)) >> NT_FACILITY_SHIFT) & NT_FACILITY_MASK)
#define NT_NTWIN32(Status) (NT_FACILITY(Status) == FACILITY_NTWIN32)
#define WIN32_FROM_NTSTATUS(Status) (((ULONG)(Status)) & 0xffff)
// Functions
#ifndef _WIN64
#define FASTCALL __fastcall
#else
#define FASTCALL
#endif
// Synchronization enumerations
typedef enum _EVENT_TYPE
{
NotificationEvent,
SynchronizationEvent
} EVENT_TYPE;
typedef enum _TIMER_TYPE
{
NotificationTimer,
SynchronizationTimer
} TIMER_TYPE;
typedef enum _WAIT_TYPE
{
WaitAll,
WaitAny,
WaitNotification
} WAIT_TYPE;
// Strings
typedef struct _STRING
{
USHORT Length;
USHORT MaximumLength;
_Field_size_bytes_part_opt_(MaximumLength, Length) PCHAR Buffer;
} STRING, *PSTRING, ANSI_STRING, *PANSI_STRING, OEM_STRING, *POEM_STRING;
typedef const STRING *PCSTRING;
typedef const ANSI_STRING *PCANSI_STRING;
typedef const OEM_STRING *PCOEM_STRING;
typedef struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
_Field_size_bytes_part_(MaximumLength, Length) PWCH Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef const UNICODE_STRING *PCUNICODE_STRING;
#define RTL_CONSTANT_STRING(s) { sizeof(s) - sizeof((s)[0]), sizeof(s), s }
// Balanced tree node
#define RTL_BALANCED_NODE_RESERVED_PARENT_MASK 3
typedef struct _RTL_BALANCED_NODE
{
union
{
struct _RTL_BALANCED_NODE *Children[2];
struct
{
struct _RTL_BALANCED_NODE *Left;
struct _RTL_BALANCED_NODE *Right;
};
};
union
{
UCHAR Red : 1;
UCHAR Balance : 2;
ULONG_PTR ParentValue;
};
} RTL_BALANCED_NODE, *PRTL_BALANCED_NODE;
#define RTL_BALANCED_NODE_GET_PARENT_POINTER(Node) \
((PRTL_BALANCED_NODE)((Node)->ParentValue & ~RTL_BALANCED_NODE_RESERVED_PARENT_MASK))
// Portability
typedef struct _SINGLE_LIST_ENTRY32
{
ULONG Next;
} SINGLE_LIST_ENTRY32, *PSINGLE_LIST_ENTRY32;
typedef struct _STRING32
{
USHORT Length;
USHORT MaximumLength;
ULONG Buffer;
} STRING32, *PSTRING32;
typedef STRING32 UNICODE_STRING32, *PUNICODE_STRING32;
typedef STRING32 ANSI_STRING32, *PANSI_STRING32;
typedef struct _STRING64
{
USHORT Length;
USHORT MaximumLength;
ULONGLONG Buffer;
} STRING64, *PSTRING64;
typedef STRING64 UNICODE_STRING64, *PUNICODE_STRING64;
typedef STRING64 ANSI_STRING64, *PANSI_STRING64;
// Object attributes
#define OBJ_INHERIT 0x00000002
#define OBJ_PERMANENT 0x00000010
#define OBJ_EXCLUSIVE 0x00000020
#define OBJ_CASE_INSENSITIVE 0x00000040
#define OBJ_OPENIF 0x00000080
#define OBJ_OPENLINK 0x00000100
#define OBJ_KERNEL_HANDLE 0x00000200
#define OBJ_FORCE_ACCESS_CHECK 0x00000400
#define OBJ_IGNORE_IMPERSONATED_DEVICEMAP 0x00000800
#define OBJ_DONT_REPARSE 0x00001000
#define OBJ_VALID_ATTRIBUTES 0x00001ff2
typedef struct _OBJECT_ATTRIBUTES
{
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor; // PSECURITY_DESCRIPTOR;
PVOID SecurityQualityOfService; // PSECURITY_QUALITY_OF_SERVICE
} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
typedef const OBJECT_ATTRIBUTES *PCOBJECT_ATTRIBUTES;
#define InitializeObjectAttributes(p, n, a, r, s) { \
(p)->Length = sizeof(OBJECT_ATTRIBUTES); \
(p)->RootDirectory = r; \
(p)->Attributes = a; \
(p)->ObjectName = n; \
(p)->SecurityDescriptor = s; \
(p)->SecurityQualityOfService = NULL; \
}
#define RTL_CONSTANT_OBJECT_ATTRIBUTES(n, a) { sizeof(OBJECT_ATTRIBUTES), NULL, n, a, NULL, NULL }
#define RTL_INIT_OBJECT_ATTRIBUTES(n, a) RTL_CONSTANT_OBJECT_ATTRIBUTES(n, a)
#define OBJ_NAME_PATH_SEPARATOR ((WCHAR)L'\\')
// Portability
typedef struct _OBJECT_ATTRIBUTES64
{
ULONG Length;
ULONG64 RootDirectory;
ULONG64 ObjectName;
ULONG Attributes;
ULONG64 SecurityDescriptor;
ULONG64 SecurityQualityOfService;
} OBJECT_ATTRIBUTES64, *POBJECT_ATTRIBUTES64;
typedef const OBJECT_ATTRIBUTES64 *PCOBJECT_ATTRIBUTES64;
typedef struct _OBJECT_ATTRIBUTES32
{
ULONG Length;
ULONG RootDirectory;
ULONG ObjectName;
ULONG Attributes;
ULONG SecurityDescriptor;
ULONG SecurityQualityOfService;
} OBJECT_ATTRIBUTES32, *POBJECT_ATTRIBUTES32;
typedef const OBJECT_ATTRIBUTES32 *PCOBJECT_ATTRIBUTES32;
// Product types
typedef enum _NT_PRODUCT_TYPE
{
NtProductWinNt = 1,
NtProductLanManNt,
NtProductServer
} NT_PRODUCT_TYPE, *PNT_PRODUCT_TYPE;
typedef enum _SUITE_TYPE
{
SmallBusiness,
Enterprise,
BackOffice,
CommunicationServer,
TerminalServer,
SmallBusinessRestricted,
EmbeddedNT,
DataCenter,
SingleUserTS,
Personal,
Blade,
EmbeddedRestricted,
SecurityAppliance,
StorageServer,
ComputeServer,
WHServer,
PhoneNT,
MaxSuiteType
} SUITE_TYPE;
// Specific
typedef struct _CLIENT_ID
{
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID, *PCLIENT_ID;
typedef struct _CLIENT_ID32
{
ULONG UniqueProcess;
ULONG UniqueThread;
} CLIENT_ID32, *PCLIENT_ID32;
typedef struct _CLIENT_ID64
{
ULONGLONG UniqueProcess;
ULONGLONG UniqueThread;
} CLIENT_ID64, *PCLIENT_ID64;
#include <pshpack4.h>
typedef struct _KSYSTEM_TIME
{
ULONG LowPart;
LONG High1Time;
LONG High2Time;
} KSYSTEM_TIME, *PKSYSTEM_TIME;
#include <poppack.h>
#endif
// #include <ntnls.h>
#define MAXIMUM_LEADBYTES 12
typedef struct _CPTABLEINFO
{
USHORT CodePage;
USHORT MaximumCharacterSize;
USHORT DefaultChar;
USHORT UniDefaultChar;
USHORT TransDefaultChar;
USHORT TransUniDefaultChar;
USHORT DBCSCodePage;
UCHAR LeadByte[MAXIMUM_LEADBYTES];
PUSHORT MultiByteTable;
PVOID WideCharTable;
PUSHORT DBCSRanges;
PUSHORT DBCSOffsets;
} CPTABLEINFO, *PCPTABLEINFO;
typedef struct _NLSTABLEINFO
{
CPTABLEINFO OemTableInfo;
CPTABLEINFO AnsiTableInfo;
PUSHORT UpperCaseTable;
PUSHORT LowerCaseTable;
} NLSTABLEINFO, *PNLSTABLEINFO;
NTSYSAPI USHORT NlsAnsiCodePage;
NTSYSAPI BOOLEAN NlsMbCodePageTag;
NTSYSAPI BOOLEAN NlsMbOemCodePageTag;
// #include <ntkeapi.h>
#define LOW_PRIORITY 0 // Lowest thread priority level
#define LOW_REALTIME_PRIORITY 16 // Lowest realtime priority level
#define HIGH_PRIORITY 31 // Highest thread priority level
#define MAXIMUM_PRIORITY 32 // Number of thread priority levels
typedef enum _KTHREAD_STATE
{
Initialized,
Ready,
Running,
Standby,
Terminated,
Waiting,
Transition,
DeferredReady,
GateWaitObsolete,
WaitingForProcessInSwap,
MaximumThreadState
} KTHREAD_STATE, *PKTHREAD_STATE;
// private
typedef enum _KHETERO_CPU_POLICY
{
KHeteroCpuPolicyAll,
KHeteroCpuPolicyLarge,
KHeteroCpuPolicyLargeOrIdle,
KHeteroCpuPolicySmall,
KHeteroCpuPolicySmallOrIdle,
KHeteroCpuPolicyDynamic,
KHeteroCpuPolicyStaticMax,
KHeteroCpuPolicyBiasedSmall,
KHeteroCpuPolicyBiasedLarge,
KHeteroCpuPolicyDefault,
KHeteroCpuPolicyMax
} KHETERO_CPU_POLICY, *PKHETERO_CPU_POLICY;
typedef enum _KWAIT_REASON
{
Executive,
FreePage,
PageIn,
PoolAllocation,
DelayExecution,
Suspended,
UserRequest,
WrExecutive,
WrFreePage,
WrPageIn,
WrPoolAllocation,
WrDelayExecution,
WrSuspended,
WrUserRequest,
WrEventPair,
WrQueue,
WrLpcReceive,
WrLpcReply,
WrVirtualMemory,
WrPageOut,
WrRendezvous,
WrKeyedEvent,
WrTerminated,
WrProcessInSwap,
WrCpuRateControl,
WrCalloutStack,
WrKernel,
WrResource,
WrPushLock,
WrMutex,
WrQuantumEnd,
WrDispatchInt,
WrPreempted,
WrYieldExecution,
WrFastMutex,
WrGuardedMutex,
WrRundown,
WrAlertByThreadId,
WrDeferredPreempt,
MaximumWaitReason
} KWAIT_REASON, *PKWAIT_REASON;
typedef enum _KPROFILE_SOURCE
{
ProfileTime,
ProfileAlignmentFixup,
ProfileTotalIssues,
ProfilePipelineDry,
ProfileLoadInstructions,
ProfilePipelineFrozen,
ProfileBranchInstructions,
ProfileTotalNonissues,
ProfileDcacheMisses,
ProfileIcacheMisses,
ProfileCacheMisses,
ProfileBranchMispredictions,
ProfileStoreInstructions,
ProfileFpInstructions,
ProfileIntegerInstructions,
Profile2Issue,
Profile3Issue,
Profile4Issue,
ProfileSpecialInstructions,
ProfileTotalCycles,
ProfileIcacheIssues,
ProfileDcacheAccesses,
ProfileMemoryBarrierCycles,
ProfileLoadLinkedIssues,
ProfileMaximum
} KPROFILE_SOURCE;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCallbackReturn(
_In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer,
_In_ ULONG OutputLength,
_In_ NTSTATUS Status
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCallbackReturn(
_In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer,
_In_ ULONG OutputLength,
_In_ NTSTATUS Status
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
VOID
NTAPI
NtFlushProcessWriteBuffers(
VOID
);
NTSYSCALLAPI
VOID
NTAPI
ZwFlushProcessWriteBuffers(
VOID
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_ BOOLEAN State
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_ BOOLEAN State
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtYieldExecution(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwYieldExecution(
VOID
);
// #include <ntldr.h>
// DLLs
typedef BOOLEAN (NTAPI *PLDR_INIT_ROUTINE)(
_In_ PVOID DllHandle,
_In_ ULONG Reason,
_In_opt_ PVOID Context
);
// symbols
typedef struct _LDR_SERVICE_TAG_RECORD
{
struct _LDR_SERVICE_TAG_RECORD *Next;
ULONG ServiceTag;
} LDR_SERVICE_TAG_RECORD, *PLDR_SERVICE_TAG_RECORD;
// symbols
typedef struct _LDRP_CSLIST
{
PSINGLE_LIST_ENTRY Tail;
} LDRP_CSLIST, *PLDRP_CSLIST;
// symbols
typedef enum _LDR_DDAG_STATE
{
LdrModulesMerged = -5,
LdrModulesInitError = -4,
LdrModulesSnapError = -3,
LdrModulesUnloaded = -2,
LdrModulesUnloading = -1,
LdrModulesPlaceHolder = 0,
LdrModulesMapping = 1,
LdrModulesMapped = 2,
LdrModulesWaitingForDependencies = 3,
LdrModulesSnapping = 4,
LdrModulesSnapped = 5,
LdrModulesCondensed = 6,
LdrModulesReadyToInit = 7,
LdrModulesInitializing = 8,
LdrModulesReadyToRun = 9
} LDR_DDAG_STATE;
// symbols
typedef struct _LDR_DDAG_NODE
{
LIST_ENTRY Modules;
PLDR_SERVICE_TAG_RECORD ServiceTagList;
ULONG LoadCount;
ULONG LoadWhileUnloadingCount;
ULONG LowestLink;
union
{
LDRP_CSLIST Dependencies;
SINGLE_LIST_ENTRY RemovalLink;
};
LDRP_CSLIST IncomingDependencies;
LDR_DDAG_STATE State;
SINGLE_LIST_ENTRY CondenseLink;
ULONG PreorderNumber;
} LDR_DDAG_NODE, *PLDR_DDAG_NODE;
// rev
typedef struct _LDR_DEPENDENCY_RECORD
{
SINGLE_LIST_ENTRY DependencyLink;
PLDR_DDAG_NODE DependencyNode;
SINGLE_LIST_ENTRY IncomingDependencyLink;
PLDR_DDAG_NODE IncomingDependencyNode;
} LDR_DEPENDENCY_RECORD, *PLDR_DEPENDENCY_RECORD;
// symbols
typedef enum _LDR_DLL_LOAD_REASON
{
LoadReasonStaticDependency,
LoadReasonStaticForwarderDependency,
LoadReasonDynamicForwarderDependency,
LoadReasonDelayloadDependency,
LoadReasonDynamicLoad,
LoadReasonAsImageLoad,
LoadReasonAsDataLoad,
LoadReasonEnclavePrimary, // REDSTONE3
LoadReasonEnclaveDependency,
LoadReasonUnknown = -1
} LDR_DLL_LOAD_REASON, *PLDR_DLL_LOAD_REASON;
#define LDRP_PACKAGED_BINARY 0x00000001
#define LDRP_STATIC_LINK 0x00000002
#define LDRP_IMAGE_DLL 0x00000004
#define LDRP_LOAD_IN_PROGRESS 0x00001000
#define LDRP_UNLOAD_IN_PROGRESS 0x00002000
#define LDRP_ENTRY_PROCESSED 0x00004000
#define LDRP_ENTRY_INSERTED 0x00008000
#define LDRP_CURRENT_LOAD 0x00010000
#define LDRP_FAILED_BUILTIN_LOAD 0x00020000
#define LDRP_DONT_CALL_FOR_THREADS 0x00040000
#define LDRP_PROCESS_ATTACH_CALLED 0x00080000
#define LDRP_DEBUG_SYMBOLS_LOADED 0x00100000
#define LDRP_IMAGE_NOT_AT_BASE 0x00200000 // Vista and below
#define LDRP_COR_IMAGE 0x00400000
#define LDRP_DONT_RELOCATE 0x00800000 // LDR_COR_OWNS_UNMAP
#define LDRP_SYSTEM_MAPPED 0x01000000
#define LDRP_IMAGE_VERIFYING 0x02000000
#define LDRP_DRIVER_DEPENDENT_DLL 0x04000000
#define LDRP_ENTRY_NATIVE 0x08000000
#define LDRP_REDIRECTED 0x10000000
#define LDRP_NON_PAGED_DEBUG_INFO 0x20000000
#define LDRP_MM_LOADED 0x40000000
#define LDRP_COMPAT_DATABASE_PROCESSED 0x80000000
#define LDR_DATA_TABLE_ENTRY_SIZE_WINXP FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DdagNode)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN7 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, BaseNameHashValue)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN8 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ImplicitPathOptions)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN10 sizeof(LDR_DATA_TABLE_ENTRY)
// symbols
typedef struct _LDR_DATA_TABLE_ENTRY
{
LIST_ENTRY InLoadOrderLinks;
LIST_ENTRY InMemoryOrderLinks;
union
{
LIST_ENTRY InInitializationOrderLinks;
LIST_ENTRY InProgressLinks;
};
PVOID DllBase;
PLDR_INIT_ROUTINE EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
union
{
UCHAR FlagGroup[4];
ULONG Flags;
struct
{
ULONG PackagedBinary : 1;
ULONG MarkedForRemoval : 1;
ULONG ImageDll : 1;
ULONG LoadNotificationsSent : 1;
ULONG TelemetryEntryProcessed : 1;
ULONG ProcessStaticImport : 1;
ULONG InLegacyLists : 1;
ULONG InIndexes : 1;
ULONG ShimDll : 1;
ULONG InExceptionTable : 1;
ULONG ReservedFlags1 : 2;
ULONG LoadInProgress : 1;
ULONG LoadConfigProcessed : 1;
ULONG EntryProcessed : 1;
ULONG ProtectDelayLoad : 1;
ULONG ReservedFlags3 : 2;
ULONG DontCallForThreads : 1;
ULONG ProcessAttachCalled : 1;
ULONG ProcessAttachFailed : 1;
ULONG CorDeferredValidate : 1;
ULONG CorImage : 1;
ULONG DontRelocate : 1;
ULONG CorILOnly : 1;
ULONG ChpeImage : 1;
ULONG ReservedFlags5 : 2;
ULONG Redirected : 1;
ULONG ReservedFlags6 : 2;
ULONG CompatDatabaseProcessed : 1;
};
};
USHORT ObsoleteLoadCount;
USHORT TlsIndex;
LIST_ENTRY HashLinks;
ULONG TimeDateStamp;
struct _ACTIVATION_CONTEXT *EntryPointActivationContext;
PVOID Lock; // RtlAcquireSRWLockExclusive
PLDR_DDAG_NODE DdagNode;
LIST_ENTRY NodeModuleLink;
struct _LDRP_LOAD_CONTEXT *LoadContext;
PVOID ParentDllBase;
PVOID SwitchBackContext;
RTL_BALANCED_NODE BaseAddressIndexNode;
RTL_BALANCED_NODE MappingInfoIndexNode;
ULONG_PTR OriginalBase;
LARGE_INTEGER LoadTime;
ULONG BaseNameHashValue;
LDR_DLL_LOAD_REASON LoadReason;
ULONG ImplicitPathOptions;
ULONG ReferenceCount;
ULONG DependentLoadFlags;
UCHAR SigningLevel; // since REDSTONE2
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
#define LDR_IS_DATAFILE(DllHandle) (((ULONG_PTR)(DllHandle)) & (ULONG_PTR)1)
#define LDR_IS_IMAGEMAPPING(DllHandle) (((ULONG_PTR)(DllHandle)) & (ULONG_PTR)2)
#define LDR_IS_RESOURCE(DllHandle) (LDR_IS_IMAGEMAPPING(DllHandle) || LDR_IS_DATAFILE(DllHandle))
NTSYSAPI
NTSTATUS
NTAPI
LdrLoadDll(
_In_opt_ PWSTR DllPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_ PVOID *DllHandle
);
NTSYSAPI
NTSTATUS
NTAPI
LdrUnloadDll(
_In_ PVOID DllHandle
);
NTSYSAPI
NTSTATUS
NTAPI
LdrGetDllHandle(
_In_opt_ PWSTR DllPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_ PVOID *DllHandle
);
#define LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT 0x00000001
#define LDR_GET_DLL_HANDLE_EX_PIN 0x00000002
NTSYSAPI
NTSTATUS
NTAPI
LdrGetDllHandleEx(
_In_ ULONG Flags,
_In_opt_ PWSTR DllPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_opt_ PVOID *DllHandle
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrGetDllHandleByMapping(
_In_ PVOID BaseAddress,
_Out_ PVOID *DllHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrGetDllHandleByName(
_In_opt_ PUNICODE_STRING BaseDllName,
_In_opt_ PUNICODE_STRING FullDllName,
_Out_ PVOID *DllHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN8)
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrGetDllFullName(
_In_ PVOID DllHandle,
_Out_ PUNICODE_STRING FullDllName
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrGetDllDirectory(
_Out_ PUNICODE_STRING DllDirectory
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrSetDllDirectory(
_In_ PUNICODE_STRING DllDirectory
);
#endif
#define LDR_ADDREF_DLL_PIN 0x00000001
NTSYSAPI
NTSTATUS
NTAPI
LdrAddRefDll(
_In_ ULONG Flags,
_In_ PVOID DllHandle
);
NTSYSAPI
NTSTATUS
NTAPI
LdrGetProcedureAddress(
_In_ PVOID DllHandle,
_In_opt_ PANSI_STRING ProcedureName,
_In_opt_ ULONG ProcedureNumber,
_Out_ PVOID *ProcedureAddress
);
// rev
#define LDR_GET_PROCEDURE_ADDRESS_DONT_RECORD_FORWARDER 0x00000001
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
LdrGetProcedureAddressEx(
_In_ PVOID DllHandle,
_In_opt_ PANSI_STRING ProcedureName,
_In_opt_ ULONG ProcedureNumber,
_Out_ PVOID *ProcedureAddress,
_In_ ULONG Flags
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
LdrGetKnownDllSectionHandle(
_In_ PCWSTR DllName,
_In_ BOOLEAN KnownDlls32,
_Out_ PHANDLE Section
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrGetProcedureAddressForCaller(
_In_ PVOID DllHandle,
_In_opt_ PANSI_STRING ProcedureName,
_In_opt_ ULONG ProcedureNumber,
_Out_ PVOID *ProcedureAddress,
_In_ ULONG Flags,
_In_ PVOID *Callback
);
#endif
#define LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001
#define LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY 0x00000002
#define LDR_LOCK_LOADER_LOCK_DISPOSITION_INVALID 0
#define LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED 1
#define LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED 2
NTSYSAPI
NTSTATUS
NTAPI
LdrLockLoaderLock(
_In_ ULONG Flags,
_Out_opt_ ULONG *Disposition,
_Out_ PVOID *Cookie
);
#define LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001
NTSYSAPI
NTSTATUS
NTAPI
LdrUnlockLoaderLock(
_In_ ULONG Flags,
_Inout_ PVOID Cookie
);
NTSYSAPI
NTSTATUS
NTAPI
LdrRelocateImage(
_In_ PVOID NewBase,
_In_ PSTR LoaderName,
_In_ NTSTATUS Success,
_In_ NTSTATUS Conflict,
_In_ NTSTATUS Invalid
);
NTSYSAPI
NTSTATUS
NTAPI
LdrRelocateImageWithBias(
_In_ PVOID NewBase,
_In_ LONGLONG Bias,
_In_ PSTR LoaderName,
_In_ NTSTATUS Success,
_In_ NTSTATUS Conflict,
_In_ NTSTATUS Invalid
);
NTSYSAPI
PIMAGE_BASE_RELOCATION
NTAPI
LdrProcessRelocationBlock(
_In_ ULONG_PTR VA,
_In_ ULONG SizeOfBlock,
_In_ PUSHORT NextOffset,
_In_ LONG_PTR Diff
);
NTSYSAPI
BOOLEAN
NTAPI
LdrVerifyMappedImageMatchesChecksum(
_In_ PVOID BaseAddress,
_In_ SIZE_T NumberOfBytes,
_In_ ULONG FileLength
);
typedef VOID (NTAPI *PLDR_IMPORT_MODULE_CALLBACK)(
_In_ PVOID Parameter,
_In_ PSTR ModuleName
);
NTSYSAPI
NTSTATUS
NTAPI
LdrVerifyImageMatchesChecksum(
_In_ HANDLE ImageFileHandle,
_In_opt_ PLDR_IMPORT_MODULE_CALLBACK ImportCallbackRoutine,
_In_ PVOID ImportCallbackParameter,
_Out_opt_ PUSHORT ImageCharacteristics
);
// private
typedef struct _LDR_IMPORT_CALLBACK_INFO
{
PLDR_IMPORT_MODULE_CALLBACK ImportCallbackRoutine;
PVOID ImportCallbackParameter;
} LDR_IMPORT_CALLBACK_INFO, *PLDR_IMPORT_CALLBACK_INFO;
// private
typedef struct _LDR_SECTION_INFO
{
HANDLE SectionHandle;
ACCESS_MASK DesiredAccess;
POBJECT_ATTRIBUTES ObjA;
ULONG SectionPageProtection;
ULONG AllocationAttributes;
} LDR_SECTION_INFO, *PLDR_SECTION_INFO;
// private
typedef struct _LDR_VERIFY_IMAGE_INFO
{
ULONG Size;
ULONG Flags;
LDR_IMPORT_CALLBACK_INFO CallbackInfo;
LDR_SECTION_INFO SectionInfo;
USHORT ImageCharacteristics;
} LDR_VERIFY_IMAGE_INFO, *PLDR_VERIFY_IMAGE_INFO;
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
LdrVerifyImageMatchesChecksumEx(
_In_ HANDLE ImageFileHandle,
_Inout_ PLDR_VERIFY_IMAGE_INFO VerifyInfo
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
LdrQueryModuleServiceTags(
_In_ PVOID DllHandle,
_Out_writes_(*BufferSize) PULONG ServiceTagBuffer,
_Inout_ PULONG BufferSize
);
#endif
// begin_msdn:"DLL Load Notification"
#define LDR_DLL_NOTIFICATION_REASON_LOADED 1
#define LDR_DLL_NOTIFICATION_REASON_UNLOADED 2
typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA
{
ULONG Flags;
PUNICODE_STRING FullDllName;
PUNICODE_STRING BaseDllName;
PVOID DllBase;
ULONG SizeOfImage;
} LDR_DLL_LOADED_NOTIFICATION_DATA, *PLDR_DLL_LOADED_NOTIFICATION_DATA;
typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA
{
ULONG Flags;
PCUNICODE_STRING FullDllName;
PCUNICODE_STRING BaseDllName;
PVOID DllBase;
ULONG SizeOfImage;
} LDR_DLL_UNLOADED_NOTIFICATION_DATA, *PLDR_DLL_UNLOADED_NOTIFICATION_DATA;
typedef union _LDR_DLL_NOTIFICATION_DATA
{
LDR_DLL_LOADED_NOTIFICATION_DATA Loaded;
LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded;
} LDR_DLL_NOTIFICATION_DATA, *PLDR_DLL_NOTIFICATION_DATA;
typedef VOID (NTAPI *PLDR_DLL_NOTIFICATION_FUNCTION)(
_In_ ULONG NotificationReason,
_In_ PLDR_DLL_NOTIFICATION_DATA NotificationData,
_In_opt_ PVOID Context
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
LdrRegisterDllNotification(
_In_ ULONG Flags,
_In_ PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction,
_In_ PVOID Context,
_Out_ PVOID *Cookie
);
NTSYSAPI
NTSTATUS
NTAPI
LdrUnregisterDllNotification(
_In_ PVOID Cookie
);
#endif
// end_msdn
// rev
NTSYSAPI
PUNICODE_STRING
NTAPI
LdrStandardizeSystemPath(
_In_ PUNICODE_STRING SystemPath
);
// private
typedef struct _PS_MITIGATION_OPTIONS_MAP
{
ULONG_PTR Map[2];
} PS_MITIGATION_OPTIONS_MAP, *PPS_MITIGATION_OPTIONS_MAP;
// private
typedef struct _PS_MITIGATION_AUDIT_OPTIONS_MAP
{
ULONG_PTR Map[2];
} PS_MITIGATION_AUDIT_OPTIONS_MAP, *PPS_MITIGATION_AUDIT_OPTIONS_MAP;
// private
typedef struct _PS_SYSTEM_DLL_INIT_BLOCK
{
ULONG Size;
ULONG_PTR SystemDllWowRelocation;
ULONG_PTR SystemDllNativeRelocation;
ULONG_PTR Wow64SharedInformation[16];
ULONG RngData;
union
{
ULONG Flags;
struct
{
ULONG CfgOverride : 1;
ULONG Reserved : 31;
};
};
PS_MITIGATION_OPTIONS_MAP MitigationOptionsMap;
ULONG_PTR CfgBitMap;
ULONG_PTR CfgBitMapSize;
ULONG_PTR Wow64CfgBitMap;
ULONG_PTR Wow64CfgBitMapSize;
PS_MITIGATION_AUDIT_OPTIONS_MAP MitigationAuditOptionsMap; // REDSTONE3
} PS_SYSTEM_DLL_INIT_BLOCK, *PPS_SYSTEM_DLL_INIT_BLOCK;
#if (NTDDI_VERSION >= NTDDI_WIN10)
// rev
NTSYSAPI
PPS_SYSTEM_DLL_INIT_BLOCK
NTAPI
LdrSystemDllInitBlock(
VOID
);
#endif
// Load as data table
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
LdrAddLoadAsDataTable(
_In_ PVOID Module,
_In_ PWSTR FilePath,
_In_ SIZE_T Size,
_In_ HANDLE Handle
);
// private
NTSYSAPI
NTSTATUS
NTAPI
LdrRemoveLoadAsDataTable(
_In_ PVOID InitModule,
_Out_opt_ PVOID *BaseModule,
_Out_opt_ PSIZE_T Size,
_In_ ULONG Flags
);
// private
NTSYSAPI
NTSTATUS
NTAPI
LdrGetFileNameFromLoadAsDataTable(
_In_ PVOID Module,
_Out_ PVOID *pFileNamePrt
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
LdrDisableThreadCalloutsForDll(
_In_ PVOID DllImageBase
);
// Resources
NTSYSAPI
NTSTATUS
NTAPI
LdrAccessResource(
_In_ PVOID DllHandle,
_In_ PIMAGE_RESOURCE_DATA_ENTRY ResourceDataEntry,
_Out_opt_ PVOID *ResourceBuffer,
_Out_opt_ ULONG *ResourceLength
);
typedef struct _LDR_RESOURCE_INFO
{
ULONG_PTR Type;
ULONG_PTR Name;
ULONG_PTR Language;
} LDR_RESOURCE_INFO, *PLDR_RESOURCE_INFO;
#define RESOURCE_TYPE_LEVEL 0
#define RESOURCE_NAME_LEVEL 1
#define RESOURCE_LANGUAGE_LEVEL 2
#define RESOURCE_DATA_LEVEL 3
NTSYSAPI
NTSTATUS
NTAPI
LdrFindResource_U(
_In_ PVOID DllHandle,
_In_ PLDR_RESOURCE_INFO ResourceInfo,
_In_ ULONG Level,
_Out_ PIMAGE_RESOURCE_DATA_ENTRY *ResourceDataEntry
);
NTSYSAPI
NTSTATUS
NTAPI
LdrFindResourceDirectory_U(
_In_ PVOID DllHandle,
_In_ PLDR_RESOURCE_INFO ResourceInfo,
_In_ ULONG Level,
_Out_ PIMAGE_RESOURCE_DIRECTORY *ResourceDirectory
);
// private
typedef struct _LDR_ENUM_RESOURCE_ENTRY
{
union
{
ULONG_PTR NameOrId;
PIMAGE_RESOURCE_DIRECTORY_STRING Name;
struct
{
USHORT Id;
USHORT NameIsPresent;
};
} Path[3];
PVOID Data;
ULONG Size;
ULONG Reserved;
} LDR_ENUM_RESOURCE_ENTRY, *PLDR_ENUM_RESOURCE_ENTRY;
#define NAME_FROM_RESOURCE_ENTRY(RootDirectory, Entry) \
((Entry)->NameIsString ? (ULONG_PTR)PTR_ADD_OFFSET((RootDirectory), (Entry)->NameOffset) : (Entry)->Id)
NTSYSAPI
NTSTATUS
NTAPI
LdrEnumResources(
_In_ PVOID DllHandle,
_In_ PLDR_RESOURCE_INFO ResourceInfo,
_In_ ULONG Level,
_Inout_ ULONG *ResourceCount,
_Out_writes_to_opt_(*ResourceCount, *ResourceCount) PLDR_ENUM_RESOURCE_ENTRY Resources
);
NTSYSAPI
NTSTATUS
NTAPI
LdrFindEntryForAddress(
_In_ PVOID DllHandle,
_Out_ PLDR_DATA_TABLE_ENTRY *Entry
);
// Module information
typedef struct _RTL_PROCESS_MODULE_INFORMATION
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION;
typedef struct _RTL_PROCESS_MODULES
{
ULONG NumberOfModules;
RTL_PROCESS_MODULE_INFORMATION Modules[1];
} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES;
// private
typedef struct _RTL_PROCESS_MODULE_INFORMATION_EX
{
USHORT NextOffset;
RTL_PROCESS_MODULE_INFORMATION BaseInfo;
ULONG ImageChecksum;
ULONG TimeDateStamp;
PVOID DefaultBase;
} RTL_PROCESS_MODULE_INFORMATION_EX, *PRTL_PROCESS_MODULE_INFORMATION_EX;
NTSYSAPI
NTSTATUS
NTAPI
LdrQueryProcessModuleInformation(
_In_opt_ PRTL_PROCESS_MODULES ModuleInformation,
_In_opt_ ULONG Size,
_Out_ PULONG ReturnedSize
);
typedef VOID (NTAPI *PLDR_ENUM_CALLBACK)(
_In_ PLDR_DATA_TABLE_ENTRY ModuleInformation,
_In_ PVOID Parameter,
_Out_ BOOLEAN *Stop
);
NTSYSAPI
NTSTATUS
NTAPI
LdrEnumerateLoadedModules(
_In_ BOOLEAN ReservedFlag,
_In_ PLDR_ENUM_CALLBACK EnumProc,
_In_ PVOID Context
);
NTSYSAPI
NTSTATUS
NTAPI
LdrOpenImageFileOptionsKey(
_In_ PUNICODE_STRING SubKey,
_In_ BOOLEAN Wow64,
_Out_ PHANDLE NewKeyHandle
);
NTSYSAPI
NTSTATUS
NTAPI
LdrQueryImageFileKeyOption(
_In_ HANDLE KeyHandle,
_In_ PCWSTR ValueName,
_In_ ULONG Type,
_Out_ PVOID Buffer,
_In_ ULONG BufferSize,
_Out_opt_ PULONG ReturnedLength
);
NTSYSAPI
NTSTATUS
NTAPI
LdrQueryImageFileExecutionOptions(
_In_ PUNICODE_STRING SubKey,
_In_ PCWSTR ValueName,
_In_ ULONG ValueSize,
_Out_ PVOID Buffer,
_In_ ULONG BufferSize,
_Out_opt_ PULONG ReturnedLength
);
NTSYSAPI
NTSTATUS
NTAPI
LdrQueryImageFileExecutionOptionsEx(
_In_ PUNICODE_STRING SubKey,
_In_ PCWSTR ValueName,
_In_ ULONG Type,
_Out_ PVOID Buffer,
_In_ ULONG BufferSize,
_Out_opt_ PULONG ReturnedLength,
_In_ BOOLEAN Wow64
);
// private
typedef struct _DELAYLOAD_PROC_DESCRIPTOR
{
ULONG ImportDescribedByName;
union
{
PCSTR Name;
ULONG Ordinal;
} Description;
} DELAYLOAD_PROC_DESCRIPTOR, *PDELAYLOAD_PROC_DESCRIPTOR;
// private
typedef struct _DELAYLOAD_INFO
{
ULONG Size;
PCIMAGE_DELAYLOAD_DESCRIPTOR DelayloadDescriptor;
PIMAGE_THUNK_DATA ThunkAddress;
PCSTR TargetDllName;
DELAYLOAD_PROC_DESCRIPTOR TargetApiDescriptor;
PVOID TargetModuleBase;
PVOID Unused;
ULONG LastError;
} DELAYLOAD_INFO, *PDELAYLOAD_INFO;
// private
typedef PVOID (NTAPI *PDELAYLOAD_FAILURE_DLL_CALLBACK)(
_In_ ULONG NotificationReason,
_In_ PDELAYLOAD_INFO DelayloadInfo
);
// rev
typedef PVOID (NTAPI *PDELAYLOAD_FAILURE_SYSTEM_ROUTINE)(
_In_ PCSTR DllName,
_In_ PCSTR ProcName
);
// rev
NTSYSAPI
PVOID
NTAPI
LdrResolveDelayLoadedAPI(
_In_ PVOID ParentModuleBase,
_In_ PCIMAGE_DELAYLOAD_DESCRIPTOR DelayloadDescriptor,
_In_opt_ PDELAYLOAD_FAILURE_DLL_CALLBACK FailureDllHook,
_In_opt_ PDELAYLOAD_FAILURE_SYSTEM_ROUTINE FailureSystemHook, // kernel32.DelayLoadFailureHook
_Out_ PIMAGE_THUNK_DATA ThunkAddress,
_Reserved_ ULONG Flags
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrResolveDelayLoadsFromDll(
_In_ PVOID ParentBase,
_In_ PCSTR TargetDllName,
_Reserved_ ULONG Flags
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrSetDefaultDllDirectories(
_In_ ULONG DirectoryFlags
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrShutdownProcess(
VOID
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrShutdownThread(
VOID
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
LdrSetImplicitPathOptions(
_In_ ULONG ImplicitPathOptions
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
LdrControlFlowGuardEnforced(
VOID
);
#if (NTDDI_VERSION >= NTDDI_WIN10_19H1)
// rev
NTSYSAPI
BOOLEAN
NTAPI
LdrIsModuleSxsRedirected(
_In_ PVOID DllHandle
);
#endif
// #include <ntexapi.h>
// #include <ntkeapi.h>
// Thread execution
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDelayExecution(
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER DelayInterval
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDelayExecution(
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER DelayInterval
);
// Environment values
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySystemEnvironmentValue(
_In_ PUNICODE_STRING VariableName,
_Out_writes_bytes_(ValueLength) PWSTR VariableValue,
_In_ USHORT ValueLength,
_Out_opt_ PUSHORT ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySystemEnvironmentValue(
_In_ PUNICODE_STRING VariableName,
_Out_writes_bytes_(ValueLength) PWSTR VariableValue,
_In_ USHORT ValueLength,
_Out_opt_ PUSHORT ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSystemEnvironmentValue(
_In_ PUNICODE_STRING VariableName,
_In_ PUNICODE_STRING VariableValue
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetSystemEnvironmentValue(
_In_ PUNICODE_STRING VariableName,
_In_ PUNICODE_STRING VariableValue
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySystemEnvironmentValueEx(
_In_ PUNICODE_STRING VariableName,
_In_ LPGUID VendorGuid,
_Out_writes_bytes_opt_(*ValueLength) PVOID Value,
_Inout_ PULONG ValueLength,
_Out_opt_ PULONG Attributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySystemEnvironmentValueEx(
_In_ PUNICODE_STRING VariableName,
_In_ LPGUID VendorGuid,
_Out_writes_bytes_opt_(*ValueLength) PVOID Value,
_Inout_ PULONG ValueLength,
_Out_opt_ PULONG Attributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSystemEnvironmentValueEx(
_In_ PUNICODE_STRING VariableName,
_In_ LPGUID VendorGuid,
_In_reads_bytes_opt_(ValueLength) PVOID Value,
_In_ ULONG ValueLength,
_In_ ULONG Attributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetSystemEnvironmentValueEx(
_In_ PUNICODE_STRING VariableName,
_In_ LPGUID VendorGuid,
_In_reads_bytes_opt_(ValueLength) PVOID Value,
_In_ ULONG ValueLength,
_In_ ULONG Attributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnumerateSystemEnvironmentValuesEx(
_In_ ULONG InformationClass,
_Out_ PVOID Buffer,
_Inout_ PULONG BufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnumerateSystemEnvironmentValuesEx(
_In_ ULONG InformationClass,
_Out_ PVOID Buffer,
_Inout_ PULONG BufferLength
);
// EFI
// private
typedef struct _BOOT_ENTRY
{
ULONG Version;
ULONG Length;
ULONG Id;
ULONG Attributes;
ULONG FriendlyNameOffset;
ULONG BootFilePathOffset;
ULONG OsOptionsLength;
UCHAR OsOptions[1];
} BOOT_ENTRY, *PBOOT_ENTRY;
// private
typedef struct _BOOT_ENTRY_LIST
{
ULONG NextEntryOffset;
BOOT_ENTRY BootEntry;
} BOOT_ENTRY_LIST, *PBOOT_ENTRY_LIST;
// private
typedef struct _BOOT_OPTIONS
{
ULONG Version;
ULONG Length;
ULONG Timeout;
ULONG CurrentBootEntryId;
ULONG NextBootEntryId;
WCHAR HeadlessRedirection[1];
} BOOT_OPTIONS, *PBOOT_OPTIONS;
// private
typedef struct _FILE_PATH
{
ULONG Version;
ULONG Length;
ULONG Type;
UCHAR FilePath[1];
} FILE_PATH, *PFILE_PATH;
// private
typedef struct _EFI_DRIVER_ENTRY
{
ULONG Version;
ULONG Length;
ULONG Id;
ULONG FriendlyNameOffset;
ULONG DriverFilePathOffset;
} EFI_DRIVER_ENTRY, *PEFI_DRIVER_ENTRY;
// private
typedef struct _EFI_DRIVER_ENTRY_LIST
{
ULONG NextEntryOffset;
EFI_DRIVER_ENTRY DriverEntry;
} EFI_DRIVER_ENTRY_LIST, *PEFI_DRIVER_ENTRY_LIST;
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAddBootEntry(
_In_ PBOOT_ENTRY BootEntry,
_Out_opt_ PULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAddBootEntry(
_In_ PBOOT_ENTRY BootEntry,
_Out_opt_ PULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteBootEntry(
_In_ ULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteBootEntry(
_In_ ULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtModifyBootEntry(
_In_ PBOOT_ENTRY BootEntry
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwModifyBootEntry(
_In_ PBOOT_ENTRY BootEntry
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnumerateBootEntries(
_Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
_Inout_ PULONG BufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnumerateBootEntries(
_Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
_Inout_ PULONG BufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryBootEntryOrder(
_Out_writes_opt_(*Count) PULONG Ids,
_Inout_ PULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryBootEntryOrder(
_Out_writes_opt_(*Count) PULONG Ids,
_Inout_ PULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetBootEntryOrder(
_In_reads_(Count) PULONG Ids,
_In_ ULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetBootEntryOrder(
_In_reads_(Count) PULONG Ids,
_In_ ULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryBootOptions(
_Out_writes_bytes_opt_(*BootOptionsLength) PBOOT_OPTIONS BootOptions,
_Inout_ PULONG BootOptionsLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryBootOptions(
_Out_writes_bytes_opt_(*BootOptionsLength) PBOOT_OPTIONS BootOptions,
_Inout_ PULONG BootOptionsLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetBootOptions(
_In_ PBOOT_OPTIONS BootOptions,
_In_ ULONG FieldsToChange
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetBootOptions(
_In_ PBOOT_OPTIONS BootOptions,
_In_ ULONG FieldsToChange
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTranslateFilePath(
_In_ PFILE_PATH InputFilePath,
_In_ ULONG OutputType,
_Out_writes_bytes_opt_(*OutputFilePathLength) PFILE_PATH OutputFilePath,
_Inout_opt_ PULONG OutputFilePathLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTranslateFilePath(
_In_ PFILE_PATH InputFilePath,
_In_ ULONG OutputType,
_Out_writes_bytes_opt_(*OutputFilePathLength) PFILE_PATH OutputFilePath,
_Inout_opt_ PULONG OutputFilePathLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAddDriverEntry(
_In_ PEFI_DRIVER_ENTRY DriverEntry,
_Out_opt_ PULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAddDriverEntry(
_In_ PEFI_DRIVER_ENTRY DriverEntry,
_Out_opt_ PULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteDriverEntry(
_In_ ULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteDriverEntry(
_In_ ULONG Id
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtModifyDriverEntry(
_In_ PEFI_DRIVER_ENTRY DriverEntry
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwModifyDriverEntry(
_In_ PEFI_DRIVER_ENTRY DriverEntry
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnumerateDriverEntries(
_Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
_Inout_ PULONG BufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnumerateDriverEntries(
_Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
_Inout_ PULONG BufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDriverEntryOrder(
_Out_writes_opt_(*Count) PULONG Ids,
_Inout_ PULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDriverEntryOrder(
_Out_writes_opt_(*Count) PULONG Ids,
_Inout_ PULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetDriverEntryOrder(
_In_reads_(Count) PULONG Ids,
_In_ ULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetDriverEntryOrder(
_In_reads_(Count) PULONG Ids,
_In_ ULONG Count
);
typedef enum _FILTER_BOOT_OPTION_OPERATION
{
FilterBootOptionOperationOpenSystemStore,
FilterBootOptionOperationSetElement,
FilterBootOptionOperationDeleteElement,
FilterBootOptionOperationMax
} FILTER_BOOT_OPTION_OPERATION;
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFilterBootOption(
_In_ FILTER_BOOT_OPTION_OPERATION FilterOperation,
_In_ ULONG ObjectType,
_In_ ULONG ElementType,
_In_reads_bytes_opt_(DataSize) PVOID Data,
_In_ ULONG DataSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFilterBootOption(
_In_ FILTER_BOOT_OPTION_OPERATION FilterOperation,
_In_ ULONG ObjectType,
_In_ ULONG ElementType,
_In_reads_bytes_opt_(DataSize) PVOID Data,
_In_ ULONG DataSize
);
#endif
#endif
// Event
#ifndef EVENT_QUERY_STATE
#define EVENT_QUERY_STATE 0x0001
#endif
typedef enum _EVENT_INFORMATION_CLASS
{
EventBasicInformation
} EVENT_INFORMATION_CLASS;
typedef struct _EVENT_BASIC_INFORMATION
{
EVENT_TYPE EventType;
LONG EventState;
} EVENT_BASIC_INFORMATION, *PEVENT_BASIC_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateEvent(
_Out_ PHANDLE EventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ EVENT_TYPE EventType,
_In_ BOOLEAN InitialState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateEvent(
_Out_ PHANDLE EventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ EVENT_TYPE EventType,
_In_ BOOLEAN InitialState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenEvent(
_Out_ PHANDLE EventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenEvent(
_Out_ PHANDLE EventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetEvent(
_In_ HANDLE EventHandle,
_Out_opt_ PLONG PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetEvent(
_In_ HANDLE EventHandle,
_Out_opt_ PLONG PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetEventBoostPriority(
_In_ HANDLE EventHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetEventBoostPriority(
_In_ HANDLE EventHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtClearEvent(
_In_ HANDLE EventHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwClearEvent(
_In_ HANDLE EventHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtResetEvent(
_In_ HANDLE EventHandle,
_Out_opt_ PLONG PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwResetEvent(
_In_ HANDLE EventHandle,
_Out_opt_ PLONG PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPulseEvent(
_In_ HANDLE EventHandle,
_Out_opt_ PLONG PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPulseEvent(
_In_ HANDLE EventHandle,
_Out_opt_ PLONG PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryEvent(
_In_ HANDLE EventHandle,
_In_ EVENT_INFORMATION_CLASS EventInformationClass,
_Out_writes_bytes_(EventInformationLength) PVOID EventInformation,
_In_ ULONG EventInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryEvent(
_In_ HANDLE EventHandle,
_In_ EVENT_INFORMATION_CLASS EventInformationClass,
_Out_writes_bytes_(EventInformationLength) PVOID EventInformation,
_In_ ULONG EventInformationLength,
_Out_opt_ PULONG ReturnLength
);
// Event Pair
#define EVENT_PAIR_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateEventPair(
_Out_ PHANDLE EventPairHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateEventPair(
_Out_ PHANDLE EventPairHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenEventPair(
_Out_ PHANDLE EventPairHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenEventPair(
_Out_ PHANDLE EventPairHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetLowEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetLowEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetHighEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetHighEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitLowEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitLowEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitHighEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitHighEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetLowWaitHighEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetLowWaitHighEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetHighWaitLowEventPair(
_In_ HANDLE EventPairHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetHighWaitLowEventPair(
_In_ HANDLE EventPairHandle
);
// Mutant
typedef enum _MUTANT_INFORMATION_CLASS
{
MutantBasicInformation,
MutantOwnerInformation
} MUTANT_INFORMATION_CLASS;
typedef struct _MUTANT_BASIC_INFORMATION
{
LONG CurrentCount;
BOOLEAN OwnedByCaller;
BOOLEAN AbandonedState;
} MUTANT_BASIC_INFORMATION, *PMUTANT_BASIC_INFORMATION;
typedef struct _MUTANT_OWNER_INFORMATION
{
CLIENT_ID ClientId;
} MUTANT_OWNER_INFORMATION, *PMUTANT_OWNER_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateMutant(
_Out_ PHANDLE MutantHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ BOOLEAN InitialOwner
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateMutant(
_Out_ PHANDLE MutantHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ BOOLEAN InitialOwner
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenMutant(
_Out_ PHANDLE MutantHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenMutant(
_Out_ PHANDLE MutantHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReleaseMutant(
_In_ HANDLE MutantHandle,
_Out_opt_ PLONG PreviousCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReleaseMutant(
_In_ HANDLE MutantHandle,
_Out_opt_ PLONG PreviousCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryMutant(
_In_ HANDLE MutantHandle,
_In_ MUTANT_INFORMATION_CLASS MutantInformationClass,
_Out_writes_bytes_(MutantInformationLength) PVOID MutantInformation,
_In_ ULONG MutantInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryMutant(
_In_ HANDLE MutantHandle,
_In_ MUTANT_INFORMATION_CLASS MutantInformationClass,
_Out_writes_bytes_(MutantInformationLength) PVOID MutantInformation,
_In_ ULONG MutantInformationLength,
_Out_opt_ PULONG ReturnLength
);
// Semaphore
#ifndef SEMAPHORE_QUERY_STATE
#define SEMAPHORE_QUERY_STATE 0x0001
#endif
typedef enum _SEMAPHORE_INFORMATION_CLASS
{
SemaphoreBasicInformation
} SEMAPHORE_INFORMATION_CLASS;
typedef struct _SEMAPHORE_BASIC_INFORMATION
{
LONG CurrentCount;
LONG MaximumCount;
} SEMAPHORE_BASIC_INFORMATION, *PSEMAPHORE_BASIC_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateSemaphore(
_Out_ PHANDLE SemaphoreHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ LONG InitialCount,
_In_ LONG MaximumCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateSemaphore(
_Out_ PHANDLE SemaphoreHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ LONG InitialCount,
_In_ LONG MaximumCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenSemaphore(
_Out_ PHANDLE SemaphoreHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenSemaphore(
_Out_ PHANDLE SemaphoreHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReleaseSemaphore(
_In_ HANDLE SemaphoreHandle,
_In_ LONG ReleaseCount,
_Out_opt_ PLONG PreviousCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReleaseSemaphore(
_In_ HANDLE SemaphoreHandle,
_In_ LONG ReleaseCount,
_Out_opt_ PLONG PreviousCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySemaphore(
_In_ HANDLE SemaphoreHandle,
_In_ SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
_Out_writes_bytes_(SemaphoreInformationLength) PVOID SemaphoreInformation,
_In_ ULONG SemaphoreInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySemaphore(
_In_ HANDLE SemaphoreHandle,
_In_ SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
_Out_writes_bytes_(SemaphoreInformationLength) PVOID SemaphoreInformation,
_In_ ULONG SemaphoreInformationLength,
_Out_opt_ PULONG ReturnLength
);
// Timer
typedef enum _TIMER_INFORMATION_CLASS
{
TimerBasicInformation
} TIMER_INFORMATION_CLASS;
typedef struct _TIMER_BASIC_INFORMATION
{
LARGE_INTEGER RemainingTime;
BOOLEAN TimerState;
} TIMER_BASIC_INFORMATION, *PTIMER_BASIC_INFORMATION;
typedef VOID (NTAPI *PTIMER_APC_ROUTINE)(
_In_ PVOID TimerContext,
_In_ ULONG TimerLowValue,
_In_ LONG TimerHighValue
);
typedef enum _TIMER_SET_INFORMATION_CLASS
{
TimerSetCoalescableTimer,
MaxTimerInfoClass
} TIMER_SET_INFORMATION_CLASS;
#if (NTDDI_VERSION >= NTDDI_WIN7)
struct _COUNTED_REASON_CONTEXT;
typedef struct _TIMER_SET_COALESCABLE_TIMER_INFO
{
_In_ LARGE_INTEGER DueTime;
_In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine;
_In_opt_ PVOID TimerContext;
_In_opt_ struct _COUNTED_REASON_CONTEXT *WakeContext;
_In_opt_ ULONG Period;
_In_ ULONG TolerableDelay;
_Out_opt_ PBOOLEAN PreviousState;
} TIMER_SET_COALESCABLE_TIMER_INFO, *PTIMER_SET_COALESCABLE_TIMER_INFO;
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateTimer(
_Out_ PHANDLE TimerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ TIMER_TYPE TimerType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateTimer(
_Out_ PHANDLE TimerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ TIMER_TYPE TimerType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenTimer(
_Out_ PHANDLE TimerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenTimer(
_Out_ PHANDLE TimerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetTimer(
_In_ HANDLE TimerHandle,
_In_ PLARGE_INTEGER DueTime,
_In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine,
_In_opt_ PVOID TimerContext,
_In_ BOOLEAN ResumeTimer,
_In_opt_ LONG Period,
_Out_opt_ PBOOLEAN PreviousState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetTimer(
_In_ HANDLE TimerHandle,
_In_ PLARGE_INTEGER DueTime,
_In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine,
_In_opt_ PVOID TimerContext,
_In_ BOOLEAN ResumeTimer,
_In_opt_ LONG Period,
_Out_opt_ PBOOLEAN PreviousState
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetTimerEx(
_In_ HANDLE TimerHandle,
_In_ TIMER_SET_INFORMATION_CLASS TimerSetInformationClass,
_Inout_updates_bytes_opt_(TimerSetInformationLength) PVOID TimerSetInformation,
_In_ ULONG TimerSetInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetTimerEx(
_In_ HANDLE TimerHandle,
_In_ TIMER_SET_INFORMATION_CLASS TimerSetInformationClass,
_Inout_updates_bytes_opt_(TimerSetInformationLength) PVOID TimerSetInformation,
_In_ ULONG TimerSetInformationLength
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCancelTimer(
_In_ HANDLE TimerHandle,
_Out_opt_ PBOOLEAN CurrentState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCancelTimer(
_In_ HANDLE TimerHandle,
_Out_opt_ PBOOLEAN CurrentState
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryTimer(
_In_ HANDLE TimerHandle,
_In_ TIMER_INFORMATION_CLASS TimerInformationClass,
_Out_writes_bytes_(TimerInformationLength) PVOID TimerInformation,
_In_ ULONG TimerInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryTimer(
_In_ HANDLE TimerHandle,
_In_ TIMER_INFORMATION_CLASS TimerInformationClass,
_Out_writes_bytes_(TimerInformationLength) PVOID TimerInformation,
_In_ ULONG TimerInformationLength,
_Out_opt_ PULONG ReturnLength
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateIRTimer(
_Out_ PHANDLE TimerHandle,
_In_ ACCESS_MASK DesiredAccess
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateIRTimer(
_Out_ PHANDLE TimerHandle,
_In_ ACCESS_MASK DesiredAccess
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetIRTimer(
_In_ HANDLE TimerHandle,
_In_opt_ PLARGE_INTEGER DueTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetIRTimer(
_In_ HANDLE TimerHandle,
_In_opt_ PLARGE_INTEGER DueTime
);
#endif
typedef struct _T2_SET_PARAMETERS_V0
{
ULONG Version;
ULONG Reserved;
LONGLONG NoWakeTolerance;
} T2_SET_PARAMETERS, *PT2_SET_PARAMETERS;
typedef PVOID PT2_CANCEL_PARAMETERS;
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateTimer2(
_Out_ PHANDLE TimerHandle,
_In_opt_ PVOID Reserved1,
_In_opt_ PVOID Reserved2,
_In_ ULONG Attributes,
_In_ ACCESS_MASK DesiredAccess
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateTimer2(
_Out_ PHANDLE TimerHandle,
_In_opt_ PVOID Reserved1,
_In_opt_ PVOID Reserved2,
_In_ ULONG Attributes,
_In_ ACCESS_MASK DesiredAccess
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetTimer2(
_In_ HANDLE TimerHandle,
_In_ PLARGE_INTEGER DueTime,
_In_opt_ PLARGE_INTEGER Period,
_In_ PT2_SET_PARAMETERS Parameters
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetTimer2(
_In_ HANDLE TimerHandle,
_In_ PLARGE_INTEGER DueTime,
_In_opt_ PLARGE_INTEGER Period,
_In_ PT2_SET_PARAMETERS Parameters
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCancelTimer2(
_In_ HANDLE TimerHandle,
_In_ PT2_CANCEL_PARAMETERS Parameters
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCancelTimer2(
_In_ HANDLE TimerHandle,
_In_ PT2_CANCEL_PARAMETERS Parameters
);
#endif
// Profile
#define PROFILE_CONTROL 0x0001
#define PROFILE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | PROFILE_CONTROL)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateProfile(
_Out_ PHANDLE ProfileHandle,
_In_opt_ HANDLE Process,
_In_ PVOID ProfileBase,
_In_ SIZE_T ProfileSize,
_In_ ULONG BucketSize,
_In_reads_bytes_(BufferSize) PULONG Buffer,
_In_ ULONG BufferSize,
_In_ KPROFILE_SOURCE ProfileSource,
_In_ KAFFINITY Affinity
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateProfile(
_Out_ PHANDLE ProfileHandle,
_In_opt_ HANDLE Process,
_In_ PVOID ProfileBase,
_In_ SIZE_T ProfileSize,
_In_ ULONG BucketSize,
_In_reads_bytes_(BufferSize) PULONG Buffer,
_In_ ULONG BufferSize,
_In_ KPROFILE_SOURCE ProfileSource,
_In_ KAFFINITY Affinity
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateProfileEx(
_Out_ PHANDLE ProfileHandle,
_In_opt_ HANDLE Process,
_In_ PVOID ProfileBase,
_In_ SIZE_T ProfileSize,
_In_ ULONG BucketSize,
_In_reads_bytes_(BufferSize) PULONG Buffer,
_In_ ULONG BufferSize,
_In_ KPROFILE_SOURCE ProfileSource,
_In_ USHORT GroupCount,
_In_reads_(GroupCount) PGROUP_AFFINITY GroupAffinity
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateProfileEx(
_Out_ PHANDLE ProfileHandle,
_In_opt_ HANDLE Process,
_In_ PVOID ProfileBase,
_In_ SIZE_T ProfileSize,
_In_ ULONG BucketSize,
_In_reads_bytes_(BufferSize) PULONG Buffer,
_In_ ULONG BufferSize,
_In_ KPROFILE_SOURCE ProfileSource,
_In_ USHORT GroupCount,
_In_reads_(GroupCount) PGROUP_AFFINITY GroupAffinity
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtStartProfile(
_In_ HANDLE ProfileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwStartProfile(
_In_ HANDLE ProfileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtStopProfile(
_In_ HANDLE ProfileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwStopProfile(
_In_ HANDLE ProfileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryIntervalProfile(
_In_ KPROFILE_SOURCE ProfileSource,
_Out_ PULONG Interval
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryIntervalProfile(
_In_ KPROFILE_SOURCE ProfileSource,
_Out_ PULONG Interval
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetIntervalProfile(
_In_ ULONG Interval,
_In_ KPROFILE_SOURCE Source
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetIntervalProfile(
_In_ ULONG Interval,
_In_ KPROFILE_SOURCE Source
);
// Keyed Event
#define KEYEDEVENT_WAIT 0x0001
#define KEYEDEVENT_WAKE 0x0002
#define KEYEDEVENT_ALL_ACCESS \
(STANDARD_RIGHTS_REQUIRED | KEYEDEVENT_WAIT | KEYEDEVENT_WAKE)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateKeyedEvent(
_Out_ PHANDLE KeyedEventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateKeyedEvent(
_Out_ PHANDLE KeyedEventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenKeyedEvent(
_Out_ PHANDLE KeyedEventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenKeyedEvent(
_Out_ PHANDLE KeyedEventHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReleaseKeyedEvent(
_In_ HANDLE KeyedEventHandle,
_In_ PVOID KeyValue,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReleaseKeyedEvent(
_In_ HANDLE KeyedEventHandle,
_In_ PVOID KeyValue,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForKeyedEvent(
_In_ HANDLE KeyedEventHandle,
_In_ PVOID KeyValue,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForKeyedEvent(
_In_ HANDLE KeyedEventHandle,
_In_ PVOID KeyValue,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
// UMS
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUmsThreadYield(
_In_ PVOID SchedulerParam
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUmsThreadYield(
_In_ PVOID SchedulerParam
);
#endif
// WNF
// begin_private
typedef struct _WNF_STATE_NAME
{
ULONG Data[2];
} WNF_STATE_NAME, *PWNF_STATE_NAME;
typedef const WNF_STATE_NAME *PCWNF_STATE_NAME;
typedef enum _WNF_STATE_NAME_LIFETIME
{
WnfWellKnownStateName,
WnfPermanentStateName,
WnfPersistentStateName,
WnfTemporaryStateName
} WNF_STATE_NAME_LIFETIME;
typedef enum _WNF_STATE_NAME_INFORMATION
{
WnfInfoStateNameExist,
WnfInfoSubscribersPresent,
WnfInfoIsQuiescent
} WNF_STATE_NAME_INFORMATION;
typedef enum _WNF_DATA_SCOPE
{
WnfDataScopeSystem,
WnfDataScopeSession,
WnfDataScopeUser,
WnfDataScopeProcess,
WnfDataScopeMachine // REDSTONE3
} WNF_DATA_SCOPE;
typedef struct _WNF_TYPE_ID
{
GUID TypeId;
} WNF_TYPE_ID, *PWNF_TYPE_ID;
typedef const WNF_TYPE_ID *PCWNF_TYPE_ID;
// rev
typedef ULONG WNF_CHANGE_STAMP, *PWNF_CHANGE_STAMP;
typedef struct _WNF_DELIVERY_DESCRIPTOR
{
ULONGLONG SubscriptionId;
WNF_STATE_NAME StateName;
WNF_CHANGE_STAMP ChangeStamp;
ULONG StateDataSize;
ULONG EventMask;
WNF_TYPE_ID TypeId;
ULONG StateDataOffset;
} WNF_DELIVERY_DESCRIPTOR, *PWNF_DELIVERY_DESCRIPTOR;
// end_private
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateWnfStateName(
_Out_ PWNF_STATE_NAME StateName,
_In_ WNF_STATE_NAME_LIFETIME NameLifetime,
_In_ WNF_DATA_SCOPE DataScope,
_In_ BOOLEAN PersistData,
_In_opt_ PCWNF_TYPE_ID TypeId,
_In_ ULONG MaximumStateSize,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateWnfStateName(
_Out_ PWNF_STATE_NAME StateName,
_In_ WNF_STATE_NAME_LIFETIME NameLifetime,
_In_ WNF_DATA_SCOPE DataScope,
_In_ BOOLEAN PersistData,
_In_opt_ PCWNF_TYPE_ID TypeId,
_In_ ULONG MaximumStateSize,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteWnfStateName(
_In_ PCWNF_STATE_NAME StateName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteWnfStateName(
_In_ PCWNF_STATE_NAME StateName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUpdateWnfStateData(
_In_ PCWNF_STATE_NAME StateName,
_In_reads_bytes_opt_(Length) const VOID *Buffer,
_In_opt_ ULONG Length,
_In_opt_ PCWNF_TYPE_ID TypeId,
_In_opt_ const VOID *ExplicitScope,
_In_ WNF_CHANGE_STAMP MatchingChangeStamp,
_In_ LOGICAL CheckStamp
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUpdateWnfStateData(
_In_ PCWNF_STATE_NAME StateName,
_In_reads_bytes_opt_(Length) const VOID *Buffer,
_In_opt_ ULONG Length,
_In_opt_ PCWNF_TYPE_ID TypeId,
_In_opt_ const VOID *ExplicitScope,
_In_ WNF_CHANGE_STAMP MatchingChangeStamp,
_In_ LOGICAL CheckStamp
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteWnfStateData(
_In_ PCWNF_STATE_NAME StateName,
_In_opt_ const VOID *ExplicitScope
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteWnfStateData(
_In_ PCWNF_STATE_NAME StateName,
_In_opt_ const VOID *ExplicitScope
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryWnfStateData(
_In_ PCWNF_STATE_NAME StateName,
_In_opt_ PCWNF_TYPE_ID TypeId,
_In_opt_ const VOID *ExplicitScope,
_Out_ PWNF_CHANGE_STAMP ChangeStamp,
_Out_writes_bytes_to_opt_(*BufferSize, *BufferSize) PVOID Buffer,
_Inout_ PULONG BufferSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryWnfStateData(
_In_ PCWNF_STATE_NAME StateName,
_In_opt_ PCWNF_TYPE_ID TypeId,
_In_opt_ const VOID *ExplicitScope,
_Out_ PWNF_CHANGE_STAMP ChangeStamp,
_Out_writes_bytes_to_opt_(*BufferSize, *BufferSize) PVOID Buffer,
_Inout_ PULONG BufferSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryWnfStateNameInformation(
_In_ PCWNF_STATE_NAME StateName,
_In_ WNF_STATE_NAME_INFORMATION NameInfoClass,
_In_opt_ const VOID *ExplicitScope,
_Out_writes_bytes_(InfoBufferSize) PVOID InfoBuffer,
_In_ ULONG InfoBufferSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryWnfStateNameInformation(
_In_ PCWNF_STATE_NAME StateName,
_In_ WNF_STATE_NAME_INFORMATION NameInfoClass,
_In_opt_ const VOID *ExplicitScope,
_Out_writes_bytes_(InfoBufferSize) PVOID InfoBuffer,
_In_ ULONG InfoBufferSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSubscribeWnfStateChange(
_In_ PCWNF_STATE_NAME StateName,
_In_opt_ WNF_CHANGE_STAMP ChangeStamp,
_In_ ULONG EventMask,
_Out_opt_ PULONG64 SubscriptionId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSubscribeWnfStateChange(
_In_ PCWNF_STATE_NAME StateName,
_In_opt_ WNF_CHANGE_STAMP ChangeStamp,
_In_ ULONG EventMask,
_Out_opt_ PULONG64 SubscriptionId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnsubscribeWnfStateChange(
_In_ PCWNF_STATE_NAME StateName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnsubscribeWnfStateChange(
_In_ PCWNF_STATE_NAME StateName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetCompleteWnfStateSubscription(
_In_opt_ PWNF_STATE_NAME OldDescriptorStateName,
_In_opt_ ULONG64 *OldSubscriptionId,
_In_opt_ ULONG OldDescriptorEventMask,
_In_opt_ ULONG OldDescriptorStatus,
_Out_writes_bytes_(DescriptorSize) PWNF_DELIVERY_DESCRIPTOR NewDeliveryDescriptor,
_In_ ULONG DescriptorSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetCompleteWnfStateSubscription(
_In_opt_ PWNF_STATE_NAME OldDescriptorStateName,
_In_opt_ ULONG64 *OldSubscriptionId,
_In_opt_ ULONG OldDescriptorEventMask,
_In_opt_ ULONG OldDescriptorStatus,
_Out_writes_bytes_(DescriptorSize) PWNF_DELIVERY_DESCRIPTOR NewDeliveryDescriptor,
_In_ ULONG DescriptorSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetWnfProcessNotificationEvent(
_In_ HANDLE NotificationEvent
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetWnfProcessNotificationEvent(
_In_ HANDLE NotificationEvent
);
#endif
// Worker factory
// begin_rev
#define WORKER_FACTORY_RELEASE_WORKER 0x0001
#define WORKER_FACTORY_WAIT 0x0002
#define WORKER_FACTORY_SET_INFORMATION 0x0004
#define WORKER_FACTORY_QUERY_INFORMATION 0x0008
#define WORKER_FACTORY_READY_WORKER 0x0010
#define WORKER_FACTORY_SHUTDOWN 0x0020
#define WORKER_FACTORY_ALL_ACCESS ( \
STANDARD_RIGHTS_REQUIRED | \
WORKER_FACTORY_RELEASE_WORKER | \
WORKER_FACTORY_WAIT | \
WORKER_FACTORY_SET_INFORMATION | \
WORKER_FACTORY_QUERY_INFORMATION | \
WORKER_FACTORY_READY_WORKER | \
WORKER_FACTORY_SHUTDOWN \
)
// end_rev
// begin_private
typedef enum _WORKERFACTORYINFOCLASS
{
WorkerFactoryTimeout,
WorkerFactoryRetryTimeout,
WorkerFactoryIdleTimeout,
WorkerFactoryBindingCount,
WorkerFactoryThreadMinimum,
WorkerFactoryThreadMaximum,
WorkerFactoryPaused,
WorkerFactoryBasicInformation,
WorkerFactoryAdjustThreadGoal,
WorkerFactoryCallbackType,
WorkerFactoryStackInformation, // 10
WorkerFactoryThreadBasePriority,
WorkerFactoryTimeoutWaiters, // since THRESHOLD
WorkerFactoryFlags,
WorkerFactoryThreadSoftMaximum,
WorkerFactoryThreadCpuSets, // since REDSTONE5
MaxWorkerFactoryInfoClass
} WORKERFACTORYINFOCLASS, *PWORKERFACTORYINFOCLASS;
typedef struct _WORKER_FACTORY_BASIC_INFORMATION
{
LARGE_INTEGER Timeout;
LARGE_INTEGER RetryTimeout;
LARGE_INTEGER IdleTimeout;
BOOLEAN Paused;
BOOLEAN TimerSet;
BOOLEAN QueuedToExWorker;
BOOLEAN MayCreate;
BOOLEAN CreateInProgress;
BOOLEAN InsertedIntoQueue;
BOOLEAN Shutdown;
ULONG BindingCount;
ULONG ThreadMinimum;
ULONG ThreadMaximum;
ULONG PendingWorkerCount;
ULONG WaitingWorkerCount;
ULONG TotalWorkerCount;
ULONG ReleaseCount;
LONGLONG InfiniteWaitGoal;
PVOID StartRoutine;
PVOID StartParameter;
HANDLE ProcessId;
SIZE_T StackReserve;
SIZE_T StackCommit;
NTSTATUS LastThreadCreationStatus;
} WORKER_FACTORY_BASIC_INFORMATION, *PWORKER_FACTORY_BASIC_INFORMATION;
// end_private
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateWorkerFactory(
_Out_ PHANDLE WorkerFactoryHandleReturn,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE CompletionPortHandle,
_In_ HANDLE WorkerProcessHandle,
_In_ PVOID StartRoutine,
_In_opt_ PVOID StartParameter,
_In_opt_ ULONG MaxThreadCount,
_In_opt_ SIZE_T StackReserve,
_In_opt_ SIZE_T StackCommit
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateWorkerFactory(
_Out_ PHANDLE WorkerFactoryHandleReturn,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE CompletionPortHandle,
_In_ HANDLE WorkerProcessHandle,
_In_ PVOID StartRoutine,
_In_opt_ PVOID StartParameter,
_In_opt_ ULONG MaxThreadCount,
_In_opt_ SIZE_T StackReserve,
_In_opt_ SIZE_T StackCommit
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
_Out_writes_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
_In_ ULONG WorkerFactoryInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
_Out_writes_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
_In_ ULONG WorkerFactoryInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
_In_reads_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
_In_ ULONG WorkerFactoryInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
_In_reads_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
_In_ ULONG WorkerFactoryInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtShutdownWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_Inout_ volatile LONG *PendingWorkerCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwShutdownWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_Inout_ volatile LONG *PendingWorkerCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReleaseWorkerFactoryWorker(
_In_ HANDLE WorkerFactoryHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReleaseWorkerFactoryWorker(
_In_ HANDLE WorkerFactoryHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWorkerFactoryWorkerReady(
_In_ HANDLE WorkerFactoryHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWorkerFactoryWorkerReady(
_In_ HANDLE WorkerFactoryHandle
);
struct _FILE_IO_COMPLETION_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForWorkViaWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_Out_ struct _FILE_IO_COMPLETION_INFORMATION *MiniPacket
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForWorkViaWorkerFactory(
_In_ HANDLE WorkerFactoryHandle,
_Out_ struct _FILE_IO_COMPLETION_INFORMATION *MiniPacket
);
#endif
// Time
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySystemTime(
_Out_ PLARGE_INTEGER SystemTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySystemTime(
_Out_ PLARGE_INTEGER SystemTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSystemTime(
_In_opt_ PLARGE_INTEGER SystemTime,
_Out_opt_ PLARGE_INTEGER PreviousTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetSystemTime(
_In_opt_ PLARGE_INTEGER SystemTime,
_Out_opt_ PLARGE_INTEGER PreviousTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryTimerResolution(
_Out_ PULONG MaximumTime,
_Out_ PULONG MinimumTime,
_Out_ PULONG CurrentTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryTimerResolution(
_Out_ PULONG MaximumTime,
_Out_ PULONG MinimumTime,
_Out_ PULONG CurrentTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetTimerResolution(
_In_ ULONG DesiredTime,
_In_ BOOLEAN SetResolution,
_Out_ PULONG ActualTime
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetTimerResolution(
_In_ ULONG DesiredTime,
_In_ BOOLEAN SetResolution,
_Out_ PULONG ActualTime
);
// Performance Counter
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryPerformanceCounter(
_Out_ PLARGE_INTEGER PerformanceCounter,
_Out_opt_ PLARGE_INTEGER PerformanceFrequency
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryPerformanceCounter(
_Out_ PLARGE_INTEGER PerformanceCounter,
_Out_opt_ PLARGE_INTEGER PerformanceFrequency
);
// LUIDs
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAllocateLocallyUniqueId(
_Out_ PLUID Luid
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAllocateLocallyUniqueId(
_Out_ PLUID Luid
);
// UUIDs
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetUuidSeed(
_In_ PCHAR Seed
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetUuidSeed(
_In_ PCHAR Seed
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAllocateUuids(
_Out_ PULARGE_INTEGER Time,
_Out_ PULONG Range,
_Out_ PULONG Sequence,
_Out_ PCHAR Seed
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAllocateUuids(
_Out_ PULARGE_INTEGER Time,
_Out_ PULONG Range,
_Out_ PULONG Sequence,
_Out_ PCHAR Seed
);
// System Information
// rev
// private
typedef enum _SYSTEM_INFORMATION_CLASS
{
SystemBasicInformation, // q: SYSTEM_BASIC_INFORMATION
SystemProcessorInformation, // q: SYSTEM_PROCESSOR_INFORMATION
SystemPerformanceInformation, // q: SYSTEM_PERFORMANCE_INFORMATION
SystemTimeOfDayInformation, // q: SYSTEM_TIMEOFDAY_INFORMATION
SystemPathInformation, // not implemented
SystemProcessInformation, // q: SYSTEM_PROCESS_INFORMATION
SystemCallCountInformation, // q: SYSTEM_CALL_COUNT_INFORMATION
SystemDeviceInformation, // q: SYSTEM_DEVICE_INFORMATION
SystemProcessorPerformanceInformation, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
SystemFlagsInformation, // q: SYSTEM_FLAGS_INFORMATION
SystemCallTimeInformation, // not implemented // SYSTEM_CALL_TIME_INFORMATION // 10
SystemModuleInformation, // q: RTL_PROCESS_MODULES
SystemLocksInformation, // q: RTL_PROCESS_LOCKS
SystemStackTraceInformation, // q: RTL_PROCESS_BACKTRACES
SystemPagedPoolInformation, // not implemented
SystemNonPagedPoolInformation, // not implemented
SystemHandleInformation, // q: SYSTEM_HANDLE_INFORMATION
SystemObjectInformation, // q: SYSTEM_OBJECTTYPE_INFORMATION mixed with SYSTEM_OBJECT_INFORMATION
SystemPageFileInformation, // q: SYSTEM_PAGEFILE_INFORMATION
SystemVdmInstemulInformation, // q
SystemVdmBopInformation, // not implemented // 20
SystemFileCacheInformation, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemCache)
SystemPoolTagInformation, // q: SYSTEM_POOLTAG_INFORMATION
SystemInterruptInformation, // q: SYSTEM_INTERRUPT_INFORMATION
SystemDpcBehaviorInformation, // q: SYSTEM_DPC_BEHAVIOR_INFORMATION; s: SYSTEM_DPC_BEHAVIOR_INFORMATION (requires SeLoadDriverPrivilege)
SystemFullMemoryInformation, // not implemented
SystemLoadGdiDriverInformation, // s (kernel-mode only)
SystemUnloadGdiDriverInformation, // s (kernel-mode only)
SystemTimeAdjustmentInformation, // q: SYSTEM_QUERY_TIME_ADJUST_INFORMATION; s: SYSTEM_SET_TIME_ADJUST_INFORMATION (requires SeSystemtimePrivilege)
SystemSummaryMemoryInformation, // not implemented
SystemMirrorMemoryInformation, // s (requires license value "Kernel-MemoryMirroringSupported") (requires SeShutdownPrivilege) // 30
SystemPerformanceTraceInformation, // q; s: (type depends on EVENT_TRACE_INFORMATION_CLASS)
SystemObsolete0, // not implemented
SystemExceptionInformation, // q: SYSTEM_EXCEPTION_INFORMATION
SystemCrashDumpStateInformation, // s (requires SeDebugPrivilege)
SystemKernelDebuggerInformation, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION
SystemContextSwitchInformation, // q: SYSTEM_CONTEXT_SWITCH_INFORMATION
SystemRegistryQuotaInformation, // q: SYSTEM_REGISTRY_QUOTA_INFORMATION; s (requires SeIncreaseQuotaPrivilege)
SystemExtendServiceTableInformation, // s (requires SeLoadDriverPrivilege) // loads win32k only
SystemPrioritySeperation, // s (requires SeTcbPrivilege)
SystemVerifierAddDriverInformation, // s (requires SeDebugPrivilege) // 40
SystemVerifierRemoveDriverInformation, // s (requires SeDebugPrivilege)
SystemProcessorIdleInformation, // q: SYSTEM_PROCESSOR_IDLE_INFORMATION
SystemLegacyDriverInformation, // q: SYSTEM_LEGACY_DRIVER_INFORMATION
SystemCurrentTimeZoneInformation, // q; s: RTL_TIME_ZONE_INFORMATION
SystemLookasideInformation, // q: SYSTEM_LOOKASIDE_INFORMATION
SystemTimeSlipNotification, // s (requires SeSystemtimePrivilege)
SystemSessionCreate, // not implemented
SystemSessionDetach, // not implemented
SystemSessionInformation, // not implemented (SYSTEM_SESSION_INFORMATION)
SystemRangeStartInformation, // q: SYSTEM_RANGE_START_INFORMATION // 50
SystemVerifierInformation, // q: SYSTEM_VERIFIER_INFORMATION; s (requires SeDebugPrivilege)
SystemVerifierThunkExtend, // s (kernel-mode only)
SystemSessionProcessInformation, // q: SYSTEM_SESSION_PROCESS_INFORMATION
SystemLoadGdiDriverInSystemSpace, // s (kernel-mode only) (same as SystemLoadGdiDriverInformation)
SystemNumaProcessorMap, // q
SystemPrefetcherInformation, // q: PREFETCHER_INFORMATION; s: PREFETCHER_INFORMATION // PfSnQueryPrefetcherInformation
SystemExtendedProcessInformation, // q: SYSTEM_PROCESS_INFORMATION
SystemRecommendedSharedDataAlignment, // q
SystemComPlusPackage, // q; s
SystemNumaAvailableMemory, // 60
SystemProcessorPowerInformation, // q: SYSTEM_PROCESSOR_POWER_INFORMATION
SystemEmulationBasicInformation,
SystemEmulationProcessorInformation,
SystemExtendedHandleInformation, // q: SYSTEM_HANDLE_INFORMATION_EX
SystemLostDelayedWriteInformation, // q: ULONG
SystemBigPoolInformation, // q: SYSTEM_BIGPOOL_INFORMATION
SystemSessionPoolTagInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION
SystemSessionMappedViewInformation, // q: SYSTEM_SESSION_MAPPED_VIEW_INFORMATION
SystemHotpatchInformation, // q; s: SYSTEM_HOTPATCH_CODE_INFORMATION
SystemObjectSecurityMode, // q: ULONG // 70
SystemWatchdogTimerHandler, // s (kernel-mode only)
SystemWatchdogTimerInformation, // q (kernel-mode only); s (kernel-mode only)
SystemLogicalProcessorInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION
SystemWow64SharedInformationObsolete, // not implemented
SystemRegisterFirmwareTableInformationHandler, // s (kernel-mode only)
SystemFirmwareTableInformation, // SYSTEM_FIRMWARE_TABLE_INFORMATION
SystemModuleInformationEx, // q: RTL_PROCESS_MODULE_INFORMATION_EX
SystemVerifierTriageInformation, // not implemented
SystemSuperfetchInformation, // q; s: SUPERFETCH_INFORMATION // PfQuerySuperfetchInformation
SystemMemoryListInformation, // q: SYSTEM_MEMORY_LIST_INFORMATION; s: SYSTEM_MEMORY_LIST_COMMAND (requires SeProfileSingleProcessPrivilege) // 80
SystemFileCacheInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (same as SystemFileCacheInformation)
SystemThreadPriorityClientIdInformation, // s: SYSTEM_THREAD_CID_PRIORITY_INFORMATION (requires SeIncreaseBasePriorityPrivilege)
SystemProcessorIdleCycleTimeInformation, // q: SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION[]
SystemVerifierCancellationInformation, // not implemented // name:wow64:whNT32QuerySystemVerifierCancellationInformation
SystemProcessorPowerInformationEx, // not implemented
SystemRefTraceInformation, // q; s: SYSTEM_REF_TRACE_INFORMATION // ObQueryRefTraceInformation
SystemSpecialPoolInformation, // q; s (requires SeDebugPrivilege) // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0
SystemProcessIdInformation, // q: SYSTEM_PROCESS_ID_INFORMATION
SystemErrorPortInformation, // s (requires SeTcbPrivilege)
SystemBootEnvironmentInformation, // q: SYSTEM_BOOT_ENVIRONMENT_INFORMATION // 90
SystemHypervisorInformation, // q; s (kernel-mode only)
SystemVerifierInformationEx, // q; s: SYSTEM_VERIFIER_INFORMATION_EX
SystemTimeZoneInformation, // s (requires SeTimeZonePrivilege)
SystemImageFileExecutionOptionsInformation, // s: SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION (requires SeTcbPrivilege)
SystemCoverageInformation, // q; s // name:wow64:whNT32QuerySystemCoverageInformation; ExpCovQueryInformation
SystemPrefetchPatchInformation, // not implemented
SystemVerifierFaultsInformation, // s (requires SeDebugPrivilege)
SystemSystemPartitionInformation, // q: SYSTEM_SYSTEM_PARTITION_INFORMATION
SystemSystemDiskInformation, // q: SYSTEM_SYSTEM_DISK_INFORMATION
SystemProcessorPerformanceDistribution, // q: SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION // 100
SystemNumaProximityNodeInformation,
SystemDynamicTimeZoneInformation, // q; s (requires SeTimeZonePrivilege)
SystemCodeIntegrityInformation, // q: SYSTEM_CODEINTEGRITY_INFORMATION // SeCodeIntegrityQueryInformation
SystemProcessorMicrocodeUpdateInformation, // s
SystemProcessorBrandString, // q // HaliQuerySystemInformation -> HalpGetProcessorBrandString, info class 23
SystemVirtualAddressInformation, // q: SYSTEM_VA_LIST_INFORMATION[]; s: SYSTEM_VA_LIST_INFORMATION[] (requires SeIncreaseQuotaPrivilege) // MmQuerySystemVaInformation
SystemLogicalProcessorAndGroupInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX // since WIN7 // KeQueryLogicalProcessorRelationship
SystemProcessorCycleTimeInformation, // q: SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION[]
SystemStoreInformation, // q; s: SYSTEM_STORE_INFORMATION // SmQueryStoreInformation
SystemRegistryAppendString, // s: SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS // 110
SystemAitSamplingValue, // s: ULONG (requires SeProfileSingleProcessPrivilege)
SystemVhdBootInformation, // q: SYSTEM_VHD_BOOT_INFORMATION
SystemCpuQuotaInformation, // q; s // PsQueryCpuQuotaInformation
SystemNativeBasicInformation, // not implemented
SystemSpare1, // not implemented
SystemLowPriorityIoInformation, // q: SYSTEM_LOW_PRIORITY_IO_INFORMATION
SystemTpmBootEntropyInformation, // q: TPM_BOOT_ENTROPY_NT_RESULT // ExQueryTpmBootEntropyInformation
SystemVerifierCountersInformation, // q: SYSTEM_VERIFIER_COUNTERS_INFORMATION
SystemPagedPoolInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypePagedPool)
SystemSystemPtesInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemPtes) // 120
SystemNodeDistanceInformation,
SystemAcpiAuditInformation, // q: SYSTEM_ACPI_AUDIT_INFORMATION // HaliQuerySystemInformation -> HalpAuditQueryResults, info class 26
SystemBasicPerformanceInformation, // q: SYSTEM_BASIC_PERFORMANCE_INFORMATION // name:wow64:whNtQuerySystemInformation_SystemBasicPerformanceInformation
SystemQueryPerformanceCounterInformation, // q: SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION // since WIN7 SP1
SystemSessionBigPoolInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION // since WIN8
SystemBootGraphicsInformation, // q; s: SYSTEM_BOOT_GRAPHICS_INFORMATION (kernel-mode only)
SystemScrubPhysicalMemoryInformation, // q; s: MEMORY_SCRUB_INFORMATION
SystemBadPageInformation,
SystemProcessorProfileControlArea, // q; s: SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA
SystemCombinePhysicalMemoryInformation, // s: MEMORY_COMBINE_INFORMATION, MEMORY_COMBINE_INFORMATION_EX, MEMORY_COMBINE_INFORMATION_EX2 // 130
SystemEntropyInterruptTimingCallback,
SystemConsoleInformation, // q: SYSTEM_CONSOLE_INFORMATION
SystemPlatformBinaryInformation, // q: SYSTEM_PLATFORM_BINARY_INFORMATION
SystemThrottleNotificationInformation,
SystemHypervisorProcessorCountInformation, // q: SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION
SystemDeviceDataInformation, // q: SYSTEM_DEVICE_DATA_INFORMATION
SystemDeviceDataEnumerationInformation,
SystemMemoryTopologyInformation, // q: SYSTEM_MEMORY_TOPOLOGY_INFORMATION
SystemMemoryChannelInformation, // q: SYSTEM_MEMORY_CHANNEL_INFORMATION
SystemBootLogoInformation, // q: SYSTEM_BOOT_LOGO_INFORMATION // 140
SystemProcessorPerformanceInformationEx, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX // since WINBLUE
SystemSpare0,
SystemSecureBootPolicyInformation, // q: SYSTEM_SECUREBOOT_POLICY_INFORMATION
SystemPageFileInformationEx, // q: SYSTEM_PAGEFILE_INFORMATION_EX
SystemSecureBootInformation, // q: SYSTEM_SECUREBOOT_INFORMATION
SystemEntropyInterruptTimingRawInformation,
SystemPortableWorkspaceEfiLauncherInformation, // q: SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION
SystemFullProcessInformation, // q: SYSTEM_PROCESS_INFORMATION with SYSTEM_PROCESS_INFORMATION_EXTENSION (requires admin)
SystemKernelDebuggerInformationEx, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX
SystemBootMetadataInformation, // 150
SystemSoftRebootInformation, // q: ULONG
SystemElamCertificateInformation, // s: SYSTEM_ELAM_CERTIFICATE_INFORMATION
SystemOfflineDumpConfigInformation,
SystemProcessorFeaturesInformation, // q: SYSTEM_PROCESSOR_FEATURES_INFORMATION
SystemRegistryReconciliationInformation,
SystemEdidInformation,
SystemManufacturingInformation, // q: SYSTEM_MANUFACTURING_INFORMATION // since THRESHOLD
SystemEnergyEstimationConfigInformation, // q: SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION
SystemHypervisorDetailInformation, // q: SYSTEM_HYPERVISOR_DETAIL_INFORMATION
SystemProcessorCycleStatsInformation, // q: SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION // 160
SystemVmGenerationCountInformation,
SystemTrustedPlatformModuleInformation, // q: SYSTEM_TPM_INFORMATION
SystemKernelDebuggerFlags, // SYSTEM_KERNEL_DEBUGGER_FLAGS
SystemCodeIntegrityPolicyInformation, // q: SYSTEM_CODEINTEGRITYPOLICY_INFORMATION
SystemIsolatedUserModeInformation, // q: SYSTEM_ISOLATED_USER_MODE_INFORMATION
SystemHardwareSecurityTestInterfaceResultsInformation,
SystemSingleModuleInformation, // q: SYSTEM_SINGLE_MODULE_INFORMATION
SystemAllowedCpuSetsInformation,
SystemVsmProtectionInformation, // q: SYSTEM_VSM_PROTECTION_INFORMATION (previously SystemDmaProtectionInformation)
SystemInterruptCpuSetsInformation, // q: SYSTEM_INTERRUPT_CPU_SET_INFORMATION // 170
SystemSecureBootPolicyFullInformation, // q: SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION
SystemCodeIntegrityPolicyFullInformation,
SystemAffinitizedInterruptProcessorInformation,
SystemRootSiloInformation, // q: SYSTEM_ROOT_SILO_INFORMATION
SystemCpuSetInformation, // q: SYSTEM_CPU_SET_INFORMATION // since THRESHOLD2
SystemCpuSetTagInformation, // q: SYSTEM_CPU_SET_TAG_INFORMATION
SystemWin32WerStartCallout,
SystemSecureKernelProfileInformation, // q: SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION
SystemCodeIntegrityPlatformManifestInformation, // q: SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION // since REDSTONE
SystemInterruptSteeringInformation, // 180
SystemSupportedProcessorArchitectures,
SystemMemoryUsageInformation, // q: SYSTEM_MEMORY_USAGE_INFORMATION
SystemCodeIntegrityCertificateInformation, // q: SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION
SystemPhysicalMemoryInformation, // q: SYSTEM_PHYSICAL_MEMORY_INFORMATION // since REDSTONE2
SystemControlFlowTransition,
SystemKernelDebuggingAllowed, // s: ULONG
SystemActivityModerationExeState, // SYSTEM_ACTIVITY_MODERATION_EXE_STATE
SystemActivityModerationUserSettings, // SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS
SystemCodeIntegrityPoliciesFullInformation,
SystemCodeIntegrityUnlockInformation, // SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION // 190
SystemIntegrityQuotaInformation,
SystemFlushInformation, // q: SYSTEM_FLUSH_INFORMATION
SystemProcessorIdleMaskInformation, // q: ULONG_PTR // since REDSTONE3
SystemSecureDumpEncryptionInformation,
SystemWriteConstraintInformation, // SYSTEM_WRITE_CONSTRAINT_INFORMATION
SystemKernelVaShadowInformation, // SYSTEM_KERNEL_VA_SHADOW_INFORMATION
SystemHypervisorSharedPageInformation, // SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION // since REDSTONE4
SystemFirmwareBootPerformanceInformation,
SystemCodeIntegrityVerificationInformation, // SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION
SystemFirmwarePartitionInformation, // SYSTEM_FIRMWARE_PARTITION_INFORMATION // 200
SystemSpeculationControlInformation, // SYSTEM_SPECULATION_CONTROL_INFORMATION // (CVE-2017-5715) REDSTONE3 and above.
SystemDmaGuardPolicyInformation, // SYSTEM_DMA_GUARD_POLICY_INFORMATION
SystemEnclaveLaunchControlInformation, // SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION
SystemWorkloadAllowedCpuSetsInformation, // SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION // since REDSTONE5
SystemCodeIntegrityUnlockModeInformation,
SystemLeapSecondInformation, // SYSTEM_LEAP_SECOND_INFORMATION
SystemFlags2Information, // q: SYSTEM_FLAGS_INFORMATION
SystemSecurityModelInformation, // SYSTEM_SECURITY_MODEL_INFORMATION // since 19H1
SystemCodeIntegritySyntheticCacheInformation,
MaxSystemInfoClass
} SYSTEM_INFORMATION_CLASS;
typedef struct _SYSTEM_BASIC_INFORMATION
{
ULONG Reserved;
ULONG TimerResolution;
ULONG PageSize;
ULONG NumberOfPhysicalPages;
ULONG LowestPhysicalPageNumber;
ULONG HighestPhysicalPageNumber;
ULONG AllocationGranularity;
ULONG_PTR MinimumUserModeAddress;
ULONG_PTR MaximumUserModeAddress;
ULONG_PTR ActiveProcessorsAffinityMask;
CCHAR NumberOfProcessors;
} SYSTEM_BASIC_INFORMATION, *PSYSTEM_BASIC_INFORMATION;
typedef struct _SYSTEM_PROCESSOR_INFORMATION
{
USHORT ProcessorArchitecture;
USHORT ProcessorLevel;
USHORT ProcessorRevision;
USHORT MaximumProcessors;
ULONG ProcessorFeatureBits;
} SYSTEM_PROCESSOR_INFORMATION, *PSYSTEM_PROCESSOR_INFORMATION;
typedef struct _SYSTEM_PERFORMANCE_INFORMATION
{
LARGE_INTEGER IdleProcessTime;
LARGE_INTEGER IoReadTransferCount;
LARGE_INTEGER IoWriteTransferCount;
LARGE_INTEGER IoOtherTransferCount;
ULONG IoReadOperationCount;
ULONG IoWriteOperationCount;
ULONG IoOtherOperationCount;
ULONG AvailablePages;
ULONG CommittedPages;
ULONG CommitLimit;
ULONG PeakCommitment;
ULONG PageFaultCount;
ULONG CopyOnWriteCount;
ULONG TransitionCount;
ULONG CacheTransitionCount;
ULONG DemandZeroCount;
ULONG PageReadCount;
ULONG PageReadIoCount;
ULONG CacheReadCount;
ULONG CacheIoCount;
ULONG DirtyPagesWriteCount;
ULONG DirtyWriteIoCount;
ULONG MappedPagesWriteCount;
ULONG MappedWriteIoCount;
ULONG PagedPoolPages;
ULONG NonPagedPoolPages;
ULONG PagedPoolAllocs;
ULONG PagedPoolFrees;
ULONG NonPagedPoolAllocs;
ULONG NonPagedPoolFrees;
ULONG FreeSystemPtes;
ULONG ResidentSystemCodePage;
ULONG TotalSystemDriverPages;
ULONG TotalSystemCodePages;
ULONG NonPagedPoolLookasideHits;
ULONG PagedPoolLookasideHits;
ULONG AvailablePagedPoolPages;
ULONG ResidentSystemCachePage;
ULONG ResidentPagedPoolPage;
ULONG ResidentSystemDriverPage;
ULONG CcFastReadNoWait;
ULONG CcFastReadWait;
ULONG CcFastReadResourceMiss;
ULONG CcFastReadNotPossible;
ULONG CcFastMdlReadNoWait;
ULONG CcFastMdlReadWait;
ULONG CcFastMdlReadResourceMiss;
ULONG CcFastMdlReadNotPossible;
ULONG CcMapDataNoWait;
ULONG CcMapDataWait;
ULONG CcMapDataNoWaitMiss;
ULONG CcMapDataWaitMiss;
ULONG CcPinMappedDataCount;
ULONG CcPinReadNoWait;
ULONG CcPinReadWait;
ULONG CcPinReadNoWaitMiss;
ULONG CcPinReadWaitMiss;
ULONG CcCopyReadNoWait;
ULONG CcCopyReadWait;
ULONG CcCopyReadNoWaitMiss;
ULONG CcCopyReadWaitMiss;
ULONG CcMdlReadNoWait;
ULONG CcMdlReadWait;
ULONG CcMdlReadNoWaitMiss;
ULONG CcMdlReadWaitMiss;
ULONG CcReadAheadIos;
ULONG CcLazyWriteIos;
ULONG CcLazyWritePages;
ULONG CcDataFlushes;
ULONG CcDataPages;
ULONG ContextSwitches;
ULONG FirstLevelTbFills;
ULONG SecondLevelTbFills;
ULONG SystemCalls;
ULONGLONG CcTotalDirtyPages; // since THRESHOLD
ULONGLONG CcDirtyPageThreshold; // since THRESHOLD
LONGLONG ResidentAvailablePages; // since THRESHOLD
ULONGLONG SharedCommittedPages; // since THRESHOLD
} SYSTEM_PERFORMANCE_INFORMATION, *PSYSTEM_PERFORMANCE_INFORMATION;
typedef struct _SYSTEM_TIMEOFDAY_INFORMATION
{
LARGE_INTEGER BootTime;
LARGE_INTEGER CurrentTime;
LARGE_INTEGER TimeZoneBias;
ULONG TimeZoneId;
ULONG Reserved;
ULONGLONG BootTimeBias;
ULONGLONG SleepTimeBias;
} SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION;
typedef struct _SYSTEM_THREAD_INFORMATION
{
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
LONG BasePriority;
ULONG ContextSwitches;
ULONG ThreadState;
KWAIT_REASON WaitReason;
} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;
typedef struct _TEB TEB, *PTEB;
// private
typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION
{
SYSTEM_THREAD_INFORMATION ThreadInfo;
PVOID StackBase;
PVOID StackLimit;
PVOID Win32StartAddress;
PTEB TebBase; // since VISTA
ULONG_PTR Reserved2;
ULONG_PTR Reserved3;
ULONG_PTR Reserved4;
} SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION;
typedef struct _SYSTEM_PROCESS_INFORMATION
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER WorkingSetPrivateSize; // since VISTA
ULONG HardFaultCount; // since WIN7
ULONG NumberOfThreadsHighWatermark; // since WIN7
ULONGLONG CycleTime; // since WIN7
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SessionId;
ULONG_PTR UniqueProcessKey; // since VISTA (requires SystemExtendedProcessInformation)
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
LARGE_INTEGER ReadOperationCount;
LARGE_INTEGER WriteOperationCount;
LARGE_INTEGER OtherOperationCount;
LARGE_INTEGER ReadTransferCount;
LARGE_INTEGER WriteTransferCount;
LARGE_INTEGER OtherTransferCount;
SYSTEM_THREAD_INFORMATION Threads[1]; // SystemProcessInformation
// SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1]; // SystemExtendedProcessinformation
// SYSTEM_EXTENDED_THREAD_INFORMATION + SYSTEM_PROCESS_INFORMATION_EXTENSION // SystemFullProcessInformation
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;
typedef struct _SYSTEM_CALL_COUNT_INFORMATION
{
ULONG Length;
ULONG NumberOfTables;
} SYSTEM_CALL_COUNT_INFORMATION, *PSYSTEM_CALL_COUNT_INFORMATION;
typedef struct _SYSTEM_DEVICE_INFORMATION
{
ULONG NumberOfDisks;
ULONG NumberOfFloppies;
ULONG NumberOfCdRoms;
ULONG NumberOfTapes;
ULONG NumberOfSerialPorts;
ULONG NumberOfParallelPorts;
} SYSTEM_DEVICE_INFORMATION, *PSYSTEM_DEVICE_INFORMATION;
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
{
LARGE_INTEGER IdleTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER DpcTime;
LARGE_INTEGER InterruptTime;
ULONG InterruptCount;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;
typedef struct _SYSTEM_FLAGS_INFORMATION
{
ULONG Flags; // NtGlobalFlag
} SYSTEM_FLAGS_INFORMATION, *PSYSTEM_FLAGS_INFORMATION;
// private
typedef struct _SYSTEM_CALL_TIME_INFORMATION
{
ULONG Length;
ULONG TotalCalls;
LARGE_INTEGER TimeOfCalls[1];
} SYSTEM_CALL_TIME_INFORMATION, *PSYSTEM_CALL_TIME_INFORMATION;
// private
typedef struct _RTL_PROCESS_LOCK_INFORMATION
{
PVOID Address;
USHORT Type;
USHORT CreatorBackTraceIndex;
HANDLE OwningThread;
LONG LockCount;
ULONG ContentionCount;
ULONG EntryCount;
LONG RecursionCount;
ULONG NumberOfWaitingShared;
ULONG NumberOfWaitingExclusive;
} RTL_PROCESS_LOCK_INFORMATION, *PRTL_PROCESS_LOCK_INFORMATION;
// private
typedef struct _RTL_PROCESS_LOCKS
{
ULONG NumberOfLocks;
RTL_PROCESS_LOCK_INFORMATION Locks[1];
} RTL_PROCESS_LOCKS, *PRTL_PROCESS_LOCKS;
// private
typedef struct _RTL_PROCESS_BACKTRACE_INFORMATION
{
PCHAR SymbolicBackTrace;
ULONG TraceCount;
USHORT Index;
USHORT Depth;
PVOID BackTrace[32];
} RTL_PROCESS_BACKTRACE_INFORMATION, *PRTL_PROCESS_BACKTRACE_INFORMATION;
// private
typedef struct _RTL_PROCESS_BACKTRACES
{
ULONG CommittedMemory;
ULONG ReservedMemory;
ULONG NumberOfBackTraceLookups;
ULONG NumberOfBackTraces;
RTL_PROCESS_BACKTRACE_INFORMATION BackTraces[1];
} RTL_PROCESS_BACKTRACES, *PRTL_PROCESS_BACKTRACES;
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
typedef struct _SYSTEM_OBJECTTYPE_INFORMATION
{
ULONG NextEntryOffset;
ULONG NumberOfObjects;
ULONG NumberOfHandles;
ULONG TypeIndex;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
ULONG PoolType;
BOOLEAN SecurityRequired;
BOOLEAN WaitableObject;
UNICODE_STRING TypeName;
} SYSTEM_OBJECTTYPE_INFORMATION, *PSYSTEM_OBJECTTYPE_INFORMATION;
typedef struct _SYSTEM_OBJECT_INFORMATION
{
ULONG NextEntryOffset;
PVOID Object;
HANDLE CreatorUniqueProcess;
USHORT CreatorBackTraceIndex;
USHORT Flags;
LONG PointerCount;
LONG HandleCount;
ULONG PagedPoolCharge;
ULONG NonPagedPoolCharge;
HANDLE ExclusiveProcessId;
PVOID SecurityDescriptor;
UNICODE_STRING NameInfo;
} SYSTEM_OBJECT_INFORMATION, *PSYSTEM_OBJECT_INFORMATION;
typedef struct _SYSTEM_PAGEFILE_INFORMATION
{
ULONG NextEntryOffset;
ULONG TotalSize;
ULONG TotalInUse;
ULONG PeakUsage;
UNICODE_STRING PageFileName;
} SYSTEM_PAGEFILE_INFORMATION, *PSYSTEM_PAGEFILE_INFORMATION;
#define MM_WORKING_SET_MAX_HARD_ENABLE 0x1
#define MM_WORKING_SET_MAX_HARD_DISABLE 0x2
#define MM_WORKING_SET_MIN_HARD_ENABLE 0x4
#define MM_WORKING_SET_MIN_HARD_DISABLE 0x8
typedef struct _SYSTEM_FILECACHE_INFORMATION
{
SIZE_T CurrentSize;
SIZE_T PeakSize;
ULONG PageFaultCount;
SIZE_T MinimumWorkingSet;
SIZE_T MaximumWorkingSet;
SIZE_T CurrentSizeIncludingTransitionInPages;
SIZE_T PeakSizeIncludingTransitionInPages;
ULONG TransitionRePurposeCount;
ULONG Flags;
} SYSTEM_FILECACHE_INFORMATION, *PSYSTEM_FILECACHE_INFORMATION;
// Can be used instead of SYSTEM_FILECACHE_INFORMATION
typedef struct _SYSTEM_BASIC_WORKING_SET_INFORMATION
{
SIZE_T CurrentSize;
SIZE_T PeakSize;
ULONG PageFaultCount;
} SYSTEM_BASIC_WORKING_SET_INFORMATION, *PSYSTEM_BASIC_WORKING_SET_INFORMATION;
typedef struct _SYSTEM_POOLTAG
{
union
{
UCHAR Tag[4];
ULONG TagUlong;
};
ULONG PagedAllocs;
ULONG PagedFrees;
SIZE_T PagedUsed;
ULONG NonPagedAllocs;
ULONG NonPagedFrees;
SIZE_T NonPagedUsed;
} SYSTEM_POOLTAG, *PSYSTEM_POOLTAG;
typedef struct _SYSTEM_POOLTAG_INFORMATION
{
ULONG Count;
SYSTEM_POOLTAG TagInfo[1];
} SYSTEM_POOLTAG_INFORMATION, *PSYSTEM_POOLTAG_INFORMATION;
typedef struct _SYSTEM_INTERRUPT_INFORMATION
{
ULONG ContextSwitches;
ULONG DpcCount;
ULONG DpcRate;
ULONG TimeIncrement;
ULONG DpcBypassCount;
ULONG ApcBypassCount;
} SYSTEM_INTERRUPT_INFORMATION, *PSYSTEM_INTERRUPT_INFORMATION;
typedef struct _SYSTEM_DPC_BEHAVIOR_INFORMATION
{
ULONG Spare;
ULONG DpcQueueDepth;
ULONG MinimumDpcRate;
ULONG AdjustDpcThreshold;
ULONG IdealDpcRate;
} SYSTEM_DPC_BEHAVIOR_INFORMATION, *PSYSTEM_DPC_BEHAVIOR_INFORMATION;
typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION
{
ULONG TimeAdjustment;
ULONG TimeIncrement;
BOOLEAN Enable;
} SYSTEM_QUERY_TIME_ADJUST_INFORMATION, *PSYSTEM_QUERY_TIME_ADJUST_INFORMATION;
typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION_PRECISE
{
ULONGLONG TimeAdjustment;
ULONGLONG TimeIncrement;
BOOLEAN Enable;
} SYSTEM_QUERY_TIME_ADJUST_INFORMATION_PRECISE, *PSYSTEM_QUERY_TIME_ADJUST_INFORMATION_PRECISE;
typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION
{
ULONG TimeAdjustment;
BOOLEAN Enable;
} SYSTEM_SET_TIME_ADJUST_INFORMATION, *PSYSTEM_SET_TIME_ADJUST_INFORMATION;
typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION_PRECISE
{
ULONGLONG TimeAdjustment;
BOOLEAN Enable;
} SYSTEM_SET_TIME_ADJUST_INFORMATION_PRECISE, *PSYSTEM_SET_TIME_ADJUST_INFORMATION_PRECISE;
typedef enum _EVENT_TRACE_INFORMATION_CLASS
{
EventTraceKernelVersionInformation, // EVENT_TRACE_VERSION_INFORMATION
EventTraceGroupMaskInformation, // EVENT_TRACE_GROUPMASK_INFORMATION
EventTracePerformanceInformation, // EVENT_TRACE_PERFORMANCE_INFORMATION
EventTraceTimeProfileInformation, // EVENT_TRACE_TIME_PROFILE_INFORMATION
EventTraceSessionSecurityInformation, // EVENT_TRACE_SESSION_SECURITY_INFORMATION
EventTraceSpinlockInformation, // EVENT_TRACE_SPINLOCK_INFORMATION
EventTraceStackTracingInformation, // EVENT_TRACE_SYSTEM_EVENT_INFORMATION
EventTraceExecutiveResourceInformation, // EVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION
EventTraceHeapTracingInformation, // EVENT_TRACE_HEAP_TRACING_INFORMATION
EventTraceHeapSummaryTracingInformation, // EVENT_TRACE_HEAP_TRACING_INFORMATION
EventTracePoolTagFilterInformation, // EVENT_TRACE_TAG_FILTER_INFORMATION
EventTracePebsTracingInformation, // EVENT_TRACE_SYSTEM_EVENT_INFORMATION
EventTraceProfileConfigInformation, // EVENT_TRACE_PROFILE_COUNTER_INFORMATION
EventTraceProfileSourceListInformation, // EVENT_TRACE_PROFILE_LIST_INFORMATION
EventTraceProfileEventListInformation, // EVENT_TRACE_SYSTEM_EVENT_INFORMATION
EventTraceProfileCounterListInformation, // EVENT_TRACE_PROFILE_COUNTER_INFORMATION
EventTraceStackCachingInformation, // EVENT_TRACE_STACK_CACHING_INFORMATION
EventTraceObjectTypeFilterInformation, // EVENT_TRACE_TAG_FILTER_INFORMATION
EventTraceSoftRestartInformation, // EVENT_TRACE_SOFT_RESTART_INFORMATION
EventTraceLastBranchConfigurationInformation, // REDSTONE3
EventTraceLastBranchEventListInformation,
EventTraceProfileSourceAddInformation, // EVENT_TRACE_PROFILE_ADD_INFORMATION // REDSTONE4
EventTraceProfileSourceRemoveInformation, // EVENT_TRACE_PROFILE_REMOVE_INFORMATION
EventTraceProcessorTraceConfigurationInformation,
EventTraceProcessorTraceEventListInformation,
EventTraceCoverageSamplerInformation, // EVENT_TRACE_COVERAGE_SAMPLER_INFORMATION
MaxEventTraceInfoClass
} EVENT_TRACE_INFORMATION_CLASS;
typedef struct _EVENT_TRACE_VERSION_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG EventTraceKernelVersion;
} EVENT_TRACE_VERSION_INFORMATION, *PEVENT_TRACE_VERSION_INFORMATION;
typedef struct _PERFINFO_GROUPMASK
{
ULONG Masks[8];
} PERFINFO_GROUPMASK, *PPERFINFO_GROUPMASK;
typedef struct _EVENT_TRACE_GROUPMASK_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
HANDLE TraceHandle;
PERFINFO_GROUPMASK EventTraceGroupMasks;
} EVENT_TRACE_GROUPMASK_INFORMATION, *PEVENT_TRACE_GROUPMASK_INFORMATION;
typedef struct _EVENT_TRACE_PERFORMANCE_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
LARGE_INTEGER LogfileBytesWritten;
} EVENT_TRACE_PERFORMANCE_INFORMATION, *PEVENT_TRACE_PERFORMANCE_INFORMATION;
typedef struct _EVENT_TRACE_TIME_PROFILE_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG ProfileInterval;
} EVENT_TRACE_TIME_PROFILE_INFORMATION, *PEVENT_TRACE_TIME_PROFILE_INFORMATION;
typedef struct _EVENT_TRACE_SESSION_SECURITY_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG SecurityInformation;
HANDLE TraceHandle;
UCHAR SecurityDescriptor[1];
} EVENT_TRACE_SESSION_SECURITY_INFORMATION, *PEVENT_TRACE_SESSION_SECURITY_INFORMATION;
typedef struct _EVENT_TRACE_SPINLOCK_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG SpinLockSpinThreshold;
ULONG SpinLockAcquireSampleRate;
ULONG SpinLockContentionSampleRate;
ULONG SpinLockHoldThreshold;
} EVENT_TRACE_SPINLOCK_INFORMATION, *PEVENT_TRACE_SPINLOCK_INFORMATION;
typedef struct _EVENT_TRACE_SYSTEM_EVENT_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
HANDLE TraceHandle;
ULONG HookId[1];
} EVENT_TRACE_SYSTEM_EVENT_INFORMATION, *PEVENT_TRACE_SYSTEM_EVENT_INFORMATION;
typedef struct _EVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG ReleaseSamplingRate;
ULONG ContentionSamplingRate;
ULONG NumberOfExcessiveTimeouts;
} EVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION, *PEVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION;
typedef struct _EVENT_TRACE_HEAP_TRACING_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG ProcessId;
} EVENT_TRACE_HEAP_TRACING_INFORMATION, *PEVENT_TRACE_HEAP_TRACING_INFORMATION;
typedef struct _EVENT_TRACE_TAG_FILTER_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
HANDLE TraceHandle;
ULONG Filter[1];
} EVENT_TRACE_TAG_FILTER_INFORMATION, *PEVENT_TRACE_TAG_FILTER_INFORMATION;
typedef struct _EVENT_TRACE_PROFILE_COUNTER_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
HANDLE TraceHandle;
ULONG ProfileSource[1];
} EVENT_TRACE_PROFILE_COUNTER_INFORMATION, *PEVENT_TRACE_PROFILE_COUNTER_INFORMATION;
//typedef struct _PROFILE_SOURCE_INFO
//{
// ULONG NextEntryOffset;
// ULONG Source;
// ULONG MinInterval;
// ULONG MaxInterval;
// PVOID Reserved;
// WCHAR Description[1];
//} PROFILE_SOURCE_INFO, *PPROFILE_SOURCE_INFO;
typedef struct _EVENT_TRACE_PROFILE_LIST_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
ULONG Spare;
struct _PROFILE_SOURCE_INFO* Profile[1];
} EVENT_TRACE_PROFILE_LIST_INFORMATION, *PEVENT_TRACE_PROFILE_LIST_INFORMATION;
typedef struct _EVENT_TRACE_STACK_CACHING_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
HANDLE TraceHandle;
BOOLEAN Enabled;
UCHAR Reserved[3];
ULONG CacheSize;
ULONG BucketCount;
} EVENT_TRACE_STACK_CACHING_INFORMATION, *PEVENT_TRACE_STACK_CACHING_INFORMATION;
typedef struct _EVENT_TRACE_SOFT_RESTART_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
HANDLE TraceHandle;
BOOLEAN PersistTraceBuffers;
WCHAR FileName[1];
} EVENT_TRACE_SOFT_RESTART_INFORMATION, *PEVENT_TRACE_SOFT_RESTART_INFORMATION;
typedef struct _EVENT_TRACE_PROFILE_ADD_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
BOOLEAN PerfEvtEventSelect;
BOOLEAN PerfEvtUnitSelect;
ULONG PerfEvtType;
ULONG CpuInfoHierarchy[0x3];
ULONG InitialInterval;
BOOLEAN AllowsHalt;
BOOLEAN Persist;
WCHAR ProfileSourceDescription[0x1];
} EVENT_TRACE_PROFILE_ADD_INFORMATION, *PEVENT_TRACE_PROFILE_ADD_INFORMATION;
typedef struct _EVENT_TRACE_PROFILE_REMOVE_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
KPROFILE_SOURCE ProfileSource;
ULONG CpuInfoHierarchy[0x3];
} EVENT_TRACE_PROFILE_REMOVE_INFORMATION, *PEVENT_TRACE_PROFILE_REMOVE_INFORMATION;
typedef struct _EVENT_TRACE_COVERAGE_SAMPLER_INFORMATION
{
EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
BOOLEAN CoverageSamplerInformationClass;
UCHAR MajorVersion;
UCHAR MinorVersion;
UCHAR Reserved;
HANDLE SamplerHandle;
} EVENT_TRACE_COVERAGE_SAMPLER_INFORMATION, *PEVENT_TRACE_COVERAGE_SAMPLER_INFORMATION;
typedef struct _SYSTEM_EXCEPTION_INFORMATION
{
ULONG AlignmentFixupCount;
ULONG ExceptionDispatchCount;
ULONG FloatingEmulationCount;
ULONG ByteWordEmulationCount;
} SYSTEM_EXCEPTION_INFORMATION, *PSYSTEM_EXCEPTION_INFORMATION;
typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION
{
BOOLEAN KernelDebuggerEnabled;
BOOLEAN KernelDebuggerNotPresent;
} SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION;
typedef struct _SYSTEM_CONTEXT_SWITCH_INFORMATION
{
ULONG ContextSwitches;
ULONG FindAny;
ULONG FindLast;
ULONG FindIdeal;
ULONG IdleAny;
ULONG IdleCurrent;
ULONG IdleLast;
ULONG IdleIdeal;
ULONG PreemptAny;
ULONG PreemptCurrent;
ULONG PreemptLast;
ULONG SwitchToIdle;
} SYSTEM_CONTEXT_SWITCH_INFORMATION, *PSYSTEM_CONTEXT_SWITCH_INFORMATION;
typedef struct _SYSTEM_REGISTRY_QUOTA_INFORMATION
{
ULONG RegistryQuotaAllowed;
ULONG RegistryQuotaUsed;
SIZE_T PagedPoolSize;
} SYSTEM_REGISTRY_QUOTA_INFORMATION, *PSYSTEM_REGISTRY_QUOTA_INFORMATION;
typedef struct _SYSTEM_PROCESSOR_IDLE_INFORMATION
{
ULONGLONG IdleTime;
ULONGLONG C1Time;
ULONGLONG C2Time;
ULONGLONG C3Time;
ULONG C1Transitions;
ULONG C2Transitions;
ULONG C3Transitions;
ULONG Padding;
} SYSTEM_PROCESSOR_IDLE_INFORMATION, *PSYSTEM_PROCESSOR_IDLE_INFORMATION;
typedef struct _SYSTEM_LEGACY_DRIVER_INFORMATION
{
ULONG VetoType;
UNICODE_STRING VetoList;
} SYSTEM_LEGACY_DRIVER_INFORMATION, *PSYSTEM_LEGACY_DRIVER_INFORMATION;
typedef struct _SYSTEM_LOOKASIDE_INFORMATION
{
USHORT CurrentDepth;
USHORT MaximumDepth;
ULONG TotalAllocates;
ULONG AllocateMisses;
ULONG TotalFrees;
ULONG FreeMisses;
ULONG Type;
ULONG Tag;
ULONG Size;
} SYSTEM_LOOKASIDE_INFORMATION, *PSYSTEM_LOOKASIDE_INFORMATION;
// private
typedef struct _SYSTEM_RANGE_START_INFORMATION
{
PVOID SystemRangeStart;
} SYSTEM_RANGE_START_INFORMATION, *PSYSTEM_RANGE_START_INFORMATION;
typedef struct _SYSTEM_VERIFIER_INFORMATION_LEGACY // pre-19H1
{
ULONG NextEntryOffset;
ULONG Level;
UNICODE_STRING DriverName;
ULONG RaiseIrqls;
ULONG AcquireSpinLocks;
ULONG SynchronizeExecutions;
ULONG AllocationsAttempted;
ULONG AllocationsSucceeded;
ULONG AllocationsSucceededSpecialPool;
ULONG AllocationsWithNoTag;
ULONG TrimRequests;
ULONG Trims;
ULONG AllocationsFailed;
ULONG AllocationsFailedDeliberately;
ULONG Loads;
ULONG Unloads;
ULONG UnTrackedPool;
ULONG CurrentPagedPoolAllocations;
ULONG CurrentNonPagedPoolAllocations;
ULONG PeakPagedPoolAllocations;
ULONG PeakNonPagedPoolAllocations;
SIZE_T PagedPoolUsageInBytes;
SIZE_T NonPagedPoolUsageInBytes;
SIZE_T PeakPagedPoolUsageInBytes;
SIZE_T PeakNonPagedPoolUsageInBytes;
} SYSTEM_VERIFIER_INFORMATION_LEGACY, *PSYSTEM_VERIFIER_INFORMATION_LEGACY;
typedef struct _SYSTEM_VERIFIER_INFORMATION
{
ULONG NextEntryOffset;
ULONG Level;
ULONG RuleClasses[2];
ULONG TriageContext;
ULONG AreAllDriversBeingVerified;
UNICODE_STRING DriverName;
ULONG RaiseIrqls;
ULONG AcquireSpinLocks;
ULONG SynchronizeExecutions;
ULONG AllocationsAttempted;
ULONG AllocationsSucceeded;
ULONG AllocationsSucceededSpecialPool;
ULONG AllocationsWithNoTag;
ULONG TrimRequests;
ULONG Trims;
ULONG AllocationsFailed;
ULONG AllocationsFailedDeliberately;
ULONG Loads;
ULONG Unloads;
ULONG UnTrackedPool;
ULONG CurrentPagedPoolAllocations;
ULONG CurrentNonPagedPoolAllocations;
ULONG PeakPagedPoolAllocations;
ULONG PeakNonPagedPoolAllocations;
SIZE_T PagedPoolUsageInBytes;
SIZE_T NonPagedPoolUsageInBytes;
SIZE_T PeakPagedPoolUsageInBytes;
SIZE_T PeakNonPagedPoolUsageInBytes;
} SYSTEM_VERIFIER_INFORMATION, *PSYSTEM_VERIFIER_INFORMATION;
typedef struct _SYSTEM_SESSION_PROCESS_INFORMATION
{
ULONG SessionId;
ULONG SizeOfBuf;
PVOID Buffer;
} SYSTEM_SESSION_PROCESS_INFORMATION, *PSYSTEM_SESSION_PROCESS_INFORMATION;
typedef struct _SYSTEM_PROCESSOR_POWER_INFORMATION
{
UCHAR CurrentFrequency;
UCHAR ThermalLimitFrequency;
UCHAR ConstantThrottleFrequency;
UCHAR DegradedThrottleFrequency;
UCHAR LastBusyFrequency;
UCHAR LastC3Frequency;
UCHAR LastAdjustedBusyFrequency;
UCHAR ProcessorMinThrottle;
UCHAR ProcessorMaxThrottle;
ULONG NumberOfFrequencies;
ULONG PromotionCount;
ULONG DemotionCount;
ULONG ErrorCount;
ULONG RetryCount;
ULONGLONG CurrentFrequencyTime;
ULONGLONG CurrentProcessorTime;
ULONGLONG CurrentProcessorIdleTime;
ULONGLONG LastProcessorTime;
ULONGLONG LastProcessorIdleTime;
ULONGLONG Energy;
} SYSTEM_PROCESSOR_POWER_INFORMATION, *PSYSTEM_PROCESSOR_POWER_INFORMATION;
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
{
PVOID Object;
ULONG_PTR UniqueProcessId;
ULONG_PTR HandleValue;
ULONG GrantedAccess;
USHORT CreatorBackTraceIndex;
USHORT ObjectTypeIndex;
ULONG HandleAttributes;
ULONG Reserved;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX;
typedef struct _SYSTEM_HANDLE_INFORMATION_EX
{
ULONG_PTR NumberOfHandles;
ULONG_PTR Reserved;
SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];
} SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX;
typedef struct _SYSTEM_BIGPOOL_ENTRY
{
union
{
PVOID VirtualAddress;
ULONG_PTR NonPaged : 1;
};
SIZE_T SizeInBytes;
union
{
UCHAR Tag[4];
ULONG TagUlong;
};
} SYSTEM_BIGPOOL_ENTRY, *PSYSTEM_BIGPOOL_ENTRY;
typedef struct _SYSTEM_BIGPOOL_INFORMATION
{
ULONG Count;
SYSTEM_BIGPOOL_ENTRY AllocatedInfo[1];
} SYSTEM_BIGPOOL_INFORMATION, *PSYSTEM_BIGPOOL_INFORMATION;
typedef struct _SYSTEM_POOL_ENTRY
{
BOOLEAN Allocated;
BOOLEAN Spare0;
USHORT AllocatorBackTraceIndex;
ULONG Size;
union
{
UCHAR Tag[4];
ULONG TagUlong;
PVOID ProcessChargedQuota;
};
} SYSTEM_POOL_ENTRY, *PSYSTEM_POOL_ENTRY;
typedef struct _SYSTEM_POOL_INFORMATION
{
SIZE_T TotalSize;
PVOID FirstEntry;
USHORT EntryOverhead;
BOOLEAN PoolTagPresent;
BOOLEAN Spare0;
ULONG NumberOfEntries;
SYSTEM_POOL_ENTRY Entries[1];
} SYSTEM_POOL_INFORMATION, *PSYSTEM_POOL_INFORMATION;
typedef struct _SYSTEM_SESSION_POOLTAG_INFORMATION
{
SIZE_T NextEntryOffset;
ULONG SessionId;
ULONG Count;
SYSTEM_POOLTAG TagInfo[1];
} SYSTEM_SESSION_POOLTAG_INFORMATION, *PSYSTEM_SESSION_POOLTAG_INFORMATION;
typedef struct _SYSTEM_SESSION_MAPPED_VIEW_INFORMATION
{
SIZE_T NextEntryOffset;
ULONG SessionId;
ULONG ViewFailures;
SIZE_T NumberOfBytesAvailable;
SIZE_T NumberOfBytesAvailableContiguous;
} SYSTEM_SESSION_MAPPED_VIEW_INFORMATION, *PSYSTEM_SESSION_MAPPED_VIEW_INFORMATION;
// private
typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION
{
SystemFirmwareTableEnumerate,
SystemFirmwareTableGet,
SystemFirmwareTableMax
} SYSTEM_FIRMWARE_TABLE_ACTION;
// private
typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION
{
ULONG ProviderSignature; // (same as the GetSystemFirmwareTable function)
SYSTEM_FIRMWARE_TABLE_ACTION Action;
ULONG TableID;
ULONG TableBufferLength;
UCHAR TableBuffer[1];
} SYSTEM_FIRMWARE_TABLE_INFORMATION, *PSYSTEM_FIRMWARE_TABLE_INFORMATION;
// private
typedef struct _SYSTEM_MEMORY_LIST_INFORMATION
{
ULONG_PTR ZeroPageCount;
ULONG_PTR FreePageCount;
ULONG_PTR ModifiedPageCount;
ULONG_PTR ModifiedNoWritePageCount;
ULONG_PTR BadPageCount;
ULONG_PTR PageCountByPriority[8];
ULONG_PTR RepurposedPagesByPriority[8];
ULONG_PTR ModifiedPageCountPageFile;
} SYSTEM_MEMORY_LIST_INFORMATION, *PSYSTEM_MEMORY_LIST_INFORMATION;
// private
typedef enum _SYSTEM_MEMORY_LIST_COMMAND
{
MemoryCaptureAccessedBits,
MemoryCaptureAndResetAccessedBits,
MemoryEmptyWorkingSets,
MemoryFlushModifiedList,
MemoryPurgeStandbyList,
MemoryPurgeLowPriorityStandbyList,
MemoryCommandMax
} SYSTEM_MEMORY_LIST_COMMAND;
// private
typedef struct _SYSTEM_THREAD_CID_PRIORITY_INFORMATION
{
CLIENT_ID ClientId;
KPRIORITY Priority;
} SYSTEM_THREAD_CID_PRIORITY_INFORMATION, *PSYSTEM_THREAD_CID_PRIORITY_INFORMATION;
// private
typedef struct _SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION
{
ULONGLONG CycleTime;
} SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION, *PSYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION;
// private
typedef struct _SYSTEM_REF_TRACE_INFORMATION
{
BOOLEAN TraceEnable;
BOOLEAN TracePermanent;
UNICODE_STRING TraceProcessName;
UNICODE_STRING TracePoolTags;
} SYSTEM_REF_TRACE_INFORMATION, *PSYSTEM_REF_TRACE_INFORMATION;
// private
typedef struct _SYSTEM_PROCESS_ID_INFORMATION
{
HANDLE ProcessId;
UNICODE_STRING ImageName;
} SYSTEM_PROCESS_ID_INFORMATION, *PSYSTEM_PROCESS_ID_INFORMATION;
// private
typedef struct _SYSTEM_BOOT_ENVIRONMENT_INFORMATION
{
GUID BootIdentifier;
FIRMWARE_TYPE FirmwareType;
union
{
ULONGLONG BootFlags;
struct
{
ULONGLONG DbgMenuOsSelection : 1; // REDSTONE4
ULONGLONG DbgHiberBoot : 1;
ULONGLONG DbgSoftBoot : 1;
ULONGLONG DbgMeasuredLaunch : 1;
ULONGLONG DbgMeasuredLaunchCapable : 1; // 19H1
ULONGLONG DbgSystemHiveReplace : 1;
ULONGLONG DbgMeasuredLaunchSmmProtections : 1;
};
};
} SYSTEM_BOOT_ENVIRONMENT_INFORMATION, *PSYSTEM_BOOT_ENVIRONMENT_INFORMATION;
// private
typedef struct _SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION
{
ULONG FlagsToEnable;
ULONG FlagsToDisable;
} SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION, *PSYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION;
// private
typedef struct _SYSTEM_VERIFIER_INFORMATION_EX
{
ULONG VerifyMode;
ULONG OptionChanges;
UNICODE_STRING PreviousBucketName;
ULONG IrpCancelTimeoutMsec;
ULONG VerifierExtensionEnabled;
#ifdef _WIN64
ULONG Reserved[1];
#else
ULONG Reserved[3];
#endif
} SYSTEM_VERIFIER_INFORMATION_EX, *PSYSTEM_VERIFIER_INFORMATION_EX;
// private
typedef struct _SYSTEM_SYSTEM_PARTITION_INFORMATION
{
UNICODE_STRING SystemPartition;
} SYSTEM_SYSTEM_PARTITION_INFORMATION, *PSYSTEM_SYSTEM_PARTITION_INFORMATION;
// private
typedef struct _SYSTEM_SYSTEM_DISK_INFORMATION
{
UNICODE_STRING SystemDisk;
} SYSTEM_SYSTEM_DISK_INFORMATION, *PSYSTEM_SYSTEM_DISK_INFORMATION;
// private (Windows 8.1 and above)
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT
{
ULONGLONG Hits;
UCHAR PercentFrequency;
} SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT, *PSYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT;
// private (Windows 7 and Windows 8)
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT_WIN8
{
ULONG Hits;
UCHAR PercentFrequency;
} SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT_WIN8, *PSYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT_WIN8;
// private
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_STATE_DISTRIBUTION
{
ULONG ProcessorNumber;
ULONG StateCount;
SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT States[1];
} SYSTEM_PROCESSOR_PERFORMANCE_STATE_DISTRIBUTION, *PSYSTEM_PROCESSOR_PERFORMANCE_STATE_DISTRIBUTION;
// private
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION
{
ULONG ProcessorCount;
ULONG Offsets[1];
} SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION, *PSYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION;
// private
typedef struct _SYSTEM_CODEINTEGRITY_INFORMATION
{
ULONG Length;
ULONG CodeIntegrityOptions;
} SYSTEM_CODEINTEGRITY_INFORMATION, *PSYSTEM_CODEINTEGRITY_INFORMATION;
// private
typedef enum _SYSTEM_VA_TYPE
{
SystemVaTypeAll,
SystemVaTypeNonPagedPool,
SystemVaTypePagedPool,
SystemVaTypeSystemCache,
SystemVaTypeSystemPtes,
SystemVaTypeSessionSpace,
SystemVaTypeMax
} SYSTEM_VA_TYPE, *PSYSTEM_VA_TYPE;
// private
typedef struct _SYSTEM_VA_LIST_INFORMATION
{
SIZE_T VirtualSize;
SIZE_T VirtualPeak;
SIZE_T VirtualLimit;
SIZE_T AllocationFailures;
} SYSTEM_VA_LIST_INFORMATION, *PSYSTEM_VA_LIST_INFORMATION;
// rev
typedef enum _SYSTEM_STORE_INFORMATION_CLASS
{
SystemStoreCompressionInformation = 22 // q: SYSTEM_STORE_COMPRESSION_INFORMATION
} SYSTEM_STORE_INFORMATION_CLASS;
// rev
#define SYSTEM_STORE_INFORMATION_VERSION 1
// rev
typedef struct _SYSTEM_STORE_INFORMATION
{
_In_ ULONG Version;
_In_ SYSTEM_STORE_INFORMATION_CLASS StoreInformationClass;
_Inout_ PVOID Data;
_Inout_ ULONG Length;
} SYSTEM_STORE_INFORMATION, *PSYSTEM_STORE_INFORMATION;
// rev
#define SYSTEM_STORE_COMPRESSION_INFORMATION_VERSION 3
// rev
typedef struct _SYSTEM_STORE_COMPRESSION_INFORMATION
{
ULONG Version;
ULONG CompressionPid;
ULONGLONG CompressionWorkingSetSize;
ULONGLONG CompressSize;
ULONGLONG CompressedSize;
ULONGLONG NonCompressedSize;
} SYSTEM_STORE_COMPRESSION_INFORMATION, *PSYSTEM_STORE_COMPRESSION_INFORMATION;
// private
typedef struct _SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS
{
HANDLE KeyHandle;
PUNICODE_STRING ValueNamePointer;
PULONG RequiredLengthPointer;
PUCHAR Buffer;
ULONG BufferLength;
ULONG Type;
PUCHAR AppendBuffer;
ULONG AppendBufferLength;
BOOLEAN CreateIfDoesntExist;
BOOLEAN TruncateExistingValue;
} SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS, *PSYSTEM_REGISTRY_APPEND_STRING_PARAMETERS;
// msdn
typedef struct _SYSTEM_VHD_BOOT_INFORMATION
{
BOOLEAN OsDiskIsVhd;
ULONG OsVhdFilePathOffset;
WCHAR OsVhdParentVolume[ANYSIZE_ARRAY];
} SYSTEM_VHD_BOOT_INFORMATION, *PSYSTEM_VHD_BOOT_INFORMATION;
// private
typedef struct _SYSTEM_LOW_PRIORITY_IO_INFORMATION
{
ULONG LowPriReadOperations;
ULONG LowPriWriteOperations;
ULONG KernelBumpedToNormalOperations;
ULONG LowPriPagingReadOperations;
ULONG KernelPagingReadsBumpedToNormal;
ULONG LowPriPagingWriteOperations;
ULONG KernelPagingWritesBumpedToNormal;
ULONG BoostedIrpCount;
ULONG BoostedPagingIrpCount;
ULONG BlanketBoostCount;
} SYSTEM_LOW_PRIORITY_IO_INFORMATION, *PSYSTEM_LOW_PRIORITY_IO_INFORMATION;
// symbols
typedef enum _TPM_BOOT_ENTROPY_RESULT_CODE
{
TpmBootEntropyStructureUninitialized,
TpmBootEntropyDisabledByPolicy,
TpmBootEntropyNoTpmFound,
TpmBootEntropyTpmError,
TpmBootEntropySuccess
} TPM_BOOT_ENTROPY_RESULT_CODE;
// Contents of KeLoaderBlock->Extension->TpmBootEntropyResult (TPM_BOOT_ENTROPY_LDR_RESULT).
// EntropyData is truncated to 40 bytes.
// private
typedef struct _TPM_BOOT_ENTROPY_NT_RESULT
{
ULONGLONG Policy;
TPM_BOOT_ENTROPY_RESULT_CODE ResultCode;
NTSTATUS ResultStatus;
ULONGLONG Time;
ULONG EntropyLength;
UCHAR EntropyData[40];
} TPM_BOOT_ENTROPY_NT_RESULT, *PTPM_BOOT_ENTROPY_NT_RESULT;
// private
typedef struct _SYSTEM_VERIFIER_COUNTERS_INFORMATION
{
SYSTEM_VERIFIER_INFORMATION Legacy;
ULONG RaiseIrqls;
ULONG AcquireSpinLocks;
ULONG SynchronizeExecutions;
ULONG AllocationsWithNoTag;
ULONG AllocationsFailed;
ULONG AllocationsFailedDeliberately;
SIZE_T LockedBytes;
SIZE_T PeakLockedBytes;
SIZE_T MappedLockedBytes;
SIZE_T PeakMappedLockedBytes;
SIZE_T MappedIoSpaceBytes;
SIZE_T PeakMappedIoSpaceBytes;
SIZE_T PagesForMdlBytes;
SIZE_T PeakPagesForMdlBytes;
SIZE_T ContiguousMemoryBytes;
SIZE_T PeakContiguousMemoryBytes;
ULONG ExecutePoolTypes; // REDSTONE2
ULONG ExecutePageProtections;
ULONG ExecutePageMappings;
ULONG ExecuteWriteSections;
ULONG SectionAlignmentFailures;
ULONG UnsupportedRelocs;
ULONG IATInExecutableSection;
} SYSTEM_VERIFIER_COUNTERS_INFORMATION, *PSYSTEM_VERIFIER_COUNTERS_INFORMATION;
// private
typedef struct _SYSTEM_ACPI_AUDIT_INFORMATION
{
ULONG RsdpCount;
ULONG SameRsdt : 1;
ULONG SlicPresent : 1;
ULONG SlicDifferent : 1;
} SYSTEM_ACPI_AUDIT_INFORMATION, *PSYSTEM_ACPI_AUDIT_INFORMATION;
// private
typedef struct _SYSTEM_BASIC_PERFORMANCE_INFORMATION
{
SIZE_T AvailablePages;
SIZE_T CommittedPages;
SIZE_T CommitLimit;
SIZE_T PeakCommitment;
} SYSTEM_BASIC_PERFORMANCE_INFORMATION, *PSYSTEM_BASIC_PERFORMANCE_INFORMATION;
// begin_msdn
typedef struct _QUERY_PERFORMANCE_COUNTER_FLAGS
{
union
{
struct
{
ULONG KernelTransition : 1;
ULONG Reserved : 31;
};
ULONG ul;
};
} QUERY_PERFORMANCE_COUNTER_FLAGS;
typedef struct _SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION
{
ULONG Version;
QUERY_PERFORMANCE_COUNTER_FLAGS Flags;
QUERY_PERFORMANCE_COUNTER_FLAGS ValidFlags;
} SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION, *PSYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION;
// end_msdn
// private
typedef enum _SYSTEM_PIXEL_FORMAT
{
SystemPixelFormatUnknown,
SystemPixelFormatR8G8B8,
SystemPixelFormatR8G8B8X8,
SystemPixelFormatB8G8R8,
SystemPixelFormatB8G8R8X8
} SYSTEM_PIXEL_FORMAT;
// private
typedef struct _SYSTEM_BOOT_GRAPHICS_INFORMATION
{
LARGE_INTEGER FrameBuffer;
ULONG Width;
ULONG Height;
ULONG PixelStride;
ULONG Flags;
SYSTEM_PIXEL_FORMAT Format;
ULONG DisplayRotation;
} SYSTEM_BOOT_GRAPHICS_INFORMATION, *PSYSTEM_BOOT_GRAPHICS_INFORMATION;
// private
typedef struct _MEMORY_SCRUB_INFORMATION
{
HANDLE Handle;
ULONG PagesScrubbed;
} MEMORY_SCRUB_INFORMATION, *PMEMORY_SCRUB_INFORMATION;
// private
typedef struct _PEBS_DS_SAVE_AREA32
{
ULONG BtsBufferBase;
ULONG BtsIndex;
ULONG BtsAbsoluteMaximum;
ULONG BtsInterruptThreshold;
ULONG PebsBufferBase;
ULONG PebsIndex;
ULONG PebsAbsoluteMaximum;
ULONG PebsInterruptThreshold;
ULONG PebsGpCounterReset[8];
ULONG PebsFixedCounterReset[4];
} PEBS_DS_SAVE_AREA32, *PPEBS_DS_SAVE_AREA32;
// private
typedef struct _PEBS_DS_SAVE_AREA64
{
ULONGLONG BtsBufferBase;
ULONGLONG BtsIndex;
ULONGLONG BtsAbsoluteMaximum;
ULONGLONG BtsInterruptThreshold;
ULONGLONG PebsBufferBase;
ULONGLONG PebsIndex;
ULONGLONG PebsAbsoluteMaximum;
ULONGLONG PebsInterruptThreshold;
ULONGLONG PebsGpCounterReset[8];
ULONGLONG PebsFixedCounterReset[4];
} PEBS_DS_SAVE_AREA64, *PPEBS_DS_SAVE_AREA64;
// private
typedef union _PEBS_DS_SAVE_AREA
{
PEBS_DS_SAVE_AREA32 As32Bit;
PEBS_DS_SAVE_AREA64 As64Bit;
} PEBS_DS_SAVE_AREA, *PPEBS_DS_SAVE_AREA;
// private
typedef struct _PROCESSOR_PROFILE_CONTROL_AREA
{
PEBS_DS_SAVE_AREA PebsDsSaveArea;
} PROCESSOR_PROFILE_CONTROL_AREA, *PPROCESSOR_PROFILE_CONTROL_AREA;
// private
typedef struct _SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA
{
PROCESSOR_PROFILE_CONTROL_AREA ProcessorProfileControlArea;
BOOLEAN Allocate;
} SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA, *PSYSTEM_PROCESSOR_PROFILE_CONTROL_AREA;
// private
typedef struct _MEMORY_COMBINE_INFORMATION
{
HANDLE Handle;
ULONG_PTR PagesCombined;
} MEMORY_COMBINE_INFORMATION, *PMEMORY_COMBINE_INFORMATION;
// rev
#define MEMORY_COMBINE_FLAGS_COMMON_PAGES_ONLY 0x4
// private
typedef struct _MEMORY_COMBINE_INFORMATION_EX
{
HANDLE Handle;
ULONG_PTR PagesCombined;
ULONG Flags;
} MEMORY_COMBINE_INFORMATION_EX, *PMEMORY_COMBINE_INFORMATION_EX;
// private
typedef struct _MEMORY_COMBINE_INFORMATION_EX2
{
HANDLE Handle;
ULONG_PTR PagesCombined;
ULONG Flags;
HANDLE ProcessHandle;
} MEMORY_COMBINE_INFORMATION_EX2, *PMEMORY_COMBINE_INFORMATION_EX2;
// private
typedef struct _SYSTEM_CONSOLE_INFORMATION
{
ULONG DriverLoaded : 1;
ULONG Spare : 31;
} SYSTEM_CONSOLE_INFORMATION, *PSYSTEM_CONSOLE_INFORMATION;
// private
typedef struct _SYSTEM_PLATFORM_BINARY_INFORMATION
{
ULONG64 PhysicalAddress;
PVOID HandoffBuffer;
PVOID CommandLineBuffer;
ULONG HandoffBufferSize;
ULONG CommandLineBufferSize;
} SYSTEM_PLATFORM_BINARY_INFORMATION, *PSYSTEM_PLATFORM_BINARY_INFORMATION;
// private
typedef struct _SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION
{
ULONG NumberOfLogicalProcessors;
ULONG NumberOfCores;
} SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION, *PSYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION;
// private
typedef struct _SYSTEM_DEVICE_DATA_INFORMATION
{
UNICODE_STRING DeviceId;
UNICODE_STRING DataName;
ULONG DataType;
ULONG DataBufferLength;
PVOID DataBuffer;
} SYSTEM_DEVICE_DATA_INFORMATION, *PSYSTEM_DEVICE_DATA_INFORMATION;
// private
typedef struct _PHYSICAL_CHANNEL_RUN
{
ULONG NodeNumber;
ULONG ChannelNumber;
ULONGLONG BasePage;
ULONGLONG PageCount;
ULONG Flags;
} PHYSICAL_CHANNEL_RUN, *PPHYSICAL_CHANNEL_RUN;
// private
typedef struct _SYSTEM_MEMORY_TOPOLOGY_INFORMATION
{
ULONGLONG NumberOfRuns;
ULONG NumberOfNodes;
ULONG NumberOfChannels;
PHYSICAL_CHANNEL_RUN Run[1];
} SYSTEM_MEMORY_TOPOLOGY_INFORMATION, *PSYSTEM_MEMORY_TOPOLOGY_INFORMATION;
// private
typedef struct _SYSTEM_MEMORY_CHANNEL_INFORMATION
{
ULONG ChannelNumber;
ULONG ChannelHeatIndex;
ULONGLONG TotalPageCount;
ULONGLONG ZeroPageCount;
ULONGLONG FreePageCount;
ULONGLONG StandbyPageCount;
} SYSTEM_MEMORY_CHANNEL_INFORMATION, *PSYSTEM_MEMORY_CHANNEL_INFORMATION;
// private
typedef struct _SYSTEM_BOOT_LOGO_INFORMATION
{
ULONG Flags;
ULONG BitmapOffset;
} SYSTEM_BOOT_LOGO_INFORMATION, *PSYSTEM_BOOT_LOGO_INFORMATION;
// private
typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX
{
LARGE_INTEGER IdleTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER DpcTime;
LARGE_INTEGER InterruptTime;
ULONG InterruptCount;
ULONG Spare0;
LARGE_INTEGER AvailableTime;
LARGE_INTEGER Spare1;
LARGE_INTEGER Spare2;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX;
// private
typedef struct _SYSTEM_SECUREBOOT_POLICY_INFORMATION
{
GUID PolicyPublisher;
ULONG PolicyVersion;
ULONG PolicyOptions;
} SYSTEM_SECUREBOOT_POLICY_INFORMATION, *PSYSTEM_SECUREBOOT_POLICY_INFORMATION;
// private
typedef struct _SYSTEM_PAGEFILE_INFORMATION_EX
{
SYSTEM_PAGEFILE_INFORMATION Info;
ULONG MinimumSize;
ULONG MaximumSize;
} SYSTEM_PAGEFILE_INFORMATION_EX, *PSYSTEM_PAGEFILE_INFORMATION_EX;
// private
typedef struct _SYSTEM_SECUREBOOT_INFORMATION
{
BOOLEAN SecureBootEnabled;
BOOLEAN SecureBootCapable;
} SYSTEM_SECUREBOOT_INFORMATION, *PSYSTEM_SECUREBOOT_INFORMATION;
// private
typedef struct _PROCESS_DISK_COUNTERS
{
ULONGLONG BytesRead;
ULONGLONG BytesWritten;
ULONGLONG ReadOperationCount;
ULONGLONG WriteOperationCount;
ULONGLONG FlushOperationCount;
} PROCESS_DISK_COUNTERS, *PPROCESS_DISK_COUNTERS;
// private
typedef union _ENERGY_STATE_DURATION
{
union
{
ULONGLONG Value;
ULONG LastChangeTime;
};
ULONG Duration : 31;
ULONG IsInState : 1;
} ENERGY_STATE_DURATION, *PENERGY_STATE_DURATION;
typedef struct _PROCESS_ENERGY_VALUES
{
ULONGLONG Cycles[4][2];
ULONGLONG DiskEnergy;
ULONGLONG NetworkTailEnergy;
ULONGLONG MBBTailEnergy;
ULONGLONG NetworkTxRxBytes;
ULONGLONG MBBTxRxBytes;
union
{
ENERGY_STATE_DURATION Durations[3];
struct
{
ENERGY_STATE_DURATION ForegroundDuration;
ENERGY_STATE_DURATION DesktopVisibleDuration;
ENERGY_STATE_DURATION PSMForegroundDuration;
};
};
ULONG CompositionRendered;
ULONG CompositionDirtyGenerated;
ULONG CompositionDirtyPropagated;
ULONG Reserved1;
ULONGLONG AttributedCycles[4][2];
ULONGLONG WorkOnBehalfCycles[4][2];
} PROCESS_ENERGY_VALUES, *PPROCESS_ENERGY_VALUES;
typedef struct _TIMELINE_BITMAP
{
ULONGLONG Value;
ULONG EndTime;
ULONG Bitmap;
} TIMELINE_BITMAP, *PTIMELINE_BITMAP;
typedef struct _PROCESS_ENERGY_VALUES_EXTENSION
{
union
{
TIMELINE_BITMAP Timelines[14]; // 9 for REDSTONE2, 14 for REDSTONE3/4/5
struct
{
TIMELINE_BITMAP CpuTimeline;
TIMELINE_BITMAP DiskTimeline;
TIMELINE_BITMAP NetworkTimeline;
TIMELINE_BITMAP MBBTimeline;
TIMELINE_BITMAP ForegroundTimeline;
TIMELINE_BITMAP DesktopVisibleTimeline;
TIMELINE_BITMAP CompositionRenderedTimeline;
TIMELINE_BITMAP CompositionDirtyGeneratedTimeline;
TIMELINE_BITMAP CompositionDirtyPropagatedTimeline;
TIMELINE_BITMAP InputTimeline; // REDSTONE3
TIMELINE_BITMAP AudioInTimeline;
TIMELINE_BITMAP AudioOutTimeline;
TIMELINE_BITMAP DisplayRequiredTimeline;
TIMELINE_BITMAP KeyboardInputTimeline;
};
};
union // REDSTONE3
{
ENERGY_STATE_DURATION Durations[5];
struct
{
ENERGY_STATE_DURATION InputDuration;
ENERGY_STATE_DURATION AudioInDuration;
ENERGY_STATE_DURATION AudioOutDuration;
ENERGY_STATE_DURATION DisplayRequiredDuration;
ENERGY_STATE_DURATION PSMBackgroundDuration;
};
};
ULONG KeyboardInput;
ULONG MouseInput;
} PROCESS_ENERGY_VALUES_EXTENSION, *PPROCESS_ENERGY_VALUES_EXTENSION;
typedef struct _PROCESS_EXTENDED_ENERGY_VALUES
{
PROCESS_ENERGY_VALUES Base;
PROCESS_ENERGY_VALUES_EXTENSION Extension;
} PROCESS_EXTENDED_ENERGY_VALUES, *PPROCESS_EXTENDED_ENERGY_VALUES;
// private
typedef enum _SYSTEM_PROCESS_CLASSIFICATION
{
SystemProcessClassificationNormal,
SystemProcessClassificationSystem,
SystemProcessClassificationSecureSystem,
SystemProcessClassificationMemCompression,
SystemProcessClassificationRegistry, // REDSTONE4
SystemProcessClassificationMaximum
} SYSTEM_PROCESS_CLASSIFICATION;
// private
typedef struct _SYSTEM_PROCESS_INFORMATION_EXTENSION
{
PROCESS_DISK_COUNTERS DiskCounters;
ULONGLONG ContextSwitches;
union
{
ULONG Flags;
struct
{
ULONG HasStrongId : 1;
ULONG Classification : 4; // SYSTEM_PROCESS_CLASSIFICATION
ULONG BackgroundActivityModerated : 1;
ULONG Spare : 26;
};
};
ULONG UserSidOffset;
ULONG PackageFullNameOffset; // since THRESHOLD
PROCESS_ENERGY_VALUES EnergyValues; // since THRESHOLD
ULONG AppIdOffset; // since THRESHOLD
SIZE_T SharedCommitCharge; // since THRESHOLD2
ULONG JobObjectId; // since REDSTONE
ULONG SpareUlong; // since REDSTONE
ULONGLONG ProcessSequenceNumber;
} SYSTEM_PROCESS_INFORMATION_EXTENSION, *PSYSTEM_PROCESS_INFORMATION_EXTENSION;
// private
typedef struct _SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION
{
BOOLEAN EfiLauncherEnabled;
} SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION, *PSYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION;
// private
typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX
{
BOOLEAN DebuggerAllowed;
BOOLEAN DebuggerEnabled;
BOOLEAN DebuggerPresent;
} SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX;
// private
typedef struct _SYSTEM_ELAM_CERTIFICATE_INFORMATION
{
HANDLE ElamDriverFile;
} SYSTEM_ELAM_CERTIFICATE_INFORMATION, *PSYSTEM_ELAM_CERTIFICATE_INFORMATION;
// private
typedef struct _SYSTEM_PROCESSOR_FEATURES_INFORMATION
{
ULONGLONG ProcessorFeatureBits;
ULONGLONG Reserved[3];
} SYSTEM_PROCESSOR_FEATURES_INFORMATION, *PSYSTEM_PROCESSOR_FEATURES_INFORMATION;
// private
typedef struct _SYSTEM_MANUFACTURING_INFORMATION
{
ULONG Options;
UNICODE_STRING ProfileName;
} SYSTEM_MANUFACTURING_INFORMATION, *PSYSTEM_MANUFACTURING_INFORMATION;
// private
typedef struct _SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION
{
BOOLEAN Enabled;
} SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION, *PSYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION;
// private
typedef struct _HV_DETAILS
{
ULONG Data[4];
} HV_DETAILS, *PHV_DETAILS;
// private
typedef struct _SYSTEM_HYPERVISOR_DETAIL_INFORMATION
{
HV_DETAILS HvVendorAndMaxFunction;
HV_DETAILS HypervisorInterface;
HV_DETAILS HypervisorVersion;
HV_DETAILS HvFeatures;
HV_DETAILS HwFeatures;
HV_DETAILS EnlightenmentInfo;
HV_DETAILS ImplementationLimits;
} SYSTEM_HYPERVISOR_DETAIL_INFORMATION, *PSYSTEM_HYPERVISOR_DETAIL_INFORMATION;
// private
typedef struct _SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION
{
ULONGLONG Cycles[4][2];
} SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION, *PSYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION;
// private
typedef struct _SYSTEM_TPM_INFORMATION
{
ULONG Flags;
} SYSTEM_TPM_INFORMATION, *PSYSTEM_TPM_INFORMATION;
// private
typedef struct _SYSTEM_VSM_PROTECTION_INFORMATION
{
BOOLEAN DmaProtectionsAvailable;
BOOLEAN DmaProtectionsInUse;
BOOLEAN HardwareMbecAvailable; // REDSTONE4 (CVE-2018-3639)
} SYSTEM_VSM_PROTECTION_INFORMATION, *PSYSTEM_VSM_PROTECTION_INFORMATION;
// private
typedef struct _SYSTEM_KERNEL_DEBUGGER_FLAGS
{
UCHAR KernelDebuggerIgnoreUmExceptions;
} SYSTEM_KERNEL_DEBUGGER_FLAGS, *PSYSTEM_KERNEL_DEBUGGER_FLAGS;
// private
typedef struct _SYSTEM_CODEINTEGRITYPOLICY_INFORMATION
{
ULONG Options;
ULONG HVCIOptions;
ULONGLONG Version;
GUID PolicyGuid;
} SYSTEM_CODEINTEGRITYPOLICY_INFORMATION, *PSYSTEM_CODEINTEGRITYPOLICY_INFORMATION;
// private
typedef struct _SYSTEM_ISOLATED_USER_MODE_INFORMATION
{
BOOLEAN SecureKernelRunning : 1;
BOOLEAN HvciEnabled : 1;
BOOLEAN HvciStrictMode : 1;
BOOLEAN DebugEnabled : 1;
BOOLEAN FirmwarePageProtection : 1;
BOOLEAN EncryptionKeyAvailable : 1;
BOOLEAN SpareFlags : 2;
BOOLEAN TrustletRunning : 1;
BOOLEAN HvciDisableAllowed : 1;
BOOLEAN SpareFlags2 : 6;
BOOLEAN Spare0[6];
ULONGLONG Spare1;
} SYSTEM_ISOLATED_USER_MODE_INFORMATION, *PSYSTEM_ISOLATED_USER_MODE_INFORMATION;
// private
typedef struct _SYSTEM_SINGLE_MODULE_INFORMATION
{
PVOID TargetModuleAddress;
RTL_PROCESS_MODULE_INFORMATION_EX ExInfo;
} SYSTEM_SINGLE_MODULE_INFORMATION, *PSYSTEM_SINGLE_MODULE_INFORMATION;
// private
typedef struct _SYSTEM_INTERRUPT_CPU_SET_INFORMATION
{
ULONG Gsiv;
USHORT Group;
ULONGLONG CpuSets;
} SYSTEM_INTERRUPT_CPU_SET_INFORMATION, *PSYSTEM_INTERRUPT_CPU_SET_INFORMATION;
// private
typedef struct _SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION
{
SYSTEM_SECUREBOOT_POLICY_INFORMATION PolicyInformation;
ULONG PolicySize;
UCHAR Policy[1];
} SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION, *PSYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION;
// private
typedef struct _SYSTEM_ROOT_SILO_INFORMATION
{
ULONG NumberOfSilos;
ULONG SiloIdList[1];
} SYSTEM_ROOT_SILO_INFORMATION, *PSYSTEM_ROOT_SILO_INFORMATION;
// private
typedef struct _SYSTEM_CPU_SET_TAG_INFORMATION
{
ULONGLONG Tag;
ULONGLONG CpuSets[1];
} SYSTEM_CPU_SET_TAG_INFORMATION, *PSYSTEM_CPU_SET_TAG_INFORMATION;
// private
typedef struct _SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION
{
ULONG ExtentCount;
ULONG ValidStructureSize;
ULONG NextExtentIndex;
ULONG ExtentRestart;
ULONG CycleCount;
ULONG TimeoutCount;
ULONGLONG CycleTime;
ULONGLONG CycleTimeMax;
ULONGLONG ExtentTime;
ULONG ExtentTimeIndex;
ULONG ExtentTimeMaxIndex;
ULONGLONG ExtentTimeMax;
ULONGLONG HyperFlushTimeMax;
ULONGLONG TranslateVaTimeMax;
ULONGLONG DebugExemptionCount;
ULONGLONG TbHitCount;
ULONGLONG TbMissCount;
ULONGLONG VinaPendingYield;
ULONGLONG HashCycles;
ULONG HistogramOffset;
ULONG HistogramBuckets;
ULONG HistogramShift;
ULONG Reserved1;
ULONGLONG PageNotPresentCount;
} SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION, *PSYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION;
// private
typedef struct _SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION
{
ULONG PlatformManifestSize;
UCHAR PlatformManifest[1];
} SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION, *PSYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION;
// private
typedef struct _SYSTEM_MEMORY_USAGE_INFORMATION
{
ULONGLONG TotalPhysicalBytes;
ULONGLONG AvailableBytes;
LONGLONG ResidentAvailableBytes;
ULONGLONG CommittedBytes;
ULONGLONG SharedCommittedBytes;
ULONGLONG CommitLimitBytes;
ULONGLONG PeakCommitmentBytes;
} SYSTEM_MEMORY_USAGE_INFORMATION, *PSYSTEM_MEMORY_USAGE_INFORMATION;
// private
typedef struct _SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION
{
HANDLE ImageFile;
ULONG Type; // REDSTONE4
} SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION, *PSYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION;
// private
typedef struct _SYSTEM_PHYSICAL_MEMORY_INFORMATION
{
ULONGLONG TotalPhysicalBytes;
ULONGLONG LowestPhysicalAddress;
ULONGLONG HighestPhysicalAddress;
} SYSTEM_PHYSICAL_MEMORY_INFORMATION, *PSYSTEM_PHYSICAL_MEMORY_INFORMATION;
// private
typedef enum _SYSTEM_ACTIVITY_MODERATION_STATE
{
SystemActivityModerationStateSystemManaged,
SystemActivityModerationStateUserManagedAllowThrottling,
SystemActivityModerationStateUserManagedDisableThrottling,
MaxSystemActivityModerationState
} SYSTEM_ACTIVITY_MODERATION_STATE;
// private - REDSTONE2
typedef struct _SYSTEM_ACTIVITY_MODERATION_EXE_STATE // REDSTONE3: Renamed SYSTEM_ACTIVITY_MODERATION_INFO
{
UNICODE_STRING ExePathNt;
SYSTEM_ACTIVITY_MODERATION_STATE ModerationState;
} SYSTEM_ACTIVITY_MODERATION_EXE_STATE, *PSYSTEM_ACTIVITY_MODERATION_EXE_STATE;
typedef enum _SYSTEM_ACTIVITY_MODERATION_APP_TYPE
{
SystemActivityModerationAppTypeClassic,
SystemActivityModerationAppTypePackaged,
MaxSystemActivityModerationAppType
} SYSTEM_ACTIVITY_MODERATION_APP_TYPE;
// private - REDSTONE3
typedef struct _SYSTEM_ACTIVITY_MODERATION_INFO
{
UNICODE_STRING Identifier;
SYSTEM_ACTIVITY_MODERATION_STATE ModerationState;
SYSTEM_ACTIVITY_MODERATION_APP_TYPE AppType;
} SYSTEM_ACTIVITY_MODERATION_INFO, *PSYSTEM_ACTIVITY_MODERATION_INFO;
// private
typedef struct _SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS
{
HANDLE UserKeyHandle;
} SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS, *PSYSTEM_ACTIVITY_MODERATION_USER_SETTINGS;
// private
typedef struct _SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION
{
union
{
ULONG Flags;
struct
{
ULONG Locked : 1;
ULONG UnlockApplied : 1; // Unlockable field removed 19H1
ULONG UnlockIdValid : 1;
ULONG Reserved : 29;
};
};
UCHAR UnlockId[32]; // REDSTONE4
} SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION, *PSYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION;
// private
typedef struct _SYSTEM_FLUSH_INFORMATION
{
ULONG SupportedFlushMethods;
ULONG ProcessorCacheFlushSize;
ULONGLONG SystemFlushCapabilities;
ULONGLONG Reserved[2];
} SYSTEM_FLUSH_INFORMATION, *PSYSTEM_FLUSH_INFORMATION;
// private
typedef struct _SYSTEM_WRITE_CONSTRAINT_INFORMATION
{
ULONG WriteConstraintPolicy;
ULONG Reserved;
} SYSTEM_WRITE_CONSTRAINT_INFORMATION, *PSYSTEM_WRITE_CONSTRAINT_INFORMATION;
// private
typedef struct _SYSTEM_KERNEL_VA_SHADOW_INFORMATION
{
union
{
ULONG Flags;
struct
{
ULONG KvaShadowEnabled : 1;
ULONG KvaShadowUserGlobal : 1;
ULONG KvaShadowPcid : 1;
ULONG KvaShadowInvpcid : 1;
ULONG KvaShadowRequired : 1; // REDSTONE4
ULONG KvaShadowRequiredAvailable : 1;
ULONG InvalidPteBit : 6;
ULONG L1DataCacheFlushSupported : 1;
ULONG L1TerminalFaultMitigationPresent : 1;
ULONG Reserved : 18;
};
};
} SYSTEM_KERNEL_VA_SHADOW_INFORMATION, *PSYSTEM_KERNEL_VA_SHADOW_INFORMATION;
// private
typedef struct _SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION
{
HANDLE FileHandle;
ULONG ImageSize;
PVOID Image;
} SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION, *PSYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION;
// private
typedef struct _SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION
{
PVOID HypervisorSharedUserVa;
} SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION, *PSYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION;
// private
typedef struct _SYSTEM_FIRMWARE_PARTITION_INFORMATION
{
UNICODE_STRING FirmwarePartition;
} SYSTEM_FIRMWARE_PARTITION_INFORMATION, *PSYSTEM_FIRMWARE_PARTITION_INFORMATION;
// private
typedef struct _SYSTEM_SPECULATION_CONTROL_INFORMATION
{
union
{
ULONG Flags;
struct
{
ULONG BpbEnabled : 1;
ULONG BpbDisabledSystemPolicy : 1;
ULONG BpbDisabledNoHardwareSupport : 1;
ULONG SpecCtrlEnumerated : 1;
ULONG SpecCmdEnumerated : 1;
ULONG IbrsPresent : 1;
ULONG StibpPresent : 1;
ULONG SmepPresent : 1;
ULONG SpeculativeStoreBypassDisableAvailable : 1; // REDSTONE4 (CVE-2018-3639)
ULONG SpeculativeStoreBypassDisableSupported : 1;
ULONG SpeculativeStoreBypassDisabledSystemWide : 1;
ULONG SpeculativeStoreBypassDisabledKernel : 1;
ULONG SpeculativeStoreBypassDisableRequired : 1;
ULONG BpbDisabledKernelToUser : 1;
ULONG SpecCtrlRetpolineEnabled : 1;
ULONG SpecCtrlImportOptimizationEnabled : 1;
ULONG EnhancedIbrs : 1; // since 19H1
ULONG HvL1tfStatusAvailable : 1;
ULONG HvL1tfProcessorNotAffected : 1;
ULONG HvL1tfMigitationEnabled : 1;
ULONG HvL1tfMigitationNotEnabled_Hardware : 1;
ULONG HvL1tfMigitationNotEnabled_LoadOption : 1;
ULONG HvL1tfMigitationNotEnabled_CoreScheduler : 1;
ULONG EnhancedIbrsReported : 1;
ULONG Reserved : 8;
};
};
} SYSTEM_SPECULATION_CONTROL_INFORMATION, *PSYSTEM_SPECULATION_CONTROL_INFORMATION;
// private
typedef struct _SYSTEM_DMA_GUARD_POLICY_INFORMATION
{
BOOLEAN DmaGuardPolicyEnabled;
} SYSTEM_DMA_GUARD_POLICY_INFORMATION, *PSYSTEM_DMA_GUARD_POLICY_INFORMATION;
// private
typedef struct _SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION
{
UCHAR EnclaveLaunchSigner[32];
} SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION, *PSYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION;
// private
typedef struct _SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION
{
ULONGLONG WorkloadClass;
ULONGLONG CpuSets[1];
} SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION, *PSYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION;
// private
typedef struct _SYSTEM_SECURITY_MODEL_INFORMATION
{
union
{
ULONG SecurityModelFlags;
struct
{
ULONG SModeAdminlessEnabled : 1;
ULONG AllowDeviceOwnerProtectionDowngrade : 1;
ULONG Reserved : 30;
};
};
} SYSTEM_SECURITY_MODEL_INFORMATION, *PSYSTEM_SECURITY_MODEL_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySystemInformation(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
_In_ ULONG SystemInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySystemInformation(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
_In_ ULONG SystemInformationLength,
_Out_opt_ PULONG ReturnLength
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySystemInformationEx(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_In_reads_bytes_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
_In_ ULONG SystemInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySystemInformationEx(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_In_reads_bytes_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
_In_ ULONG SystemInformationLength,
_Out_opt_ PULONG ReturnLength
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSystemInformation(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_In_reads_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
_In_ ULONG SystemInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetSystemInformation(
_In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
_In_reads_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
_In_ ULONG SystemInformationLength
);
// SysDbg APIs
// private
typedef enum _SYSDBG_COMMAND
{
SysDbgQueryModuleInformation,
SysDbgQueryTraceInformation,
SysDbgSetTracepoint,
SysDbgSetSpecialCall,
SysDbgClearSpecialCalls,
SysDbgQuerySpecialCalls,
SysDbgBreakPoint,
SysDbgQueryVersion,
SysDbgReadVirtual,
SysDbgWriteVirtual,
SysDbgReadPhysical,
SysDbgWritePhysical,
SysDbgReadControlSpace,
SysDbgWriteControlSpace,
SysDbgReadIoSpace,
SysDbgWriteIoSpace,
SysDbgReadMsr,
SysDbgWriteMsr,
SysDbgReadBusData,
SysDbgWriteBusData,
SysDbgCheckLowMemory,
SysDbgEnableKernelDebugger,
SysDbgDisableKernelDebugger,
SysDbgGetAutoKdEnable,
SysDbgSetAutoKdEnable,
SysDbgGetPrintBufferSize,
SysDbgSetPrintBufferSize,
SysDbgGetKdUmExceptionEnable,
SysDbgSetKdUmExceptionEnable,
SysDbgGetTriageDump,
SysDbgGetKdBlockEnable,
SysDbgSetKdBlockEnable,
SysDbgRegisterForUmBreakInfo,
SysDbgGetUmBreakPid,
SysDbgClearUmBreakPid,
SysDbgGetUmAttachPid,
SysDbgClearUmAttachPid,
SysDbgGetLiveKernelDump
} SYSDBG_COMMAND, *PSYSDBG_COMMAND;
typedef struct _SYSDBG_VIRTUAL
{
PVOID Address;
PVOID Buffer;
ULONG Request;
} SYSDBG_VIRTUAL, *PSYSDBG_VIRTUAL;
typedef struct _SYSDBG_PHYSICAL
{
PHYSICAL_ADDRESS Address;
PVOID Buffer;
ULONG Request;
} SYSDBG_PHYSICAL, *PSYSDBG_PHYSICAL;
typedef struct _SYSDBG_CONTROL_SPACE
{
ULONG64 Address;
PVOID Buffer;
ULONG Request;
ULONG Processor;
} SYSDBG_CONTROL_SPACE, *PSYSDBG_CONTROL_SPACE;
enum _INTERFACE_TYPE;
typedef struct _SYSDBG_IO_SPACE
{
ULONG64 Address;
PVOID Buffer;
ULONG Request;
enum _INTERFACE_TYPE InterfaceType;
ULONG BusNumber;
ULONG AddressSpace;
} SYSDBG_IO_SPACE, *PSYSDBG_IO_SPACE;
typedef struct _SYSDBG_MSR
{
ULONG Msr;
ULONG64 Data;
} SYSDBG_MSR, *PSYSDBG_MSR;
enum _BUS_DATA_TYPE;
typedef struct _SYSDBG_BUS_DATA
{
ULONG Address;
PVOID Buffer;
ULONG Request;
enum _BUS_DATA_TYPE BusDataType;
ULONG BusNumber;
ULONG SlotNumber;
} SYSDBG_BUS_DATA, *PSYSDBG_BUS_DATA;
// private
typedef struct _SYSDBG_TRIAGE_DUMP
{
ULONG Flags;
ULONG BugCheckCode;
ULONG_PTR BugCheckParam1;
ULONG_PTR BugCheckParam2;
ULONG_PTR BugCheckParam3;
ULONG_PTR BugCheckParam4;
ULONG ProcessHandles;
ULONG ThreadHandles;
PHANDLE Handles;
} SYSDBG_TRIAGE_DUMP, *PSYSDBG_TRIAGE_DUMP;
// private
typedef union _SYSDBG_LIVEDUMP_CONTROL_FLAGS
{
struct
{
ULONG UseDumpStorageStack : 1;
ULONG CompressMemoryPagesData : 1;
ULONG IncludeUserSpaceMemoryPages : 1;
ULONG AbortIfMemoryPressure : 1; // REDSTONE4
ULONG Reserved : 28;
};
ULONG AsUlong;
} SYSDBG_LIVEDUMP_CONTROL_FLAGS, *PSYSDBG_LIVEDUMP_CONTROL_FLAGS;
// private
typedef union _SYSDBG_LIVEDUMP_CONTROL_ADDPAGES
{
struct
{
ULONG HypervisorPages : 1;
ULONG Reserved : 31;
};
ULONG AsUlong;
} SYSDBG_LIVEDUMP_CONTROL_ADDPAGES, *PSYSDBG_LIVEDUMP_CONTROL_ADDPAGES;
#define SYSDBG_LIVEDUMP_CONTROL_VERSION 1
// private
typedef struct _SYSDBG_LIVEDUMP_CONTROL
{
ULONG Version;
ULONG BugCheckCode;
ULONG_PTR BugCheckParam1;
ULONG_PTR BugCheckParam2;
ULONG_PTR BugCheckParam3;
ULONG_PTR BugCheckParam4;
HANDLE DumpFileHandle;
HANDLE CancelEventHandle;
SYSDBG_LIVEDUMP_CONTROL_FLAGS Flags;
SYSDBG_LIVEDUMP_CONTROL_ADDPAGES AddPagesControl;
} SYSDBG_LIVEDUMP_CONTROL, *PSYSDBG_LIVEDUMP_CONTROL;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSystemDebugControl(
_In_ SYSDBG_COMMAND Command,
_Inout_updates_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSystemDebugControl(
_In_ SYSDBG_COMMAND Command,
_Inout_updates_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength,
_Out_opt_ PULONG ReturnLength
);
// Hard errors
typedef enum _HARDERROR_RESPONSE_OPTION
{
OptionAbortRetryIgnore,
OptionOk,
OptionOkCancel,
OptionRetryCancel,
OptionYesNo,
OptionYesNoCancel,
OptionShutdownSystem,
OptionOkNoWait,
OptionCancelTryContinue
} HARDERROR_RESPONSE_OPTION;
typedef enum _HARDERROR_RESPONSE
{
ResponseReturnToCaller,
ResponseNotHandled,
ResponseAbort,
ResponseCancel,
ResponseIgnore,
ResponseNo,
ResponseOk,
ResponseRetry,
ResponseYes,
ResponseTryAgain,
ResponseContinue
} HARDERROR_RESPONSE;
#define HARDERROR_OVERRIDE_ERRORMODE 0x10000000
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRaiseHardError(
_In_ NTSTATUS ErrorStatus,
_In_ ULONG NumberOfParameters,
_In_ ULONG UnicodeStringParameterMask,
_In_reads_(NumberOfParameters) PULONG_PTR Parameters,
_In_ ULONG ValidResponseOptions,
_Out_ PULONG Response
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRaiseHardError(
_In_ NTSTATUS ErrorStatus,
_In_ ULONG NumberOfParameters,
_In_ ULONG UnicodeStringParameterMask,
_In_reads_(NumberOfParameters) PULONG_PTR Parameters,
_In_ ULONG ValidResponseOptions,
_Out_ PULONG Response
);
// Kernel-user shared data
typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE
{
StandardDesign,
NEC98x86,
EndAlternatives
} ALTERNATIVE_ARCHITECTURE_TYPE;
#define PROCESSOR_FEATURE_MAX 64
#define MAX_WOW64_SHARED_ENTRIES 16
#define NX_SUPPORT_POLICY_ALWAYSOFF 0
#define NX_SUPPORT_POLICY_ALWAYSON 1
#define NX_SUPPORT_POLICY_OPTIN 2
#define NX_SUPPORT_POLICY_OPTOUT 3
#include <pshpack4.h>
typedef struct _KUSER_SHARED_DATA
{
ULONG TickCountLowDeprecated;
ULONG TickCountMultiplier;
volatile KSYSTEM_TIME InterruptTime;
volatile KSYSTEM_TIME SystemTime;
volatile KSYSTEM_TIME TimeZoneBias;
USHORT ImageNumberLow;
USHORT ImageNumberHigh;
WCHAR NtSystemRoot[260];
ULONG MaxStackTraceDepth;
ULONG CryptoExponent;
ULONG TimeZoneId;
ULONG LargePageMinimum;
ULONG AitSamplingValue;
ULONG AppCompatFlag;
ULONGLONG RNGSeedVersion;
ULONG GlobalValidationRunlevel;
LONG TimeZoneBiasStamp;
ULONG NtBuildNumber;
NT_PRODUCT_TYPE NtProductType;
BOOLEAN ProductTypeIsValid;
UCHAR Reserved0[1];
USHORT NativeProcessorArchitecture;
ULONG NtMajorVersion;
ULONG NtMinorVersion;
BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX];
ULONG Reserved1;
ULONG Reserved3;
volatile ULONG TimeSlip;
ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture;
ULONG BootId;
LARGE_INTEGER SystemExpirationDate;
ULONG SuiteMask;
BOOLEAN KdDebuggerEnabled;
union
{
UCHAR MitigationPolicies;
struct
{
UCHAR NXSupportPolicy : 2;
UCHAR SEHValidationPolicy : 2;
UCHAR CurDirDevicesSkippedForDlls : 2;
UCHAR Reserved : 2;
};
};
USHORT CyclesPerYield;
volatile ULONG ActiveConsoleId;
volatile ULONG DismountCount;
ULONG ComPlusPackage;
ULONG LastSystemRITEventTickCount;
ULONG NumberOfPhysicalPages;
BOOLEAN SafeBootMode;
UCHAR VirtualizationFlags;
UCHAR Reserved12[2];
union
{
ULONG SharedDataFlags;
struct
{
ULONG DbgErrorPortPresent : 1;
ULONG DbgElevationEnabled : 1;
ULONG DbgVirtEnabled : 1;
ULONG DbgInstallerDetectEnabled : 1;
ULONG DbgLkgEnabled : 1;
ULONG DbgDynProcessorEnabled : 1;
ULONG DbgConsoleBrokerEnabled : 1;
ULONG DbgSecureBootEnabled : 1;
ULONG DbgMultiSessionSku : 1;
ULONG DbgMultiUsersInSessionSku : 1;
ULONG DbgStateSeparationEnabled : 1;
ULONG SpareBits : 21;
};
};
ULONG DataFlagsPad[1];
ULONGLONG TestRetInstruction;
LONGLONG QpcFrequency;
ULONG SystemCall;
ULONG SystemCallPad0;
ULONGLONG SystemCallPad[2];
union
{
volatile KSYSTEM_TIME TickCount;
volatile ULONG64 TickCountQuad;
ULONG ReservedTickCountOverlay[3];
};
ULONG TickCountPad[1];
ULONG Cookie;
ULONG CookiePad[1];
LONGLONG ConsoleSessionForegroundProcessId;
ULONGLONG TimeUpdateLock;
ULONGLONG BaselineSystemTimeQpc;
ULONGLONG BaselineInterruptTimeQpc;
ULONGLONG QpcSystemTimeIncrement;
ULONGLONG QpcInterruptTimeIncrement;
UCHAR QpcSystemTimeIncrementShift;
UCHAR QpcInterruptTimeIncrementShift;
USHORT UnparkedProcessorCount;
ULONG EnclaveFeatureMask[4];
ULONG TelemetryCoverageRound;
USHORT UserModeGlobalLogger[16];
ULONG ImageFileExecutionOptions;
ULONG LangGenerationCount;
ULONGLONG Reserved4;
volatile ULONG64 InterruptTimeBias;
volatile ULONG64 QpcBias;
ULONG ActiveProcessorCount;
volatile UCHAR ActiveGroupCount;
UCHAR Reserved9;
union
{
USHORT QpcData;
struct
{
UCHAR QpcBypassEnabled : 1;
UCHAR QpcShift : 1;
};
};
LARGE_INTEGER TimeZoneBiasEffectiveStart;
LARGE_INTEGER TimeZoneBiasEffectiveEnd;
XSTATE_CONFIGURATION XState;
} KUSER_SHARED_DATA, *PKUSER_SHARED_DATA;
#include <poppack.h>
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountMultiplier) == 0x4);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, InterruptTime) == 0x8);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SystemTime) == 0x14);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtSystemRoot) == 0x30);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, LargePageMinimum) == 0x244);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtProductType) == 0x264);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtMajorVersion) == 0x26c);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtMinorVersion) == 0x270);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ProcessorFeatures) == 0x274);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, KdDebuggerEnabled) == 0x2d4);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveConsoleId) == 0x2d8);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NumberOfPhysicalPages) == 0x2e8);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SafeBootMode) == 0x2ec);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCount) == 0x320);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountQuad) == 0x320);
C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, XState) == 0x3d8);
//C_ASSERT(sizeof(KUSER_SHARED_DATA) == 0x70C); // VS2017 has some weird issue with this.
#define USER_SHARED_DATA ((KUSER_SHARED_DATA * const)0x7ffe0000)
#if (NTDDI_VERSION >= NTDDI_WS03)
FORCEINLINE ULONGLONG NtGetTickCount64()
{
ULARGE_INTEGER tickCount;
#ifdef _WIN64
tickCount.QuadPart = USER_SHARED_DATA->TickCountQuad;
#else
while (TRUE)
{
tickCount.HighPart = (ULONG)USER_SHARED_DATA->TickCount.High1Time;
tickCount.LowPart = USER_SHARED_DATA->TickCount.LowPart;
if (tickCount.HighPart == (ULONG)USER_SHARED_DATA->TickCount.High2Time)
break;
YieldProcessor();
}
#endif
return (UInt32x32To64(tickCount.LowPart, USER_SHARED_DATA->TickCountMultiplier) >> 24) +
(UInt32x32To64(tickCount.HighPart, USER_SHARED_DATA->TickCountMultiplier) << 8);
}
FORCEINLINE ULONG NtGetTickCount()
{
#ifdef _WIN64
return (ULONG)((USER_SHARED_DATA->TickCountQuad * USER_SHARED_DATA->TickCountMultiplier) >> 24);
#else
ULARGE_INTEGER tickCount;
while (TRUE)
{
tickCount.HighPart = (ULONG)USER_SHARED_DATA->TickCount.High1Time;
tickCount.LowPart = USER_SHARED_DATA->TickCount.LowPart;
if (tickCount.HighPart == (ULONG)USER_SHARED_DATA->TickCount.High2Time)
break;
YieldProcessor();
}
return (ULONG)((UInt32x32To64(tickCount.LowPart, USER_SHARED_DATA->TickCountMultiplier) >> 24) +
UInt32x32To64((tickCount.HighPart << 8) & 0xffffffff, USER_SHARED_DATA->TickCountMultiplier));
#endif
}
#endif
// Locale
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDefaultLocale(
_In_ BOOLEAN UserProfile,
_Out_ PLCID DefaultLocaleId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDefaultLocale(
_In_ BOOLEAN UserProfile,
_Out_ PLCID DefaultLocaleId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetDefaultLocale(
_In_ BOOLEAN UserProfile,
_In_ LCID DefaultLocaleId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetDefaultLocale(
_In_ BOOLEAN UserProfile,
_In_ LCID DefaultLocaleId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInstallUILanguage(
_Out_ LANGID *InstallUILanguageId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInstallUILanguage(
_Out_ LANGID *InstallUILanguageId
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFlushInstallUILanguage(
_In_ LANGID InstallUILanguage,
_In_ ULONG SetComittedFlag
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFlushInstallUILanguage(
_In_ LANGID InstallUILanguage,
_In_ ULONG SetComittedFlag
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDefaultUILanguage(
_Out_ LANGID *DefaultUILanguageId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDefaultUILanguage(
_Out_ LANGID *DefaultUILanguageId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetDefaultUILanguage(
_In_ LANGID DefaultUILanguageId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetDefaultUILanguage(
_In_ LANGID DefaultUILanguageId
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtIsUILanguageComitted(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwIsUILanguageComitted(
VOID
);
#endif
// NLS
// begin_private
#if (NTDDI_VERSION >= NTDDI_VISTA)
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtInitializeNlsFiles(
_Out_ PVOID *BaseAddress,
_Out_ PLCID DefaultLocaleId,
_Out_ PLARGE_INTEGER DefaultCasingTableSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwInitializeNlsFiles(
_Out_ PVOID *BaseAddress,
_Out_ PLCID DefaultLocaleId,
_Out_ PLARGE_INTEGER DefaultCasingTableSize
);
#else
NTSYSCALLAPI
NTSTATUS
NTAPI
NtInitializeNlsFiles(
_Out_ PVOID *BaseAddress,
_Out_ PLCID DefaultLocaleId,
_Out_ PLARGE_INTEGER DefaultCasingTableSize,
_Out_opt_ PULONG CurrentNLSVersion
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwInitializeNlsFiles(
_Out_ PVOID *BaseAddress,
_Out_ PLCID DefaultLocaleId,
_Out_ PLARGE_INTEGER DefaultCasingTableSize,
_Out_opt_ PULONG CurrentNLSVersion
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetNlsSectionPtr(
_In_ ULONG SectionType,
_In_ ULONG SectionData,
_In_ PVOID ContextData,
_Out_ PVOID *SectionPointer,
_Out_ PULONG SectionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetNlsSectionPtr(
_In_ ULONG SectionType,
_In_ ULONG SectionData,
_In_ PVOID ContextData,
_Out_ PVOID *SectionPointer,
_Out_ PULONG SectionSize
);
#if (NTDDI_VERSION < NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAcquireCMFViewOwnership(
_Out_ PULONGLONG TimeStamp,
_Out_ PBOOLEAN tokenTaken,
_In_ BOOLEAN replaceExisting
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAcquireCMFViewOwnership(
_Out_ PULONGLONG TimeStamp,
_Out_ PBOOLEAN tokenTaken,
_In_ BOOLEAN replaceExisting
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReleaseCMFViewOwnership(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReleaseCMFViewOwnership(
VOID
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtMapCMFModule(
_In_ ULONG What,
_In_ ULONG Index,
_Out_opt_ PULONG CacheIndexOut,
_Out_opt_ PULONG CacheFlagsOut,
_Out_opt_ PULONG ViewSizeOut,
_Out_opt_ PVOID *BaseAddress
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwMapCMFModule(
_In_ ULONG What,
_In_ ULONG Index,
_Out_opt_ PULONG CacheIndexOut,
_Out_opt_ PULONG CacheFlagsOut,
_Out_opt_ PULONG ViewSizeOut,
_Out_opt_ PVOID *BaseAddress
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetMUIRegistryInfo(
_In_ ULONG Flags,
_Inout_ PULONG DataSize,
_Out_ PVOID Data
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetMUIRegistryInfo(
_In_ ULONG Flags,
_Inout_ PULONG DataSize,
_Out_ PVOID Data
);
#endif
// end_private
// Global atoms
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAddAtom(
_In_reads_bytes_opt_(Length) PWSTR AtomName,
_In_ ULONG Length,
_Out_opt_ PRTL_ATOM Atom
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAddAtom(
_In_reads_bytes_opt_(Length) PWSTR AtomName,
_In_ ULONG Length,
_Out_opt_ PRTL_ATOM Atom
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
#define ATOM_FLAG_GLOBAL 0x2
// rev
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAddAtomEx(
_In_reads_bytes_opt_(Length) PWSTR AtomName,
_In_ ULONG Length,
_Out_opt_ PRTL_ATOM Atom,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAddAtomEx(
_In_reads_bytes_opt_(Length) PWSTR AtomName,
_In_ ULONG Length,
_Out_opt_ PRTL_ATOM Atom,
_In_ ULONG Flags
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFindAtom(
_In_reads_bytes_opt_(Length) PWSTR AtomName,
_In_ ULONG Length,
_Out_opt_ PRTL_ATOM Atom
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFindAtom(
_In_reads_bytes_opt_(Length) PWSTR AtomName,
_In_ ULONG Length,
_Out_opt_ PRTL_ATOM Atom
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteAtom(
_In_ RTL_ATOM Atom
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteAtom(
_In_ RTL_ATOM Atom
);
typedef enum _ATOM_INFORMATION_CLASS
{
AtomBasicInformation,
AtomTableInformation
} ATOM_INFORMATION_CLASS;
typedef struct _ATOM_BASIC_INFORMATION
{
USHORT UsageCount;
USHORT Flags;
USHORT NameLength;
WCHAR Name[1];
} ATOM_BASIC_INFORMATION, *PATOM_BASIC_INFORMATION;
typedef struct _ATOM_TABLE_INFORMATION
{
ULONG NumberOfAtoms;
RTL_ATOM Atoms[1];
} ATOM_TABLE_INFORMATION, *PATOM_TABLE_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationAtom(
_In_ RTL_ATOM Atom,
_In_ ATOM_INFORMATION_CLASS AtomInformationClass,
_Out_writes_bytes_(AtomInformationLength) PVOID AtomInformation,
_In_ ULONG AtomInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationAtom(
_In_ RTL_ATOM Atom,
_In_ ATOM_INFORMATION_CLASS AtomInformationClass,
_Out_writes_bytes_(AtomInformationLength) PVOID AtomInformation,
_In_ ULONG AtomInformationLength,
_Out_opt_ PULONG ReturnLength
);
// Global flags
#define FLG_STOP_ON_EXCEPTION 0x00000001 // uk
#define FLG_SHOW_LDR_SNAPS 0x00000002 // uk
#define FLG_DEBUG_INITIAL_COMMAND 0x00000004 // k
#define FLG_STOP_ON_HUNG_GUI 0x00000008 // k
#define FLG_HEAP_ENABLE_TAIL_CHECK 0x00000010 // u
#define FLG_HEAP_ENABLE_FREE_CHECK 0x00000020 // u
#define FLG_HEAP_VALIDATE_PARAMETERS 0x00000040 // u
#define FLG_HEAP_VALIDATE_ALL 0x00000080 // u
#define FLG_APPLICATION_VERIFIER 0x00000100 // u
#define FLG_POOL_ENABLE_TAGGING 0x00000400 // k
#define FLG_HEAP_ENABLE_TAGGING 0x00000800 // u
#define FLG_USER_STACK_TRACE_DB 0x00001000 // u,32
#define FLG_KERNEL_STACK_TRACE_DB 0x00002000 // k,32
#define FLG_MAINTAIN_OBJECT_TYPELIST 0x00004000 // k
#define FLG_HEAP_ENABLE_TAG_BY_DLL 0x00008000 // u
#define FLG_DISABLE_STACK_EXTENSION 0x00010000 // u
#define FLG_ENABLE_CSRDEBUG 0x00020000 // k
#define FLG_ENABLE_KDEBUG_SYMBOL_LOAD 0x00040000 // k
#define FLG_DISABLE_PAGE_KERNEL_STACKS 0x00080000 // k
#define FLG_ENABLE_SYSTEM_CRIT_BREAKS 0x00100000 // u
#define FLG_HEAP_DISABLE_COALESCING 0x00200000 // u
#define FLG_ENABLE_CLOSE_EXCEPTIONS 0x00400000 // k
#define FLG_ENABLE_EXCEPTION_LOGGING 0x00800000 // k
#define FLG_ENABLE_HANDLE_TYPE_TAGGING 0x01000000 // k
#define FLG_HEAP_PAGE_ALLOCS 0x02000000 // u
#define FLG_DEBUG_INITIAL_COMMAND_EX 0x04000000 // k
#define FLG_DISABLE_DBGPRINT 0x08000000 // k
#define FLG_CRITSEC_EVENT_CREATION 0x10000000 // u
#define FLG_LDR_TOP_DOWN 0x20000000 // u,64
#define FLG_ENABLE_HANDLE_EXCEPTIONS 0x40000000 // k
#define FLG_DISABLE_PROTDLLS 0x80000000 // u
#define FLG_VALID_BITS 0xfffffdff
#define FLG_USERMODE_VALID_BITS (FLG_STOP_ON_EXCEPTION | \
FLG_SHOW_LDR_SNAPS | \
FLG_HEAP_ENABLE_TAIL_CHECK | \
FLG_HEAP_ENABLE_FREE_CHECK | \
FLG_HEAP_VALIDATE_PARAMETERS | \
FLG_HEAP_VALIDATE_ALL | \
FLG_APPLICATION_VERIFIER | \
FLG_HEAP_ENABLE_TAGGING | \
FLG_USER_STACK_TRACE_DB | \
FLG_HEAP_ENABLE_TAG_BY_DLL | \
FLG_DISABLE_STACK_EXTENSION | \
FLG_ENABLE_SYSTEM_CRIT_BREAKS | \
FLG_HEAP_DISABLE_COALESCING | \
FLG_DISABLE_PROTDLLS | \
FLG_HEAP_PAGE_ALLOCS | \
FLG_CRITSEC_EVENT_CREATION | \
FLG_LDR_TOP_DOWN)
#define FLG_BOOTONLY_VALID_BITS (FLG_KERNEL_STACK_TRACE_DB | \
FLG_MAINTAIN_OBJECT_TYPELIST | \
FLG_ENABLE_CSRDEBUG | \
FLG_DEBUG_INITIAL_COMMAND | \
FLG_DEBUG_INITIAL_COMMAND_EX | \
FLG_DISABLE_PAGE_KERNEL_STACKS)
#define FLG_KERNELMODE_VALID_BITS (FLG_STOP_ON_EXCEPTION | \
FLG_SHOW_LDR_SNAPS | \
FLG_STOP_ON_HUNG_GUI | \
FLG_POOL_ENABLE_TAGGING | \
FLG_ENABLE_KDEBUG_SYMBOL_LOAD | \
FLG_ENABLE_CLOSE_EXCEPTIONS | \
FLG_ENABLE_EXCEPTION_LOGGING | \
FLG_ENABLE_HANDLE_TYPE_TAGGING | \
FLG_DISABLE_DBGPRINT | \
FLG_ENABLE_HANDLE_EXCEPTIONS)
// Licensing
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryLicenseValue(
_In_ PUNICODE_STRING ValueName,
_Out_opt_ PULONG Type,
_Out_writes_bytes_to_opt_(DataSize, *ResultDataSize) PVOID Data,
_In_ ULONG DataSize,
_Out_ PULONG ResultDataSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryLicenseValue(
_In_ PUNICODE_STRING ValueName,
_Out_opt_ PULONG Type,
_Out_writes_bytes_to_opt_(DataSize, *ResultDataSize) PVOID Data,
_In_ ULONG DataSize,
_Out_ PULONG ResultDataSize
);
// Misc.
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetDefaultHardErrorPort(
_In_ HANDLE DefaultHardErrorPort
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetDefaultHardErrorPort(
_In_ HANDLE DefaultHardErrorPort
);
typedef enum _SHUTDOWN_ACTION
{
ShutdownNoReboot,
ShutdownReboot,
ShutdownPowerOff
} SHUTDOWN_ACTION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtShutdownSystem(
_In_ SHUTDOWN_ACTION Action
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwShutdownSystem(
_In_ SHUTDOWN_ACTION Action
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDisplayString(
_In_ PUNICODE_STRING String
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDisplayString(
_In_ PUNICODE_STRING String
);
// Boot graphics
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDrawText(
_In_ PUNICODE_STRING Text
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDrawText(
_In_ PUNICODE_STRING Text
);
#endif
// #include <ntgdi.h>
#define GDI_MAX_HANDLE_COUNT 0x4000
#define GDI_HANDLE_INDEX_SHIFT 0
#define GDI_HANDLE_INDEX_BITS 16
#define GDI_HANDLE_INDEX_MASK 0xffff
#define GDI_HANDLE_TYPE_SHIFT 16
#define GDI_HANDLE_TYPE_BITS 5
#define GDI_HANDLE_TYPE_MASK 0x1f
#define GDI_HANDLE_ALTTYPE_SHIFT 21
#define GDI_HANDLE_ALTTYPE_BITS 2
#define GDI_HANDLE_ALTTYPE_MASK 0x3
#define GDI_HANDLE_STOCK_SHIFT 23
#define GDI_HANDLE_STOCK_BITS 1
#define GDI_HANDLE_STOCK_MASK 0x1
#define GDI_HANDLE_UNIQUE_SHIFT 24
#define GDI_HANDLE_UNIQUE_BITS 8
#define GDI_HANDLE_UNIQUE_MASK 0xff
#define GDI_HANDLE_INDEX(Handle) ((ULONG)(Handle) & GDI_HANDLE_INDEX_MASK)
#define GDI_HANDLE_TYPE(Handle) (((ULONG)(Handle) >> GDI_HANDLE_TYPE_SHIFT) & GDI_HANDLE_TYPE_MASK)
#define GDI_HANDLE_ALTTYPE(Handle) (((ULONG)(Handle) >> GDI_HANDLE_ALTTYPE_SHIFT) & GDI_HANDLE_ALTTYPE_MASK)
#define GDI_HANDLE_STOCK(Handle) (((ULONG)(Handle) >> GDI_HANDLE_STOCK_SHIFT)) & GDI_HANDLE_STOCK_MASK)
#define GDI_MAKE_HANDLE(Index, Unique) ((ULONG)(((ULONG)(Unique) << GDI_HANDLE_INDEX_BITS) | (ULONG)(Index)))
// GDI server-side types
#define GDI_DEF_TYPE 0 // invalid handle
#define GDI_DC_TYPE 1
#define GDI_DD_DIRECTDRAW_TYPE 2
#define GDI_DD_SURFACE_TYPE 3
#define GDI_RGN_TYPE 4
#define GDI_SURF_TYPE 5
#define GDI_CLIENTOBJ_TYPE 6
#define GDI_PATH_TYPE 7
#define GDI_PAL_TYPE 8
#define GDI_ICMLCS_TYPE 9
#define GDI_LFONT_TYPE 10
#define GDI_RFONT_TYPE 11
#define GDI_PFE_TYPE 12
#define GDI_PFT_TYPE 13
#define GDI_ICMCXF_TYPE 14
#define GDI_ICMDLL_TYPE 15
#define GDI_BRUSH_TYPE 16
#define GDI_PFF_TYPE 17 // unused
#define GDI_CACHE_TYPE 18 // unused
#define GDI_SPACE_TYPE 19
#define GDI_DBRUSH_TYPE 20 // unused
#define GDI_META_TYPE 21
#define GDI_EFSTATE_TYPE 22
#define GDI_BMFD_TYPE 23 // unused
#define GDI_VTFD_TYPE 24 // unused
#define GDI_TTFD_TYPE 25 // unused
#define GDI_RC_TYPE 26 // unused
#define GDI_TEMP_TYPE 27 // unused
#define GDI_DRVOBJ_TYPE 28
#define GDI_DCIOBJ_TYPE 29 // unused
#define GDI_SPOOL_TYPE 30
// GDI client-side types
#define GDI_CLIENT_TYPE_FROM_HANDLE(Handle) ((ULONG)(Handle) & ((GDI_HANDLE_ALTTYPE_MASK << GDI_HANDLE_ALTTYPE_SHIFT) | \
(GDI_HANDLE_TYPE_MASK << GDI_HANDLE_TYPE_SHIFT)))
#define GDI_CLIENT_TYPE_FROM_UNIQUE(Unique) GDI_CLIENT_TYPE_FROM_HANDLE((ULONG)(Unique) << 16)
#define GDI_ALTTYPE_1 (1 << GDI_HANDLE_ALTTYPE_SHIFT)
#define GDI_ALTTYPE_2 (2 << GDI_HANDLE_ALTTYPE_SHIFT)
#define GDI_ALTTYPE_3 (3 << GDI_HANDLE_ALTTYPE_SHIFT)
#define GDI_CLIENT_BITMAP_TYPE (GDI_SURF_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_BRUSH_TYPE (GDI_BRUSH_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_CLIENTOBJ_TYPE (GDI_CLIENTOBJ_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_DC_TYPE (GDI_DC_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_FONT_TYPE (GDI_LFONT_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_PALETTE_TYPE (GDI_PAL_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_REGION_TYPE (GDI_RGN_TYPE << GDI_HANDLE_TYPE_SHIFT)
#define GDI_CLIENT_ALTDC_TYPE (GDI_CLIENT_DC_TYPE | GDI_ALTTYPE_1)
#define GDI_CLIENT_DIBSECTION_TYPE (GDI_CLIENT_BITMAP_TYPE | GDI_ALTTYPE_1)
#define GDI_CLIENT_EXTPEN_TYPE (GDI_CLIENT_BRUSH_TYPE | GDI_ALTTYPE_2)
#define GDI_CLIENT_METADC16_TYPE (GDI_CLIENT_CLIENTOBJ_TYPE | GDI_ALTTYPE_3)
#define GDI_CLIENT_METAFILE_TYPE (GDI_CLIENT_CLIENTOBJ_TYPE | GDI_ALTTYPE_2)
#define GDI_CLIENT_METAFILE16_TYPE (GDI_CLIENT_CLIENTOBJ_TYPE | GDI_ALTTYPE_1)
#define GDI_CLIENT_PEN_TYPE (GDI_CLIENT_BRUSH_TYPE | GDI_ALTTYPE_1)
typedef struct _GDI_HANDLE_ENTRY
{
union
{
PVOID Object;
PVOID NextFree;
};
union
{
struct
{
USHORT ProcessId;
USHORT Lock : 1;
USHORT Count : 15;
};
ULONG Value;
} Owner;
USHORT Unique;
UCHAR Type;
UCHAR Flags;
PVOID UserPointer;
} GDI_HANDLE_ENTRY, *PGDI_HANDLE_ENTRY;
typedef struct _GDI_SHARED_MEMORY
{
GDI_HANDLE_ENTRY Handles[GDI_MAX_HANDLE_COUNT];
} GDI_SHARED_MEMORY, *PGDI_SHARED_MEMORY;
// #include <ntmmapi.h>
// private
typedef enum _MEMORY_INFORMATION_CLASS
{
MemoryBasicInformation, // MEMORY_BASIC_INFORMATION
MemoryWorkingSetInformation, // MEMORY_WORKING_SET_INFORMATION
MemoryMappedFilenameInformation, // UNICODE_STRING
MemoryRegionInformation, // MEMORY_REGION_INFORMATION
MemoryWorkingSetExInformation, // MEMORY_WORKING_SET_EX_INFORMATION
MemorySharedCommitInformation, // MEMORY_SHARED_COMMIT_INFORMATION
MemoryImageInformation, // MEMORY_IMAGE_INFORMATION
MemoryRegionInformationEx,
MemoryPrivilegedBasicInformation,
MemoryEnclaveImageInformation, // MEMORY_ENCLAVE_IMAGE_INFORMATION // since REDSTONE3
MemoryBasicInformationCapped
} MEMORY_INFORMATION_CLASS;
typedef struct _MEMORY_WORKING_SET_BLOCK
{
ULONG_PTR Protection : 5;
ULONG_PTR ShareCount : 3;
ULONG_PTR Shared : 1;
ULONG_PTR Node : 3;
#ifdef _WIN64
ULONG_PTR VirtualPage : 52;
#else
ULONG VirtualPage : 20;
#endif
} MEMORY_WORKING_SET_BLOCK, *PMEMORY_WORKING_SET_BLOCK;
typedef struct _MEMORY_WORKING_SET_INFORMATION
{
ULONG_PTR NumberOfEntries;
MEMORY_WORKING_SET_BLOCK WorkingSetInfo[1];
} MEMORY_WORKING_SET_INFORMATION, *PMEMORY_WORKING_SET_INFORMATION;
// private
typedef struct _MEMORY_REGION_INFORMATION
{
PVOID AllocationBase;
ULONG AllocationProtect;
union
{
ULONG RegionType;
struct
{
ULONG Private : 1;
ULONG MappedDataFile : 1;
ULONG MappedImage : 1;
ULONG MappedPageFile : 1;
ULONG MappedPhysical : 1;
ULONG DirectMapped : 1;
ULONG SoftwareEnclave : 1; // REDSTONE3
ULONG PageSize64K : 1;
ULONG PlaceholderReservation : 1; // REDSTONE4
ULONG Reserved : 23;
};
};
SIZE_T RegionSize;
SIZE_T CommitSize;
ULONG_PTR PartitionId; // 19H1
} MEMORY_REGION_INFORMATION, *PMEMORY_REGION_INFORMATION;
// private
typedef enum _MEMORY_WORKING_SET_EX_LOCATION
{
MemoryLocationInvalid,
MemoryLocationResident,
MemoryLocationPagefile,
MemoryLocationReserved
} MEMORY_WORKING_SET_EX_LOCATION;
// private
typedef struct _MEMORY_WORKING_SET_EX_BLOCK
{
union
{
struct
{
ULONG_PTR Valid : 1;
ULONG_PTR ShareCount : 3;
ULONG_PTR Win32Protection : 11;
ULONG_PTR Shared : 1;
ULONG_PTR Node : 6;
ULONG_PTR Locked : 1;
ULONG_PTR LargePage : 1;
ULONG_PTR Priority : 3;
ULONG_PTR Reserved : 3;
ULONG_PTR SharedOriginal : 1;
ULONG_PTR Bad : 1;
ULONG_PTR Win32GraphicsProtection : 4; // 19H1
#ifdef _WIN64
ULONG_PTR ReservedUlong : 28;
#endif
};
struct
{
ULONG_PTR Valid : 1;
ULONG_PTR Reserved0 : 14;
ULONG_PTR Shared : 1;
ULONG_PTR Reserved1 : 5;
ULONG_PTR PageTable : 1;
ULONG_PTR Location : 2;
ULONG_PTR Priority : 3;
ULONG_PTR ModifiedList : 1;
ULONG_PTR Reserved2 : 2;
ULONG_PTR SharedOriginal : 1;
ULONG_PTR Bad : 1;
#ifdef _WIN64
ULONG_PTR ReservedUlong : 32;
#endif
} Invalid;
};
} MEMORY_WORKING_SET_EX_BLOCK, *PMEMORY_WORKING_SET_EX_BLOCK;
// private
typedef struct _MEMORY_WORKING_SET_EX_INFORMATION
{
PVOID VirtualAddress;
union
{
MEMORY_WORKING_SET_EX_BLOCK VirtualAttributes;
ULONG_PTR Long;
} u1;
} MEMORY_WORKING_SET_EX_INFORMATION, *PMEMORY_WORKING_SET_EX_INFORMATION;
// private
typedef struct _MEMORY_SHARED_COMMIT_INFORMATION
{
SIZE_T CommitSize;
} MEMORY_SHARED_COMMIT_INFORMATION, *PMEMORY_SHARED_COMMIT_INFORMATION;
// private
typedef struct _MEMORY_IMAGE_INFORMATION
{
PVOID ImageBase;
SIZE_T SizeOfImage;
union
{
ULONG ImageFlags;
struct
{
ULONG ImagePartialMap : 1;
ULONG ImageNotExecutable : 1;
ULONG ImageSigningLevel : 4; // REDSTONE3
ULONG Reserved : 26;
};
};
} MEMORY_IMAGE_INFORMATION, *PMEMORY_IMAGE_INFORMATION;
// private
typedef struct _MEMORY_ENCLAVE_IMAGE_INFORMATION
{
MEMORY_IMAGE_INFORMATION ImageInfo;
UCHAR UniqueID[32];
UCHAR AuthorID[32];
} MEMORY_ENCLAVE_IMAGE_INFORMATION, *PMEMORY_ENCLAVE_IMAGE_INFORMATION;
#define MMPFNLIST_ZERO 0
#define MMPFNLIST_FREE 1
#define MMPFNLIST_STANDBY 2
#define MMPFNLIST_MODIFIED 3
#define MMPFNLIST_MODIFIEDNOWRITE 4
#define MMPFNLIST_BAD 5
#define MMPFNLIST_ACTIVE 6
#define MMPFNLIST_TRANSITION 7
#define MMPFNUSE_PROCESSPRIVATE 0
#define MMPFNUSE_FILE 1
#define MMPFNUSE_PAGEFILEMAPPED 2
#define MMPFNUSE_PAGETABLE 3
#define MMPFNUSE_PAGEDPOOL 4
#define MMPFNUSE_NONPAGEDPOOL 5
#define MMPFNUSE_SYSTEMPTE 6
#define MMPFNUSE_SESSIONPRIVATE 7
#define MMPFNUSE_METAFILE 8
#define MMPFNUSE_AWEPAGE 9
#define MMPFNUSE_DRIVERLOCKPAGE 10
#define MMPFNUSE_KERNELSTACK 11
// private
typedef struct _MEMORY_FRAME_INFORMATION
{
ULONGLONG UseDescription : 4; // MMPFNUSE_*
ULONGLONG ListDescription : 3; // MMPFNLIST_*
ULONGLONG Cold : 1; // 19H1
ULONGLONG Pinned : 1; // 1 - pinned, 0 - not pinned
ULONGLONG DontUse : 48; // *_INFORMATION overlay
ULONGLONG Priority : 3; // rev
ULONGLONG Reserved : 4; // reserved for future expansion
} MEMORY_FRAME_INFORMATION;
// private
typedef struct _FILEOFFSET_INFORMATION
{
ULONGLONG DontUse : 9; // MEMORY_FRAME_INFORMATION overlay
ULONGLONG Offset : 48; // mapped files
ULONGLONG Reserved : 7; // reserved for future expansion
} FILEOFFSET_INFORMATION;
// private
typedef struct _PAGEDIR_INFORMATION
{
ULONGLONG DontUse : 9; // MEMORY_FRAME_INFORMATION overlay
ULONGLONG PageDirectoryBase : 48; // private pages
ULONGLONG Reserved : 7; // reserved for future expansion
} PAGEDIR_INFORMATION;
// private
typedef struct _UNIQUE_PROCESS_INFORMATION
{
ULONGLONG DontUse : 9; // MEMORY_FRAME_INFORMATION overlay
ULONGLONG UniqueProcessKey : 48; // ProcessId
ULONGLONG Reserved : 7; // reserved for future expansion
} UNIQUE_PROCESS_INFORMATION, *PUNIQUE_PROCESS_INFORMATION;
// private
typedef struct _MMPFN_IDENTITY
{
union
{
MEMORY_FRAME_INFORMATION e1; // all
FILEOFFSET_INFORMATION e2; // mapped files
PAGEDIR_INFORMATION e3; // private pages
UNIQUE_PROCESS_INFORMATION e4; // owning process
} u1;
ULONG_PTR PageFrameIndex; // all
union
{
struct
{
ULONG_PTR Image : 1;
ULONG_PTR Mismatch : 1;
} e1;
struct
{
ULONG_PTR CombinedPage;
} e2;
ULONG_PTR FileObject; // mapped files
ULONG_PTR UniqueFileObjectKey;
ULONG_PTR ProtoPteAddress;
ULONG_PTR VirtualAddress; // everything else
} u2;
} MMPFN_IDENTITY, *PMMPFN_IDENTITY;
typedef struct _MMPFN_MEMSNAP_INFORMATION
{
ULONG_PTR InitialPageFrameIndex;
ULONG_PTR Count;
} MMPFN_MEMSNAP_INFORMATION, *PMMPFN_MEMSNAP_INFORMATION;
typedef enum _SECTION_INFORMATION_CLASS
{
SectionBasicInformation, // q; SECTION_BASIC_INFORMATION
SectionImageInformation, // q; SECTION_IMAGE_INFORMATION
SectionRelocationInformation, // name:wow64:whNtQuerySection_SectionRelocationInformation
SectionOriginalBaseInformation, // PVOID BaseAddress
SectionInternalImageInformation, // SECTION_INTERNAL_IMAGE_INFORMATION // since REDSTONE2
MaxSectionInfoClass
} SECTION_INFORMATION_CLASS;
typedef struct _SECTION_BASIC_INFORMATION
{
PVOID BaseAddress;
ULONG AllocationAttributes;
LARGE_INTEGER MaximumSize;
} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;
// symbols
typedef struct _SECTION_IMAGE_INFORMATION
{
PVOID TransferAddress;
ULONG ZeroBits;
SIZE_T MaximumStackSize;
SIZE_T CommittedStackSize;
ULONG SubSystemType;
union
{
struct
{
USHORT SubSystemMinorVersion;
USHORT SubSystemMajorVersion;
};
ULONG SubSystemVersion;
};
union
{
struct
{
USHORT MajorOperatingSystemVersion;
USHORT MinorOperatingSystemVersion;
};
ULONG OperatingSystemVersion;
};
USHORT ImageCharacteristics;
USHORT DllCharacteristics;
USHORT Machine;
BOOLEAN ImageContainsCode;
union
{
UCHAR ImageFlags;
struct
{
UCHAR ComPlusNativeReady : 1;
UCHAR ComPlusILOnly : 1;
UCHAR ImageDynamicallyRelocated : 1;
UCHAR ImageMappedFlat : 1;
UCHAR BaseBelow4gb : 1;
UCHAR ComPlusPrefer32bit : 1;
UCHAR Reserved : 2;
};
};
ULONG LoaderFlags;
ULONG ImageFileSize;
ULONG CheckSum;
} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION;
// symbols
typedef struct _SECTION_INTERNAL_IMAGE_INFORMATION
{
SECTION_IMAGE_INFORMATION SectionInformation;
union
{
ULONG ExtendedFlags;
struct
{
ULONG ImageExportSuppressionEnabled : 1;
ULONG Reserved : 31;
};
};
} SECTION_INTERNAL_IMAGE_INFORMATION, *PSECTION_INTERNAL_IMAGE_INFORMATION;
typedef enum _SECTION_INHERIT
{
ViewShare = 1,
ViewUnmap = 2
} SECTION_INHERIT;
#define SEC_BASED 0x200000
#define SEC_NO_CHANGE 0x400000
#define SEC_GLOBAL 0x20000000
#define MEM_EXECUTE_OPTION_DISABLE 0x1
#define MEM_EXECUTE_OPTION_ENABLE 0x2
#define MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION 0x4
#define MEM_EXECUTE_OPTION_PERMANENT 0x8
#define MEM_EXECUTE_OPTION_EXECUTE_DISPATCH_ENABLE 0x10
#define MEM_EXECUTE_OPTION_IMAGE_DISPATCH_ENABLE 0x20
#define MEM_EXECUTE_OPTION_VALID_FLAGS 0x3f
// Virtual memory
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAllocateVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID *BaseAddress,
_In_ ULONG_PTR ZeroBits,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG AllocationType,
_In_ ULONG Protect
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAllocateVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID *BaseAddress,
_In_ ULONG_PTR ZeroBits,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG AllocationType,
_In_ ULONG Protect
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFreeVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG FreeType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFreeVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG FreeType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReadVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_Out_writes_bytes_(BufferSize) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesRead
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReadVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_Out_writes_bytes_(BufferSize) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesRead
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWriteVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesWritten
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWriteVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesWritten
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtProtectVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG NewProtect,
_Out_ PULONG OldProtect
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwProtectVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG NewProtect,
_Out_ PULONG OldProtect
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ MEMORY_INFORMATION_CLASS MemoryInformationClass,
_Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation,
_In_ SIZE_T MemoryInformationLength,
_Out_opt_ PSIZE_T ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ MEMORY_INFORMATION_CLASS MemoryInformationClass,
_Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation,
_In_ SIZE_T MemoryInformationLength,
_Out_opt_ PSIZE_T ReturnLength
);
// begin_private
typedef enum _VIRTUAL_MEMORY_INFORMATION_CLASS
{
VmPrefetchInformation, // ULONG
VmPagePriorityInformation,
VmCfgCallTargetInformation, // CFG_CALL_TARGET_LIST_INFORMATION // REDSTONE2
VmPageDirtyStateInformation, // REDSTONE3
VmImageHotPatchInformation // 19H1
} VIRTUAL_MEMORY_INFORMATION_CLASS;
typedef struct _MEMORY_RANGE_ENTRY
{
PVOID VirtualAddress;
SIZE_T NumberOfBytes;
} MEMORY_RANGE_ENTRY, *PMEMORY_RANGE_ENTRY;
typedef struct _CFG_CALL_TARGET_LIST_INFORMATION
{
ULONG NumberOfEntries;
ULONG Reserved;
PULONG NumberOfEntriesProcessed;
PCFG_CALL_TARGET_INFO CallTargetInfo;
PVOID Section; // since REDSTONE5
ULONGLONG FileOffset;
} CFG_CALL_TARGET_LIST_INFORMATION, *PCFG_CALL_TARGET_LIST_INFORMATION;
// end_private
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_ VIRTUAL_MEMORY_INFORMATION_CLASS VmInformationClass,
_In_ ULONG_PTR NumberOfEntries,
_In_reads_ (NumberOfEntries) PMEMORY_RANGE_ENTRY VirtualAddresses,
_In_reads_bytes_ (VmInformationLength) PVOID VmInformation,
_In_ ULONG VmInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationVirtualMemory(
_In_ HANDLE ProcessHandle,
_In_ VIRTUAL_MEMORY_INFORMATION_CLASS VmInformationClass,
_In_ ULONG_PTR NumberOfEntries,
_In_reads_ (NumberOfEntries) PMEMORY_RANGE_ENTRY VirtualAddresses,
_In_reads_bytes_ (VmInformationLength) PVOID VmInformation,
_In_ ULONG VmInformationLength
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLockVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG MapType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLockVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG MapType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnlockVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG MapType
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnlockVirtualMemory(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG MapType
);
// Sections
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateSection(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PLARGE_INTEGER MaximumSize,
_In_ ULONG SectionPageProtection,
_In_ ULONG AllocationAttributes,
_In_opt_ HANDLE FileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateSection(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PLARGE_INTEGER MaximumSize,
_In_ ULONG SectionPageProtection,
_In_ ULONG AllocationAttributes,
_In_opt_ HANDLE FileHandle
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS5)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateSectionEx(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PLARGE_INTEGER MaximumSize,
_In_ ULONG SectionPageProtection,
_In_ ULONG AllocationAttributes,
_In_opt_ HANDLE FileHandle,
_In_ PMEM_EXTENDED_PARAMETER ExtendedParameters,
_In_ ULONG ExtendedParameterCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateSectionEx(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PLARGE_INTEGER MaximumSize,
_In_ ULONG SectionPageProtection,
_In_ ULONG AllocationAttributes,
_In_opt_ HANDLE FileHandle,
_In_ PMEM_EXTENDED_PARAMETER ExtendedParameters,
_In_ ULONG ExtendedParameterCount
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenSection(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenSection(
_Out_ PHANDLE SectionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtMapViewOfSection(
_In_ HANDLE SectionHandle,
_In_ HANDLE ProcessHandle,
_Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID *BaseAddress,
_In_ ULONG_PTR ZeroBits,
_In_ SIZE_T CommitSize,
_Inout_opt_ PLARGE_INTEGER SectionOffset,
_Inout_ PSIZE_T ViewSize,
_In_ SECTION_INHERIT InheritDisposition,
_In_ ULONG AllocationType,
_In_ ULONG Win32Protect
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwMapViewOfSection(
_In_ HANDLE SectionHandle,
_In_ HANDLE ProcessHandle,
_Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID *BaseAddress,
_In_ ULONG_PTR ZeroBits,
_In_ SIZE_T CommitSize,
_Inout_opt_ PLARGE_INTEGER SectionOffset,
_Inout_ PSIZE_T ViewSize,
_In_ SECTION_INHERIT InheritDisposition,
_In_ ULONG AllocationType,
_In_ ULONG Win32Protect
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnmapViewOfSection(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnmapViewOfSection(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnmapViewOfSectionEx(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnmapViewOfSectionEx(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ ULONG Flags
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtExtendSection(
_In_ HANDLE SectionHandle,
_Inout_ PLARGE_INTEGER NewSectionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwExtendSection(
_In_ HANDLE SectionHandle,
_Inout_ PLARGE_INTEGER NewSectionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySection(
_In_ HANDLE SectionHandle,
_In_ SECTION_INFORMATION_CLASS SectionInformationClass,
_Out_writes_bytes_(SectionInformationLength) PVOID SectionInformation,
_In_ SIZE_T SectionInformationLength,
_Out_opt_ PSIZE_T ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySection(
_In_ HANDLE SectionHandle,
_In_ SECTION_INFORMATION_CLASS SectionInformationClass,
_Out_writes_bytes_(SectionInformationLength) PVOID SectionInformation,
_In_ SIZE_T SectionInformationLength,
_Out_opt_ PSIZE_T ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAreMappedFilesTheSame(
_In_ PVOID File1MappedAsAnImage,
_In_ PVOID File2MappedAsFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAreMappedFilesTheSame(
_In_ PVOID File1MappedAsAnImage,
_In_ PVOID File2MappedAsFile
);
// Partitions
#ifndef MEMORY_PARTITION_QUERY_ACCESS
#define MEMORY_PARTITION_QUERY_ACCESS 0x0001
#define MEMORY_PARTITION_MODIFY_ACCESS 0x0002
#define MEMORY_PARTITION_ALL_ACCESS \
(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
MEMORY_PARTITION_QUERY_ACCESS | MEMORY_PARTITION_MODIFY_ACCESS)
#endif
// private
typedef enum _MEMORY_PARTITION_INFORMATION_CLASS
{
SystemMemoryPartitionInformation, // q: MEMORY_PARTITION_CONFIGURATION_INFORMATION
SystemMemoryPartitionMoveMemory, // s: MEMORY_PARTITION_TRANSFER_INFORMATION
SystemMemoryPartitionAddPagefile, // s: MEMORY_PARTITION_PAGEFILE_INFORMATION
SystemMemoryPartitionCombineMemory, // q; s: MEMORY_PARTITION_PAGE_COMBINE_INFORMATION
SystemMemoryPartitionInitialAddMemory, // q; s: MEMORY_PARTITION_INITIAL_ADD_INFORMATION
SystemMemoryPartitionGetMemoryEvents, // MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION // since REDSTONE2
SystemMemoryPartitionMax
} MEMORY_PARTITION_INFORMATION_CLASS;
// private
typedef struct _MEMORY_PARTITION_CONFIGURATION_INFORMATION
{
ULONG Flags;
ULONG NumaNode;
ULONG Channel;
ULONG NumberOfNumaNodes;
ULONG_PTR ResidentAvailablePages;
ULONG_PTR CommittedPages;
ULONG_PTR CommitLimit;
ULONG_PTR PeakCommitment;
ULONG_PTR TotalNumberOfPages;
ULONG_PTR AvailablePages;
ULONG_PTR ZeroPages;
ULONG_PTR FreePages;
ULONG_PTR StandbyPages;
ULONG_PTR StandbyPageCountByPriority[8]; // since REDSTONE2
ULONG_PTR RepurposedPagesByPriority[8];
ULONG_PTR MaximumCommitLimit;
ULONG_PTR DonatedPagesToPartitions;
ULONG PartitionId; // since REDSTONE3
} MEMORY_PARTITION_CONFIGURATION_INFORMATION, *PMEMORY_PARTITION_CONFIGURATION_INFORMATION;
// private
typedef struct _MEMORY_PARTITION_TRANSFER_INFORMATION
{
ULONG_PTR NumberOfPages;
ULONG NumaNode;
ULONG Flags;
} MEMORY_PARTITION_TRANSFER_INFORMATION, *PMEMORY_PARTITION_TRANSFER_INFORMATION;
// private
typedef struct _MEMORY_PARTITION_PAGEFILE_INFORMATION
{
UNICODE_STRING PageFileName;
LARGE_INTEGER MinimumSize;
LARGE_INTEGER MaximumSize;
ULONG Flags;
} MEMORY_PARTITION_PAGEFILE_INFORMATION, *PMEMORY_PARTITION_PAGEFILE_INFORMATION;
// private
typedef struct _MEMORY_PARTITION_PAGE_COMBINE_INFORMATION
{
HANDLE StopHandle;
ULONG Flags;
ULONG_PTR TotalNumberOfPages;
} MEMORY_PARTITION_PAGE_COMBINE_INFORMATION, *PMEMORY_PARTITION_PAGE_COMBINE_INFORMATION;
// private
typedef struct _MEMORY_PARTITION_PAGE_RANGE
{
ULONG_PTR StartPage;
ULONG_PTR NumberOfPages;
} MEMORY_PARTITION_PAGE_RANGE, *PMEMORY_PARTITION_PAGE_RANGE;
// private
typedef struct _MEMORY_PARTITION_INITIAL_ADD_INFORMATION
{
ULONG Flags;
ULONG NumberOfRanges;
ULONG_PTR NumberOfPagesAdded;
MEMORY_PARTITION_PAGE_RANGE PartitionRanges[1];
} MEMORY_PARTITION_INITIAL_ADD_INFORMATION, *PMEMORY_PARTITION_INITIAL_ADD_INFORMATION;
// private
typedef struct _MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION
{
union
{
struct
{
ULONG CommitEvents : 1;
ULONG Spare : 31;
};
ULONG AllFlags;
} Flags;
ULONG HandleAttributes;
ULONG DesiredAccess;
HANDLE LowCommitCondition; // \KernelObjects\LowCommitCondition
HANDLE HighCommitCondition; // \KernelObjects\HighCommitCondition
HANDLE MaximumCommitCondition; // \KernelObjects\MaximumCommitCondition
} MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION, *PMEMORY_PARTITION_MEMORY_EVENTS_INFORMATION;
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreatePartition(
_Out_ PHANDLE PartitionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG PreferredNode
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreatePartition(
_Out_ PHANDLE PartitionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG PreferredNode
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenPartition(
_Out_ PHANDLE PartitionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenPartition(
_Out_ PHANDLE PartitionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtManagePartition(
_In_ MEMORY_PARTITION_INFORMATION_CLASS PartitionInformationClass,
_In_ PVOID PartitionInformation,
_In_ ULONG PartitionInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwManagePartition(
_In_ MEMORY_PARTITION_INFORMATION_CLASS PartitionInformationClass,
_In_ PVOID PartitionInformation,
_In_ ULONG PartitionInformationLength
);
#endif
// User physical pages
NTSYSCALLAPI
NTSTATUS
NTAPI
NtMapUserPhysicalPages(
_In_ PVOID VirtualAddress,
_In_ ULONG_PTR NumberOfPages,
_In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwMapUserPhysicalPages(
_In_ PVOID VirtualAddress,
_In_ ULONG_PTR NumberOfPages,
_In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtMapUserPhysicalPagesScatter(
_In_reads_(NumberOfPages) PVOID *VirtualAddresses,
_In_ ULONG_PTR NumberOfPages,
_In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwMapUserPhysicalPagesScatter(
_In_reads_(NumberOfPages) PVOID *VirtualAddresses,
_In_ ULONG_PTR NumberOfPages,
_In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAllocateUserPhysicalPages(
_In_ HANDLE ProcessHandle,
_Inout_ PULONG_PTR NumberOfPages,
_Out_writes_(*NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAllocateUserPhysicalPages(
_In_ HANDLE ProcessHandle,
_Inout_ PULONG_PTR NumberOfPages,
_Out_writes_(*NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFreeUserPhysicalPages(
_In_ HANDLE ProcessHandle,
_Inout_ PULONG_PTR NumberOfPages,
_In_reads_(*NumberOfPages) PULONG_PTR UserPfnArray
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFreeUserPhysicalPages(
_In_ HANDLE ProcessHandle,
_Inout_ PULONG_PTR NumberOfPages,
_In_reads_(*NumberOfPages) PULONG_PTR UserPfnArray
);
// Sessions
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenSession(
_Out_ PHANDLE SessionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenSession(
_Out_ PHANDLE SessionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
#endif
// Misc.
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetWriteWatch(
_In_ HANDLE ProcessHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress,
_In_ SIZE_T RegionSize,
_Out_writes_(*EntriesInUserAddressArray) PVOID *UserAddressArray,
_Inout_ PULONG_PTR EntriesInUserAddressArray,
_Out_ PULONG Granularity
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetWriteWatch(
_In_ HANDLE ProcessHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress,
_In_ SIZE_T RegionSize,
_Out_writes_(*EntriesInUserAddressArray) PVOID *UserAddressArray,
_Inout_ PULONG_PTR EntriesInUserAddressArray,
_Out_ PULONG Granularity
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtResetWriteWatch(
_In_ HANDLE ProcessHandle,
_In_ PVOID BaseAddress,
_In_ SIZE_T RegionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwResetWriteWatch(
_In_ HANDLE ProcessHandle,
_In_ PVOID BaseAddress,
_In_ SIZE_T RegionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreatePagingFile(
_In_ PUNICODE_STRING PageFileName,
_In_ PLARGE_INTEGER MinimumSize,
_In_ PLARGE_INTEGER MaximumSize,
_In_ ULONG Priority
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreatePagingFile(
_In_ PUNICODE_STRING PageFileName,
_In_ PLARGE_INTEGER MinimumSize,
_In_ PLARGE_INTEGER MaximumSize,
_In_ ULONG Priority
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFlushInstructionCache(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ SIZE_T Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFlushInstructionCache(
_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress,
_In_ SIZE_T Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFlushWriteBuffer(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFlushWriteBuffer(
VOID
);
// #include <ntobapi.h>
#define OBJECT_TYPE_CREATE 0x0001
#define OBJECT_TYPE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1)
#define DIRECTORY_QUERY 0x0001
#define DIRECTORY_TRAVERSE 0x0002
#define DIRECTORY_CREATE_OBJECT 0x0004
#define DIRECTORY_CREATE_SUBDIRECTORY 0x0008
#define DIRECTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0xf)
#define SYMBOLIC_LINK_QUERY 0x0001
#define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1)
#define OBJ_PROTECT_CLOSE 0x00000001
#ifndef OBJ_INHERIT
#define OBJ_INHERIT 0x00000002
#endif
#define OBJ_AUDIT_OBJECT_CLOSE 0x00000004
typedef enum _OBJECT_INFORMATION_CLASS
{
ObjectBasicInformation, // OBJECT_BASIC_INFORMATION
ObjectNameInformation, // OBJECT_NAME_INFORMATION
ObjectTypeInformation, // OBJECT_TYPE_INFORMATION
ObjectTypesInformation, // OBJECT_TYPES_INFORMATION
ObjectHandleFlagInformation, // OBJECT_HANDLE_FLAG_INFORMATION
ObjectSessionInformation,
ObjectSessionObjectInformation,
MaxObjectInfoClass
} OBJECT_INFORMATION_CLASS;
typedef struct _OBJECT_BASIC_INFORMATION
{
ULONG Attributes;
ACCESS_MASK GrantedAccess;
ULONG HandleCount;
ULONG PointerCount;
ULONG PagedPoolCharge;
ULONG NonPagedPoolCharge;
ULONG Reserved[3];
ULONG NameInfoSize;
ULONG TypeInfoSize;
ULONG SecurityDescriptorSize;
LARGE_INTEGER CreationTime;
} OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;
typedef struct _OBJECT_NAME_INFORMATION
{
UNICODE_STRING Name;
} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION;
typedef struct _OBJECT_TYPE_INFORMATION
{
UNICODE_STRING TypeName;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG TotalPagedPoolUsage;
ULONG TotalNonPagedPoolUsage;
ULONG TotalNamePoolUsage;
ULONG TotalHandleTableUsage;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
ULONG HighWaterPagedPoolUsage;
ULONG HighWaterNonPagedPoolUsage;
ULONG HighWaterNamePoolUsage;
ULONG HighWaterHandleTableUsage;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
UCHAR TypeIndex; // since WINBLUE
CHAR ReservedByte;
ULONG PoolType;
ULONG DefaultPagedPoolCharge;
ULONG DefaultNonPagedPoolCharge;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
typedef struct _OBJECT_TYPES_INFORMATION
{
ULONG NumberOfTypes;
} OBJECT_TYPES_INFORMATION, *POBJECT_TYPES_INFORMATION;
typedef struct _OBJECT_HANDLE_FLAG_INFORMATION
{
BOOLEAN Inherit;
BOOLEAN ProtectFromClose;
} OBJECT_HANDLE_FLAG_INFORMATION, *POBJECT_HANDLE_FLAG_INFORMATION;
// Objects, handles
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryObject(
_In_opt_ HANDLE Handle,
_In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
_Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation,
_In_ ULONG ObjectInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryObject(
_In_opt_ HANDLE Handle,
_In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
_Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation,
_In_ ULONG ObjectInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationObject(
_In_ HANDLE Handle,
_In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
_In_reads_bytes_(ObjectInformationLength) PVOID ObjectInformation,
_In_ ULONG ObjectInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationObject(
_In_ HANDLE Handle,
_In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
_In_reads_bytes_(ObjectInformationLength) PVOID ObjectInformation,
_In_ ULONG ObjectInformationLength
);
#define DUPLICATE_CLOSE_SOURCE 0x00000001
#define DUPLICATE_SAME_ACCESS 0x00000002
#define DUPLICATE_SAME_ATTRIBUTES 0x00000004
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDuplicateObject(
_In_ HANDLE SourceProcessHandle,
_In_ HANDLE SourceHandle,
_In_opt_ HANDLE TargetProcessHandle,
_Out_opt_ PHANDLE TargetHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_In_ ULONG Options
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDuplicateObject(
_In_ HANDLE SourceProcessHandle,
_In_ HANDLE SourceHandle,
_In_opt_ HANDLE TargetProcessHandle,
_Out_opt_ PHANDLE TargetHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_In_ ULONG Options
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtMakeTemporaryObject(
_In_ HANDLE Handle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwMakeTemporaryObject(
_In_ HANDLE Handle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtMakePermanentObject(
_In_ HANDLE Handle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwMakePermanentObject(
_In_ HANDLE Handle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSignalAndWaitForSingleObject(
_In_ HANDLE SignalHandle,
_In_ HANDLE WaitHandle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSignalAndWaitForSingleObject(
_In_ HANDLE SignalHandle,
_In_ HANDLE WaitHandle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForSingleObject(
_In_ HANDLE Handle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForSingleObject(
_In_ HANDLE Handle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForMultipleObjects(
_In_ ULONG Count,
_In_reads_(Count) HANDLE Handles[],
_In_ WAIT_TYPE WaitType,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForMultipleObjects(
_In_ ULONG Count,
_In_reads_(Count) HANDLE Handles[],
_In_ WAIT_TYPE WaitType,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForMultipleObjects32(
_In_ ULONG Count,
_In_reads_(Count) LONG Handles[],
_In_ WAIT_TYPE WaitType,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForMultipleObjects32(
_In_ ULONG Count,
_In_reads_(Count) LONG Handles[],
_In_ WAIT_TYPE WaitType,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSecurityObject(
_In_ HANDLE Handle,
_In_ SECURITY_INFORMATION SecurityInformation,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetSecurityObject(
_In_ HANDLE Handle,
_In_ SECURITY_INFORMATION SecurityInformation,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySecurityObject(
_In_ HANDLE Handle,
_In_ SECURITY_INFORMATION SecurityInformation,
_Out_writes_bytes_opt_(Length) PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ ULONG Length,
_Out_ PULONG LengthNeeded
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySecurityObject(
_In_ HANDLE Handle,
_In_ SECURITY_INFORMATION SecurityInformation,
_Out_writes_bytes_opt_(Length) PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ ULONG Length,
_Out_ PULONG LengthNeeded
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtClose(
_In_ HANDLE Handle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwClose(
_In_ HANDLE Handle
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCompareObjects(
_In_ HANDLE FirstObjectHandle,
_In_ HANDLE SecondObjectHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCompareObjects(
_In_ HANDLE FirstObjectHandle,
_In_ HANDLE SecondObjectHandle
);
#endif
// Directory objects
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateDirectoryObject(
_Out_ PHANDLE DirectoryHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateDirectoryObject(
_Out_ PHANDLE DirectoryHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateDirectoryObjectEx(
_Out_ PHANDLE DirectoryHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ShadowDirectoryHandle,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateDirectoryObjectEx(
_Out_ PHANDLE DirectoryHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ShadowDirectoryHandle,
_In_ ULONG Flags
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenDirectoryObject(
_Out_ PHANDLE DirectoryHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenDirectoryObject(
_Out_ PHANDLE DirectoryHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
typedef struct _OBJECT_DIRECTORY_INFORMATION
{
UNICODE_STRING Name;
UNICODE_STRING TypeName;
} OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDirectoryObject(
_In_ HANDLE DirectoryHandle,
_Out_writes_bytes_opt_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ BOOLEAN ReturnSingleEntry,
_In_ BOOLEAN RestartScan,
_Inout_ PULONG Context,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDirectoryObject(
_In_ HANDLE DirectoryHandle,
_Out_writes_bytes_opt_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ BOOLEAN ReturnSingleEntry,
_In_ BOOLEAN RestartScan,
_Inout_ PULONG Context,
_Out_opt_ PULONG ReturnLength
);
// Private namespaces
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreatePrivateNamespace(
_Out_ PHANDLE NamespaceHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PVOID BoundaryDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreatePrivateNamespace(
_Out_ PHANDLE NamespaceHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PVOID BoundaryDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenPrivateNamespace(
_Out_ PHANDLE NamespaceHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PVOID BoundaryDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenPrivateNamespace(
_Out_ PHANDLE NamespaceHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PVOID BoundaryDescriptor
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeletePrivateNamespace(
_In_ HANDLE NamespaceHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeletePrivateNamespace(
_In_ HANDLE NamespaceHandle
);
#endif
// Symbolic links
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateSymbolicLinkObject(
_Out_ PHANDLE LinkHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PUNICODE_STRING LinkTarget
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateSymbolicLinkObject(
_Out_ PHANDLE LinkHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PUNICODE_STRING LinkTarget
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenSymbolicLinkObject(
_Out_ PHANDLE LinkHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenSymbolicLinkObject(
_Out_ PHANDLE LinkHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySymbolicLinkObject(
_In_ HANDLE LinkHandle,
_Inout_ PUNICODE_STRING LinkTarget,
_Out_opt_ PULONG ReturnedLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySymbolicLinkObject(
_In_ HANDLE LinkHandle,
_Inout_ PUNICODE_STRING LinkTarget,
_Out_opt_ PULONG ReturnedLength
);
// #include <ntpsapi.h>
#ifndef PROCESS_SET_PORT
#define PROCESS_SET_PORT 0x0800
#endif
#ifndef THREAD_ALERT
#define THREAD_ALERT 0x0004
#endif
#define GDI_HANDLE_BUFFER_SIZE32 34
#define GDI_HANDLE_BUFFER_SIZE64 60
#ifndef _WIN64
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32
#else
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE64
#endif
typedef ULONG GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE];
typedef ULONG GDI_HANDLE_BUFFER32[GDI_HANDLE_BUFFER_SIZE32];
typedef ULONG GDI_HANDLE_BUFFER64[GDI_HANDLE_BUFFER_SIZE64];
//#define FLS_MAXIMUM_AVAILABLE 128
#define TLS_MINIMUM_AVAILABLE 64
#define TLS_EXPANSION_SLOTS 1024
// symbols
typedef struct _PEB_LDR_DATA
{
ULONG Length;
BOOLEAN Initialized;
HANDLE SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
BOOLEAN ShutdownInProgress;
HANDLE ShutdownThreadId;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _INITIAL_TEB
{
struct
{
PVOID OldStackBase;
PVOID OldStackLimit;
} OldInitialTeb;
PVOID StackBase;
PVOID StackLimit;
PVOID StackAllocationBase;
} INITIAL_TEB, *PINITIAL_TEB;
typedef struct _WOW64_PROCESS
{
PVOID Wow64;
} WOW64_PROCESS, *PWOW64_PROCESS;
// #include <ntpebteb.h>
typedef struct _RTL_USER_PROCESS_PARAMETERS *PRTL_USER_PROCESS_PARAMETERS;
typedef struct _RTL_CRITICAL_SECTION *PRTL_CRITICAL_SECTION;
// private
typedef struct _ACTIVATION_CONTEXT_STACK
{
struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME* ActiveFrame;
LIST_ENTRY FrameListCache;
ULONG Flags;
ULONG NextCookieSequenceNumber;
ULONG StackId;
} ACTIVATION_CONTEXT_STACK, *PACTIVATION_CONTEXT_STACK;
// private
typedef struct _API_SET_NAMESPACE
{
ULONG Version;
ULONG Size;
ULONG Flags;
ULONG Count;
ULONG EntryOffset;
ULONG HashOffset;
ULONG HashFactor;
} API_SET_NAMESPACE, *PAPI_SET_NAMESPACE;
// private
typedef struct _API_SET_HASH_ENTRY
{
ULONG Hash;
ULONG Index;
} API_SET_HASH_ENTRY, *PAPI_SET_HASH_ENTRY;
// private
typedef struct _API_SET_NAMESPACE_ENTRY
{
ULONG Flags;
ULONG NameOffset;
ULONG NameLength;
ULONG HashedLength;
ULONG ValueOffset;
ULONG ValueCount;
} API_SET_NAMESPACE_ENTRY, *PAPI_SET_NAMESPACE_ENTRY;
// private
typedef struct _API_SET_VALUE_ENTRY
{
ULONG Flags;
ULONG NameOffset;
ULONG NameLength;
ULONG ValueOffset;
ULONG ValueLength;
} API_SET_VALUE_ENTRY, *PAPI_SET_VALUE_ENTRY;
// symbols
typedef struct _PEB
{
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
union
{
BOOLEAN BitField;
struct
{
BOOLEAN ImageUsesLargePages : 1;
BOOLEAN IsProtectedProcess : 1;
BOOLEAN IsImageDynamicallyRelocated : 1;
BOOLEAN SkipPatchingUser32Forwarders : 1;
BOOLEAN IsPackagedProcess : 1;
BOOLEAN IsAppContainer : 1;
BOOLEAN IsProtectedProcessLight : 1;
BOOLEAN IsLongPathAwareProcess : 1;
};
};
HANDLE Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA Ldr;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
PRTL_CRITICAL_SECTION FastPebLock;
PVOID IFEOKey;
PSLIST_HEADER AtlThunkSListPtr;
union
{
ULONG CrossProcessFlags;
struct
{
ULONG ProcessInJob : 1;
ULONG ProcessInitializing : 1;
ULONG ProcessUsingVEH : 1;
ULONG ProcessUsingVCH : 1;
ULONG ProcessUsingFTH : 1;
ULONG ProcessPreviouslyThrottled : 1;
ULONG ProcessCurrentlyThrottled : 1;
ULONG ProcessImagesHotPatched : 1; // REDSTONE5
ULONG ReservedBits0 : 24;
};
};
union
{
PVOID KernelCallbackTable;
PVOID UserSharedInfoPtr;
};
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
PAPI_SET_NAMESPACE ApiSetMap;
ULONG TlsExpansionCounter;
PVOID TlsBitmap;
ULONG TlsBitmapBits[2];
PVOID ReadOnlySharedMemoryBase;
PVOID SharedData; // HotpatchInformation
PVOID *ReadOnlyStaticServerData;
PVOID AnsiCodePageData; // PCPTABLEINFO
PVOID OemCodePageData; // PCPTABLEINFO
PVOID UnicodeCaseTableData; // PNLSTABLEINFO
ULONG NumberOfProcessors;
ULONG NtGlobalFlag;
ULARGE_INTEGER CriticalSectionTimeout;
SIZE_T HeapSegmentReserve;
SIZE_T HeapSegmentCommit;
SIZE_T HeapDeCommitTotalFreeThreshold;
SIZE_T HeapDeCommitFreeBlockThreshold;
ULONG NumberOfHeaps;
ULONG MaximumNumberOfHeaps;
PVOID *ProcessHeaps; // PHEAP
PVOID GdiSharedHandleTable;
PVOID ProcessStarterHelper;
ULONG GdiDCAttributeList;
PRTL_CRITICAL_SECTION LoaderLock;
ULONG OSMajorVersion;
ULONG OSMinorVersion;
USHORT OSBuildNumber;
USHORT OSCSDVersion;
ULONG OSPlatformId;
ULONG ImageSubsystem;
ULONG ImageSubsystemMajorVersion;
ULONG ImageSubsystemMinorVersion;
ULONG_PTR ActiveProcessAffinityMask;
GDI_HANDLE_BUFFER GdiHandleBuffer;
PVOID PostProcessInitRoutine;
PVOID TlsExpansionBitmap;
ULONG TlsExpansionBitmapBits[32];
ULONG SessionId;
ULARGE_INTEGER AppCompatFlags;
ULARGE_INTEGER AppCompatFlagsUser;
PVOID pShimData;
PVOID AppCompatInfo; // APPCOMPAT_EXE_DATA
UNICODE_STRING CSDVersion;
PVOID ActivationContextData; // ACTIVATION_CONTEXT_DATA
PVOID ProcessAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP
PVOID SystemDefaultActivationContextData; // ACTIVATION_CONTEXT_DATA
PVOID SystemAssemblyStorageMap; // ASSEMBLY_STORAGE_MAP
SIZE_T MinimumStackCommit;
PVOID SparePointers[4]; // 19H1 (previously FlsCallback to FlsHighIndex)
ULONG SpareUlongs[5]; // 19H1
//PVOID* FlsCallback;
//LIST_ENTRY FlsListHead;
//PVOID FlsBitmap;
//ULONG FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(ULONG) * 8)];
//ULONG FlsHighIndex;
PVOID WerRegistrationData;
PVOID WerShipAssertPtr;
PVOID pUnused; // pContextData
PVOID pImageHeaderHash;
union
{
ULONG TracingFlags;
struct
{
ULONG HeapTracingEnabled : 1;
ULONG CritSecTracingEnabled : 1;
ULONG LibLoaderTracingEnabled : 1;
ULONG SpareTracingBits : 29;
};
};
ULONGLONG CsrServerReadOnlySharedMemoryBase;
PRTL_CRITICAL_SECTION TppWorkerpListLock;
LIST_ENTRY TppWorkerpList;
PVOID WaitOnAddressHashTable[128];
PVOID TelemetryCoverageHeader; // REDSTONE3
ULONG CloudFileFlags;
ULONG CloudFileDiagFlags; // REDSTONE4
CHAR PlaceholderCompatibilityMode;
CHAR PlaceholderCompatibilityModeReserved[7];
struct _LEAP_SECOND_DATA *LeapSecondData; // REDSTONE5
union
{
ULONG LeapSecondFlags;
struct
{
ULONG SixtySecondEnabled : 1;
ULONG Reserved : 31;
};
};
ULONG NtGlobalFlag2;
} PEB, *PPEB;
#ifdef _WIN64
C_ASSERT(FIELD_OFFSET(PEB, SessionId) == 0x2C0);
//C_ASSERT(sizeof(PEB) == 0x7B0); // REDSTONE3
//C_ASSERT(sizeof(PEB) == 0x7B8); // REDSTONE4
C_ASSERT(sizeof(PEB) == 0x7C8); // REDSTONE5 // 19H1
#else
C_ASSERT(FIELD_OFFSET(PEB, SessionId) == 0x1D4);
//C_ASSERT(sizeof(PEB) == 0x468); // REDSTONE3
//C_ASSERT(sizeof(PEB) == 0x470); // REDSTONE4
C_ASSERT(sizeof(PEB) == 0x480); // REDSTONE5 // 19H1
#endif
#define GDI_BATCH_BUFFER_SIZE 310
typedef struct _GDI_TEB_BATCH
{
ULONG Offset;
ULONG_PTR HDC;
ULONG Buffer[GDI_BATCH_BUFFER_SIZE];
} GDI_TEB_BATCH, *PGDI_TEB_BATCH;
typedef struct _TEB_ACTIVE_FRAME_CONTEXT
{
ULONG Flags;
PSTR FrameName;
} TEB_ACTIVE_FRAME_CONTEXT, *PTEB_ACTIVE_FRAME_CONTEXT;
typedef struct _TEB_ACTIVE_FRAME
{
ULONG Flags;
struct _TEB_ACTIVE_FRAME *Previous;
PTEB_ACTIVE_FRAME_CONTEXT Context;
} TEB_ACTIVE_FRAME, *PTEB_ACTIVE_FRAME;
struct _TEB
{
NT_TIB NtTib;
PVOID EnvironmentPointer;
CLIENT_ID ClientId;
PVOID ActiveRpcHandle;
PVOID ThreadLocalStoragePointer;
PPEB ProcessEnvironmentBlock;
ULONG LastErrorValue;
ULONG CountOfOwnedCriticalSections;
PVOID CsrClientThread;
PVOID Win32ThreadInfo;
ULONG User32Reserved[26];
ULONG UserReserved[5];
PVOID WOW32Reserved;
LCID CurrentLocale;
ULONG FpSoftwareStatusRegister;
PVOID ReservedForDebuggerInstrumentation[16];
#ifdef _WIN64
PVOID SystemReserved1[30];
#else
PVOID SystemReserved1[26];
#endif
CHAR PlaceholderCompatibilityMode;
CHAR PlaceholderReserved[11];
ULONG ProxiedProcessId;
ACTIVATION_CONTEXT_STACK ActivationStack;
UCHAR WorkingOnBehalfTicket[8];
NTSTATUS ExceptionCode;
PACTIVATION_CONTEXT_STACK ActivationContextStackPointer;
ULONG_PTR InstrumentationCallbackSp;
ULONG_PTR InstrumentationCallbackPreviousPc;
ULONG_PTR InstrumentationCallbackPreviousSp;
#ifdef _WIN64
ULONG TxFsContext;
#endif
BOOLEAN InstrumentationCallbackDisabled;
#ifndef _WIN64
UCHAR SpareBytes[23];
ULONG TxFsContext;
#endif
GDI_TEB_BATCH GdiTebBatch;
CLIENT_ID RealClientId;
HANDLE GdiCachedProcessHandle;
ULONG GdiClientPID;
ULONG GdiClientTID;
PVOID GdiThreadLocalInfo;
ULONG_PTR Win32ClientInfo[62];
PVOID glDispatchTable[233];
ULONG_PTR glReserved1[29];
PVOID glReserved2;
PVOID glSectionInfo;
PVOID glSection;
PVOID glTable;
PVOID glCurrentRC;
PVOID glContext;
NTSTATUS LastStatusValue;
UNICODE_STRING StaticUnicodeString;
WCHAR StaticUnicodeBuffer[261];
PVOID DeallocationStack;
PVOID TlsSlots[64];
LIST_ENTRY TlsLinks;
PVOID Vdm;
PVOID ReservedForNtRpc;
PVOID DbgSsReserved[2];
ULONG HardErrorMode;
#ifdef _WIN64
PVOID Instrumentation[11];
#else
PVOID Instrumentation[9];
#endif
GUID ActivityId;
PVOID SubProcessTag;
PVOID PerflibData;
PVOID EtwTraceData;
PVOID WinSockData;
ULONG GdiBatchCount;
union
{
PROCESSOR_NUMBER CurrentIdealProcessor;
ULONG IdealProcessorValue;
struct
{
UCHAR ReservedPad0;
UCHAR ReservedPad1;
UCHAR ReservedPad2;
UCHAR IdealProcessor;
};
};
ULONG GuaranteedStackBytes;
PVOID ReservedForPerf;
PVOID ReservedForOle;
ULONG WaitingOnLoaderLock;
PVOID SavedPriorityState;
ULONG_PTR ReservedForCodeCoverage;
PVOID ThreadPoolData;
PVOID *TlsExpansionSlots;
#ifdef _WIN64
PVOID DeallocationBStore;
PVOID BStoreLimit;
#endif
ULONG MuiGeneration;
ULONG IsImpersonating;
PVOID NlsCache;
PVOID pShimData;
USHORT HeapVirtualAffinity;
USHORT LowFragHeapDataSlot;
HANDLE CurrentTransactionHandle;
PTEB_ACTIVE_FRAME ActiveFrame;
PVOID FlsData;
PVOID PreferredLanguages;
PVOID UserPrefLanguages;
PVOID MergedPrefLanguages;
ULONG MuiImpersonation;
union
{
USHORT CrossTebFlags;
USHORT SpareCrossTebBits : 16;
};
union
{
USHORT SameTebFlags;
struct
{
USHORT SafeThunkCall : 1;
USHORT InDebugPrint : 1;
USHORT HasFiberData : 1;
USHORT SkipThreadAttach : 1;
USHORT WerInShipAssertCode : 1;
USHORT RanProcessInit : 1;
USHORT ClonedThread : 1;
USHORT SuppressDebugMsg : 1;
USHORT DisableUserStackWalk : 1;
USHORT RtlExceptionAttached : 1;
USHORT InitialThread : 1;
USHORT SessionAware : 1;
USHORT LoadOwner : 1;
USHORT LoaderWorker : 1;
USHORT SkipLoaderInit : 1;
USHORT SpareSameTebBits : 1;
};
};
PVOID TxnScopeEnterCallback;
PVOID TxnScopeExitCallback;
PVOID TxnScopeContext;
ULONG LockCount;
LONG WowTebOffset;
PVOID ResourceRetValue;
PVOID ReservedForWdf;
ULONGLONG ReservedForCrt;
GUID EffectiveContainerId;
};
// source:http://www.microsoft.com/whdc/system/Sysinternals/MoreThan64proc.mspx
typedef enum _PROCESSINFOCLASS
{
ProcessBasicInformation, // q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION
ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX
ProcessIoCounters, // q: IO_COUNTERS
ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX, VM_COUNTERS_EX2
ProcessTimes, // q: KERNEL_USER_TIMES
ProcessBasePriority, // s: KPRIORITY
ProcessRaisePriority, // s: ULONG
ProcessDebugPort, // q: HANDLE
ProcessExceptionPort, // s: PROCESS_EXCEPTION_PORT
ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN
ProcessLdtInformation, // qs: PROCESS_LDT_INFORMATION // 10
ProcessLdtSize, // s: PROCESS_LDT_SIZE
ProcessDefaultHardErrorMode, // qs: ULONG
ProcessIoPortHandlers, // (kernel-mode only)
ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS
ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void
ProcessUserModeIOPL,
ProcessEnableAlignmentFaultFixup, // s: BOOLEAN
ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS
ProcessWx86Information,
ProcessHandleCount, // q: ULONG, PROCESS_HANDLE_INFORMATION // 20
ProcessAffinityMask, // s: KAFFINITY
ProcessPriorityBoost, // qs: ULONG
ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX
ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION
ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND
ProcessWow64Information, // q: ULONG_PTR
ProcessImageFileName, // q: UNICODE_STRING
ProcessLUIDDeviceMapsEnabled, // q: ULONG
ProcessBreakOnTermination, // qs: ULONG
ProcessDebugObjectHandle, // q: HANDLE // 30
ProcessDebugFlags, // qs: ULONG
ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables
ProcessIoPriority, // qs: IO_PRIORITY_HINT
ProcessExecuteFlags, // qs: ULONG
ProcessResourceManagement, // ProcessTlsInformation // PROCESS_TLS_INFORMATION
ProcessCookie, // q: ULONG
ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION
ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION // since VISTA
ProcessPagePriority, // q: PAGE_PRIORITY_INFORMATION
ProcessInstrumentationCallback, // qs: PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION // 40
ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX
ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]
ProcessImageFileNameWin32, // q: UNICODE_STRING
ProcessImageFileMapping, // q: HANDLE (input)
ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE
ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE
ProcessGroupInformation, // q: USHORT[]
ProcessTokenVirtualizationEnabled, // s: ULONG
ProcessConsoleHostProcess, // q: ULONG_PTR // ProcessOwnerInformation
ProcessWindowInformation, // q: PROCESS_WINDOW_INFORMATION // 50
ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8
ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION
ProcessDynamicFunctionTableInformation,
ProcessHandleCheckingMode, // qs: ULONG; s: 0 disables, otherwise enables
ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION
ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION
ProcessWorkingSetControl, // s: PROCESS_WORKING_SET_CONTROL
ProcessHandleTable, // since WINBLUE
ProcessCheckStackExtentsMode,
ProcessCommandLineInformation, // q: UNICODE_STRING // 60
ProcessProtectionInformation, // q: PS_PROTECTION
ProcessMemoryExhaustion, // PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD
ProcessFaultInformation, // PROCESS_FAULT_INFORMATION
ProcessTelemetryIdInformation, // PROCESS_TELEMETRY_ID_INFORMATION
ProcessCommitReleaseInformation, // PROCESS_COMMIT_RELEASE_INFORMATION
ProcessDefaultCpuSetsInformation,
ProcessAllowedCpuSetsInformation,
ProcessSubsystemProcess,
ProcessJobMemoryInformation, // PROCESS_JOB_MEMORY_INFO
ProcessInPrivate, // since THRESHOLD2 // 70
ProcessRaiseUMExceptionOnInvalidHandleClose,
ProcessIumChallengeResponse,
ProcessChildProcessInformation, // PROCESS_CHILD_PROCESS_INFORMATION
ProcessHighGraphicsPriorityInformation,
ProcessSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2
ProcessEnergyValues, // PROCESS_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES
ProcessActivityThrottleState, // PROCESS_ACTIVITY_THROTTLE_STATE
ProcessActivityThrottlePolicy, // PROCESS_ACTIVITY_THROTTLE_POLICY
ProcessWin32kSyscallFilterInformation,
ProcessDisableSystemAllowedCpuSets, // 80
ProcessWakeInformation, // PROCESS_WAKE_INFORMATION
ProcessEnergyTrackingState, // PROCESS_ENERGY_TRACKING_STATE
ProcessManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3
ProcessCaptureTrustletLiveDump,
ProcessTelemetryCoverage,
ProcessEnclaveInformation,
ProcessEnableReadWriteVmLogging, // PROCESS_READWRITEVM_LOGGING_INFORMATION
ProcessUptimeInformation, // PROCESS_UPTIME_INFORMATION
ProcessImageSection,
ProcessDebugAuthInformation, // since REDSTONE4 // 90
ProcessSystemResourceManagement, // PROCESS_SYSTEM_RESOURCE_MANAGEMENT
ProcessSequenceNumber, // q: ULONGLONG
ProcessLoaderDetour, // since REDSTONE5
ProcessSecurityDomainInformation, // PROCESS_SECURITY_DOMAIN_INFORMATION
ProcessCombineSecurityDomainsInformation, // PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION
ProcessEnableLogging, // PROCESS_LOGGING_INFORMATION
ProcessLeapSecondInformation, // PROCESS_LEAP_SECOND_INFORMATION
ProcessFiberShadowStackAllocation, // PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION // since 19H1
ProcessFreeFiberShadowStackAllocation, // PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
MaxProcessInfoClass
} PROCESSINFOCLASS;
typedef enum _THREADINFOCLASS
{
ThreadBasicInformation, // q: THREAD_BASIC_INFORMATION
ThreadTimes, // q: KERNEL_USER_TIMES
ThreadPriority, // s: KPRIORITY
ThreadBasePriority, // s: LONG
ThreadAffinityMask, // s: KAFFINITY
ThreadImpersonationToken, // s: HANDLE
ThreadDescriptorTableEntry, // q: DESCRIPTOR_TABLE_ENTRY (or WOW64_DESCRIPTOR_TABLE_ENTRY)
ThreadEnableAlignmentFaultFixup, // s: BOOLEAN
ThreadEventPair,
ThreadQuerySetWin32StartAddress, // q: PVOID
ThreadZeroTlsCell, // 10
ThreadPerformanceCount, // q: LARGE_INTEGER
ThreadAmILastThread, // q: ULONG
ThreadIdealProcessor, // s: ULONG
ThreadPriorityBoost, // qs: ULONG
ThreadSetTlsArrayAddress,
ThreadIsIoPending, // q: ULONG
ThreadHideFromDebugger, // s: void
ThreadBreakOnTermination, // qs: ULONG
ThreadSwitchLegacyState,
ThreadIsTerminated, // q: ULONG // 20
ThreadLastSystemCall, // q: THREAD_LAST_SYSCALL_INFORMATION
ThreadIoPriority, // qs: IO_PRIORITY_HINT
ThreadCycleTime, // q: THREAD_CYCLE_TIME_INFORMATION
ThreadPagePriority, // q: ULONG
ThreadActualBasePriority,
ThreadTebInformation, // q: THREAD_TEB_INFORMATION (requires THREAD_GET_CONTEXT + THREAD_SET_CONTEXT)
ThreadCSwitchMon,
ThreadCSwitchPmu,
ThreadWow64Context, // q: WOW64_CONTEXT
ThreadGroupInformation, // q: GROUP_AFFINITY // 30
ThreadUmsInformation, // q: THREAD_UMS_INFORMATION
ThreadCounterProfiling,
ThreadIdealProcessorEx, // q: PROCESSOR_NUMBER
ThreadCpuAccountingInformation, // since WIN8
ThreadSuspendCount, // since WINBLUE
ThreadHeterogeneousCpuPolicy, // q: KHETERO_CPU_POLICY // since THRESHOLD
ThreadContainerId, // q: GUID
ThreadNameInformation, // qs: THREAD_NAME_INFORMATION
ThreadSelectedCpuSets,
ThreadSystemThreadInformation, // q: SYSTEM_THREAD_INFORMATION // 40
ThreadActualGroupAffinity, // since THRESHOLD2
ThreadDynamicCodePolicyInfo,
ThreadExplicitCaseSensitivity, // qs: ULONG; s: 0 disables, otherwise enables
ThreadWorkOnBehalfTicket,
ThreadSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2
ThreadDbgkWerReportActive,
ThreadAttachContainer,
ThreadManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3
ThreadPowerThrottlingState, // THREAD_POWER_THROTTLING_STATE
ThreadWorkloadClass, // THREAD_WORKLOAD_CLASS // since REDSTONE5 // 50
MaxThreadInfoClass
} THREADINFOCLASS;
// Use with both ProcessPagePriority and ThreadPagePriority
typedef struct _PAGE_PRIORITY_INFORMATION
{
ULONG PagePriority;
} PAGE_PRIORITY_INFORMATION, *PPAGE_PRIORITY_INFORMATION;
// Process information structures
typedef struct _PROCESS_BASIC_INFORMATION
{
NTSTATUS ExitStatus;
PPEB PebBaseAddress;
ULONG_PTR AffinityMask;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;
typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION
{
SIZE_T Size; // set to sizeof structure on input
PROCESS_BASIC_INFORMATION BasicInfo;
union
{
ULONG Flags;
struct
{
ULONG IsProtectedProcess : 1;
ULONG IsWow64Process : 1;
ULONG IsProcessDeleting : 1;
ULONG IsCrossSessionCreate : 1;
ULONG IsFrozen : 1;
ULONG IsBackground : 1;
ULONG IsStronglyNamed : 1;
ULONG IsSecureProcess : 1;
ULONG IsSubsystemProcess : 1;
ULONG SpareBits : 23;
};
};
} PROCESS_EXTENDED_BASIC_INFORMATION, *PPROCESS_EXTENDED_BASIC_INFORMATION;
typedef struct _VM_COUNTERS
{
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
} VM_COUNTERS, *PVM_COUNTERS;
typedef struct _VM_COUNTERS_EX
{
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivateUsage;
} VM_COUNTERS_EX, *PVM_COUNTERS_EX;
// private
typedef struct _VM_COUNTERS_EX2
{
VM_COUNTERS_EX CountersEx;
SIZE_T PrivateWorkingSetSize;
SIZE_T SharedCommitUsage;
} VM_COUNTERS_EX2, *PVM_COUNTERS_EX2;
typedef struct _KERNEL_USER_TIMES
{
LARGE_INTEGER CreateTime;
LARGE_INTEGER ExitTime;
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
} KERNEL_USER_TIMES, *PKERNEL_USER_TIMES;
typedef struct _POOLED_USAGE_AND_LIMITS
{
SIZE_T PeakPagedPoolUsage;
SIZE_T PagedPoolUsage;
SIZE_T PagedPoolLimit;
SIZE_T PeakNonPagedPoolUsage;
SIZE_T NonPagedPoolUsage;
SIZE_T NonPagedPoolLimit;
SIZE_T PeakPagefileUsage;
SIZE_T PagefileUsage;
SIZE_T PagefileLimit;
} POOLED_USAGE_AND_LIMITS, *PPOOLED_USAGE_AND_LIMITS;
#define PROCESS_EXCEPTION_PORT_ALL_STATE_BITS 0x00000003
#define PROCESS_EXCEPTION_PORT_ALL_STATE_FLAGS ((ULONG_PTR)((1UL << PROCESS_EXCEPTION_PORT_ALL_STATE_BITS) - 1))
typedef struct _PROCESS_EXCEPTION_PORT
{
_In_ HANDLE ExceptionPortHandle; // Handle to the exception port. No particular access required.
_Inout_ ULONG StateFlags; // Miscellaneous state flags to be cached along with the exception port in the kernel.
} PROCESS_EXCEPTION_PORT, *PPROCESS_EXCEPTION_PORT;
typedef struct _PROCESS_ACCESS_TOKEN
{
HANDLE Token; // needs TOKEN_ASSIGN_PRIMARY access
HANDLE Thread; // handle to initial/only thread; needs THREAD_QUERY_INFORMATION access
} PROCESS_ACCESS_TOKEN, *PPROCESS_ACCESS_TOKEN;
typedef struct _PROCESS_LDT_INFORMATION
{
ULONG Start;
ULONG Length;
LDT_ENTRY LdtEntries[1];
} PROCESS_LDT_INFORMATION, *PPROCESS_LDT_INFORMATION;
typedef struct _PROCESS_LDT_SIZE
{
ULONG Length;
} PROCESS_LDT_SIZE, *PPROCESS_LDT_SIZE;
typedef struct _PROCESS_WS_WATCH_INFORMATION
{
PVOID FaultingPc;
PVOID FaultingVa;
} PROCESS_WS_WATCH_INFORMATION, *PPROCESS_WS_WATCH_INFORMATION;
// psapi:PSAPI_WS_WATCH_INFORMATION_EX
typedef struct _PROCESS_WS_WATCH_INFORMATION_EX
{
PROCESS_WS_WATCH_INFORMATION BasicInfo;
ULONG_PTR FaultingThreadId;
ULONG_PTR Flags;
} PROCESS_WS_WATCH_INFORMATION_EX, *PPROCESS_WS_WATCH_INFORMATION_EX;
#define PROCESS_PRIORITY_CLASS_UNKNOWN 0
#define PROCESS_PRIORITY_CLASS_IDLE 1
#define PROCESS_PRIORITY_CLASS_NORMAL 2
#define PROCESS_PRIORITY_CLASS_HIGH 3
#define PROCESS_PRIORITY_CLASS_REALTIME 4
#define PROCESS_PRIORITY_CLASS_BELOW_NORMAL 5
#define PROCESS_PRIORITY_CLASS_ABOVE_NORMAL 6
typedef struct _PROCESS_PRIORITY_CLASS
{
BOOLEAN Foreground;
UCHAR PriorityClass;
} PROCESS_PRIORITY_CLASS, *PPROCESS_PRIORITY_CLASS;
typedef struct _PROCESS_FOREGROUND_BACKGROUND
{
BOOLEAN Foreground;
} PROCESS_FOREGROUND_BACKGROUND, *PPROCESS_FOREGROUND_BACKGROUND;
typedef struct _PROCESS_DEVICEMAP_INFORMATION
{
union
{
struct
{
HANDLE DirectoryHandle;
} Set;
struct
{
ULONG DriveMap;
UCHAR DriveType[32];
} Query;
};
} PROCESS_DEVICEMAP_INFORMATION, *PPROCESS_DEVICEMAP_INFORMATION;
#define PROCESS_LUID_DOSDEVICES_ONLY 0x00000001
typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX
{
union
{
struct
{
HANDLE DirectoryHandle;
} Set;
struct
{
ULONG DriveMap;
UCHAR DriveType[32];
} Query;
};
ULONG Flags; // PROCESS_LUID_DOSDEVICES_ONLY
} PROCESS_DEVICEMAP_INFORMATION_EX, *PPROCESS_DEVICEMAP_INFORMATION_EX;
typedef struct _PROCESS_SESSION_INFORMATION
{
ULONG SessionId;
} PROCESS_SESSION_INFORMATION, *PPROCESS_SESSION_INFORMATION;
#define PROCESS_HANDLE_EXCEPTIONS_ENABLED 0x00000001
#define PROCESS_HANDLE_RAISE_EXCEPTION_ON_INVALID_HANDLE_CLOSE_DISABLED 0x00000000
#define PROCESS_HANDLE_RAISE_EXCEPTION_ON_INVALID_HANDLE_CLOSE_ENABLED 0x00000001
typedef struct _PROCESS_HANDLE_TRACING_ENABLE
{
ULONG Flags;
} PROCESS_HANDLE_TRACING_ENABLE, *PPROCESS_HANDLE_TRACING_ENABLE;
#define PROCESS_HANDLE_TRACING_MAX_SLOTS 0x20000
typedef struct _PROCESS_HANDLE_TRACING_ENABLE_EX
{
ULONG Flags;
ULONG TotalSlots;
} PROCESS_HANDLE_TRACING_ENABLE_EX, *PPROCESS_HANDLE_TRACING_ENABLE_EX;
#define PROCESS_HANDLE_TRACING_MAX_STACKS 16
#define PROCESS_HANDLE_TRACE_TYPE_OPEN 1
#define PROCESS_HANDLE_TRACE_TYPE_CLOSE 2
#define PROCESS_HANDLE_TRACE_TYPE_BADREF 3
typedef struct _PROCESS_HANDLE_TRACING_ENTRY
{
HANDLE Handle;
CLIENT_ID ClientId;
ULONG Type;
PVOID Stacks[PROCESS_HANDLE_TRACING_MAX_STACKS];
} PROCESS_HANDLE_TRACING_ENTRY, *PPROCESS_HANDLE_TRACING_ENTRY;
typedef struct _PROCESS_HANDLE_TRACING_QUERY
{
HANDLE Handle;
ULONG TotalTraces;
PROCESS_HANDLE_TRACING_ENTRY HandleTrace[1];
} PROCESS_HANDLE_TRACING_QUERY, *PPROCESS_HANDLE_TRACING_QUERY;
// private
typedef struct _THREAD_TLS_INFORMATION
{
ULONG Flags;
PVOID NewTlsData;
PVOID OldTlsData;
HANDLE ThreadId;
} THREAD_TLS_INFORMATION, *PTHREAD_TLS_INFORMATION;
// private
typedef enum _PROCESS_TLS_INFORMATION_TYPE
{
ProcessTlsReplaceIndex,
ProcessTlsReplaceVector,
MaxProcessTlsOperation
} PROCESS_TLS_INFORMATION_TYPE, *PPROCESS_TLS_INFORMATION_TYPE;
// private
typedef struct _PROCESS_TLS_INFORMATION
{
ULONG Flags;
ULONG OperationType;
ULONG ThreadDataCount;
ULONG TlsIndex;
ULONG PreviousCount;
THREAD_TLS_INFORMATION ThreadData[1];
} PROCESS_TLS_INFORMATION, *PPROCESS_TLS_INFORMATION;
// private
typedef struct _PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION
{
ULONG Version;
ULONG Reserved;
PVOID Callback;
} PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION, *PPROCESS_INSTRUMENTATION_CALLBACK_INFORMATION;
// private
typedef struct _PROCESS_STACK_ALLOCATION_INFORMATION
{
SIZE_T ReserveSize;
SIZE_T ZeroBits;
PVOID StackBase;
} PROCESS_STACK_ALLOCATION_INFORMATION, *PPROCESS_STACK_ALLOCATION_INFORMATION;
// private
typedef struct _PROCESS_STACK_ALLOCATION_INFORMATION_EX
{
ULONG PreferredNode;
ULONG Reserved0;
ULONG Reserved1;
ULONG Reserved2;
PROCESS_STACK_ALLOCATION_INFORMATION AllocInfo;
} PROCESS_STACK_ALLOCATION_INFORMATION_EX, *PPROCESS_STACK_ALLOCATION_INFORMATION_EX;
// private
typedef union _PROCESS_AFFINITY_UPDATE_MODE
{
ULONG Flags;
struct
{
ULONG EnableAutoUpdate : 1;
ULONG Permanent : 1;
ULONG Reserved : 30;
};
} PROCESS_AFFINITY_UPDATE_MODE, *PPROCESS_AFFINITY_UPDATE_MODE;
// private
typedef union _PROCESS_MEMORY_ALLOCATION_MODE
{
ULONG Flags;
struct
{
ULONG TopDown : 1;
ULONG Reserved : 31;
};
} PROCESS_MEMORY_ALLOCATION_MODE, *PPROCESS_MEMORY_ALLOCATION_MODE;
// private
typedef struct _PROCESS_HANDLE_INFORMATION
{
ULONG HandleCount;
ULONG HandleCountHighWatermark;
} PROCESS_HANDLE_INFORMATION, *PPROCESS_HANDLE_INFORMATION;
// private
typedef struct _PROCESS_CYCLE_TIME_INFORMATION
{
ULONGLONG AccumulatedCycles;
ULONGLONG CurrentCycleCount;
} PROCESS_CYCLE_TIME_INFORMATION, *PPROCESS_CYCLE_TIME_INFORMATION;
// private
typedef struct _PROCESS_WINDOW_INFORMATION
{
ULONG WindowFlags;
USHORT WindowTitleLength;
WCHAR WindowTitle[1];
} PROCESS_WINDOW_INFORMATION, *PPROCESS_WINDOW_INFORMATION;
// private
typedef struct _PROCESS_HANDLE_TABLE_ENTRY_INFO
{
HANDLE HandleValue;
ULONG_PTR HandleCount;
ULONG_PTR PointerCount;
ULONG GrantedAccess;
ULONG ObjectTypeIndex;
ULONG HandleAttributes;
ULONG Reserved;
} PROCESS_HANDLE_TABLE_ENTRY_INFO, *PPROCESS_HANDLE_TABLE_ENTRY_INFO;
// private
typedef struct _PROCESS_HANDLE_SNAPSHOT_INFORMATION
{
ULONG_PTR NumberOfHandles;
ULONG_PTR Reserved;
PROCESS_HANDLE_TABLE_ENTRY_INFO Handles[1];
} PROCESS_HANDLE_SNAPSHOT_INFORMATION, *PPROCESS_HANDLE_SNAPSHOT_INFORMATION;
// private
typedef struct _PROCESS_MITIGATION_POLICY_INFORMATION
{
PROCESS_MITIGATION_POLICY Policy;
union
{
PROCESS_MITIGATION_ASLR_POLICY ASLRPolicy;
PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY StrictHandleCheckPolicy;
PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY SystemCallDisablePolicy;
PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY ExtensionPointDisablePolicy;
PROCESS_MITIGATION_DYNAMIC_CODE_POLICY DynamicCodePolicy;
PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY ControlFlowGuardPolicy;
PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY SignaturePolicy;
PROCESS_MITIGATION_FONT_DISABLE_POLICY FontDisablePolicy;
PROCESS_MITIGATION_IMAGE_LOAD_POLICY ImageLoadPolicy;
PROCESS_MITIGATION_SYSTEM_CALL_FILTER_POLICY SystemCallFilterPolicy;
PROCESS_MITIGATION_PAYLOAD_RESTRICTION_POLICY PayloadRestrictionPolicy;
PROCESS_MITIGATION_CHILD_PROCESS_POLICY ChildProcessPolicy;
PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY SideChannelIsolationPolicy;
};
} PROCESS_MITIGATION_POLICY_INFORMATION, *PPROCESS_MITIGATION_POLICY_INFORMATION;
typedef struct _PROCESS_KEEPALIVE_COUNT_INFORMATION
{
ULONG WakeCount;
ULONG NoWakeCount;
} PROCESS_KEEPALIVE_COUNT_INFORMATION, *PPROCESS_KEEPALIVE_COUNT_INFORMATION;
typedef struct _PROCESS_REVOKE_FILE_HANDLES_INFORMATION
{
UNICODE_STRING TargetDevicePath;
} PROCESS_REVOKE_FILE_HANDLES_INFORMATION, *PPROCESS_REVOKE_FILE_HANDLES_INFORMATION;
// begin_private
typedef enum _PROCESS_WORKING_SET_OPERATION
{
ProcessWorkingSetSwap,
ProcessWorkingSetEmpty,
ProcessWorkingSetOperationMax
} PROCESS_WORKING_SET_OPERATION;
typedef struct _PROCESS_WORKING_SET_CONTROL
{
ULONG Version;
PROCESS_WORKING_SET_OPERATION Operation;
ULONG Flags;
} PROCESS_WORKING_SET_CONTROL, *PPROCESS_WORKING_SET_CONTROL;
typedef enum _PS_PROTECTED_TYPE
{
PsProtectedTypeNone,
PsProtectedTypeProtectedLight,
PsProtectedTypeProtected,
PsProtectedTypeMax
} PS_PROTECTED_TYPE;
typedef enum _PS_PROTECTED_SIGNER
{
PsProtectedSignerNone,
PsProtectedSignerAuthenticode,
PsProtectedSignerCodeGen,
PsProtectedSignerAntimalware,
PsProtectedSignerLsa,
PsProtectedSignerWindows,
PsProtectedSignerWinTcb,
PsProtectedSignerWinSystem,
PsProtectedSignerApp,
PsProtectedSignerMax
} PS_PROTECTED_SIGNER;
#define PS_PROTECTED_SIGNER_MASK 0xFF
#define PS_PROTECTED_AUDIT_MASK 0x08
#define PS_PROTECTED_TYPE_MASK 0x07
// vProtectionLevel.Level = PsProtectedValue(PsProtectedSignerCodeGen, FALSE, PsProtectedTypeProtectedLight)
#define PsProtectedValue(aSigner, aAudit, aType) ( \
((aSigner & PS_PROTECTED_SIGNER_MASK) << 4) | \
((aAudit & PS_PROTECTED_AUDIT_MASK) << 3) | \
(aType & PS_PROTECTED_TYPE_MASK)\
)
// InitializePsProtection(&vProtectionLevel, PsProtectedSignerCodeGen, FALSE, PsProtectedTypeProtectedLight)
#define InitializePsProtection(aProtectionLevelPtr, aSigner, aAudit, aType) { \
(aProtectionLevelPtr)->Signer = aSigner; \
(aProtectionLevelPtr)->Audit = aAudit; \
(aProtectionLevelPtr)->Type = aType; \
}
typedef struct _PS_PROTECTION
{
union
{
UCHAR Level;
struct
{
UCHAR Type : 3;
UCHAR Audit : 1;
UCHAR Signer : 4;
};
};
} PS_PROTECTION, *PPS_PROTECTION;
typedef struct _PROCESS_FAULT_INFORMATION
{
ULONG FaultFlags;
ULONG AdditionalInfo;
} PROCESS_FAULT_INFORMATION, *PPROCESS_FAULT_INFORMATION;
typedef struct _PROCESS_TELEMETRY_ID_INFORMATION
{
ULONG HeaderSize;
ULONG ProcessId;
ULONGLONG ProcessStartKey;
ULONGLONG CreateTime;
ULONGLONG CreateInterruptTime;
ULONGLONG CreateUnbiasedInterruptTime;
ULONGLONG ProcessSequenceNumber;
ULONGLONG SessionCreateTime;
ULONG SessionId;
ULONG BootId;
ULONG ImageChecksum;
ULONG ImageTimeDateStamp;
ULONG UserSidOffset;
ULONG ImagePathOffset;
ULONG PackageNameOffset;
ULONG RelativeAppNameOffset;
ULONG CommandLineOffset;
} PROCESS_TELEMETRY_ID_INFORMATION, *PPROCESS_TELEMETRY_ID_INFORMATION;
typedef struct _PROCESS_COMMIT_RELEASE_INFORMATION
{
ULONG Version;
struct
{
ULONG Eligible : 1;
ULONG ReleaseRepurposedMemResetCommit : 1;
ULONG ForceReleaseMemResetCommit : 1;
ULONG Spare : 29;
};
SIZE_T CommitDebt;
SIZE_T CommittedMemResetSize;
SIZE_T RepurposedMemResetSize;
} PROCESS_COMMIT_RELEASE_INFORMATION, *PPROCESS_COMMIT_RELEASE_INFORMATION;
typedef struct _PROCESS_JOB_MEMORY_INFO
{
ULONGLONG SharedCommitUsage;
ULONGLONG PrivateCommitUsage;
ULONGLONG PeakPrivateCommitUsage;
ULONGLONG PrivateCommitLimit;
ULONGLONG TotalCommitLimit;
} PROCESS_JOB_MEMORY_INFO, *PPROCESS_JOB_MEMORY_INFO;
typedef struct _PROCESS_CHILD_PROCESS_INFORMATION
{
BOOLEAN ProhibitChildProcesses;
//BOOLEAN EnableAutomaticOverride; // REDSTONE2
BOOLEAN AlwaysAllowSecureChildProcess; // REDSTONE3
BOOLEAN AuditProhibitChildProcesses;
} PROCESS_CHILD_PROCESS_INFORMATION, *PPROCESS_CHILD_PROCESS_INFORMATION;
typedef struct _PROCESS_WAKE_INFORMATION
{
ULONGLONG NotificationChannel;
ULONG WakeCounters[7];
struct _JOBOBJECT_WAKE_FILTER* WakeFilter;
} PROCESS_WAKE_INFORMATION, *PPROCESS_WAKE_INFORMATION;
typedef struct _PROCESS_ENERGY_TRACKING_STATE
{
ULONG StateUpdateMask;
ULONG StateDesiredValue;
ULONG StateSequence;
ULONG UpdateTag : 1;
WCHAR Tag[64];
} PROCESS_ENERGY_TRACKING_STATE, *PPROCESS_ENERGY_TRACKING_STATE;
typedef struct _MANAGE_WRITES_TO_EXECUTABLE_MEMORY
{
ULONG Version : 8;
ULONG ProcessEnableWriteExceptions : 1;
ULONG ThreadAllowWrites : 1;
ULONG Spare : 22;
PVOID KernelWriteToExecutableSignal; // 19H1
} MANAGE_WRITES_TO_EXECUTABLE_MEMORY, *PMANAGE_WRITES_TO_EXECUTABLE_MEMORY;
#define PROCESS_READWRITEVM_LOGGING_ENABLE_READVM 1
#define PROCESS_READWRITEVM_LOGGING_ENABLE_WRITEVM 2
#define PROCESS_READWRITEVM_LOGGING_ENABLE_READVM_V 1UL
#define PROCESS_READWRITEVM_LOGGING_ENABLE_WRITEVM_V 2UL
typedef union _PROCESS_READWRITEVM_LOGGING_INFORMATION
{
UCHAR Flags;
struct
{
UCHAR EnableReadVmLogging : 1;
UCHAR EnableWriteVmLogging : 1;
UCHAR Unused : 6;
};
} PROCESS_READWRITEVM_LOGGING_INFORMATION, *PPROCESS_READWRITEVM_LOGGING_INFORMATION;
typedef struct _PROCESS_UPTIME_INFORMATION
{
ULONGLONG QueryInterruptTime;
ULONGLONG QueryUnbiasedTime;
ULONGLONG EndInterruptTime;
ULONGLONG TimeSinceCreation;
ULONGLONG Uptime;
ULONGLONG SuspendedTime;
union
{
ULONG HangCount : 4;
ULONG GhostCount : 4;
ULONG Crashed : 1;
ULONG Terminated : 1;
};
} PROCESS_UPTIME_INFORMATION, *PPROCESS_UPTIME_INFORMATION;
typedef union _PROCESS_SYSTEM_RESOURCE_MANAGEMENT
{
ULONG Flags;
struct
{
ULONG Foreground : 1;
ULONG Reserved : 31;
};
} PROCESS_SYSTEM_RESOURCE_MANAGEMENT, *PPROCESS_SYSTEM_RESOURCE_MANAGEMENT;
// private
typedef struct _PROCESS_SECURITY_DOMAIN_INFORMATION
{
ULONGLONG SecurityDomain;
} PROCESS_SECURITY_DOMAIN_INFORMATION, *PPROCESS_SECURITY_DOMAIN_INFORMATION;
// private
typedef struct _PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION
{
HANDLE ProcessHandle;
} PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION, *PPROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION;
// private
typedef struct _PROCESS_LOGGING_INFORMATION
{
ULONG Flags;
struct
{
ULONG EnableReadVmLogging : 1;
ULONG EnableWriteVmLogging : 1;
ULONG EnableProcessSuspendResumeLogging : 1;
ULONG EnableThreadSuspendResumeLogging : 1;
ULONG Reserved : 28;
};
} PROCESS_LOGGING_INFORMATION, *PPROCESS_LOGGING_INFORMATION;
// private
typedef struct _PROCESS_LEAP_SECOND_INFORMATION
{
ULONG Flags;
ULONG Reserved;
} PROCESS_LEAP_SECOND_INFORMATION, *PPROCESS_LEAP_SECOND_INFORMATION;
// private
typedef struct _PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
{
ULONGLONG ReserveSize;
ULONGLONG CommitSize;
ULONG PreferredNode;
ULONG Reserved;
PVOID Ssp;
} PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION, *PPROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION;
// private
typedef struct _PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
{
PVOID Ssp;
} PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION, *PPROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION;
// end_private
// Thread information structures
typedef struct _THREAD_BASIC_INFORMATION
{
NTSTATUS ExitStatus;
PTEB TebBaseAddress;
CLIENT_ID ClientId;
ULONG_PTR AffinityMask;
KPRIORITY Priority;
LONG BasePriority;
} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
// private
typedef struct _THREAD_LAST_SYSCALL_INFORMATION
{
PVOID FirstArgument;
USHORT SystemCallNumber;
#ifdef WIN64
USHORT Pad[0x3]; // since REDSTONE2
#else
USHORT Pad[0x1]; // since REDSTONE2
#endif
ULONG64 WaitTime;
} THREAD_LAST_SYSCALL_INFORMATION, *PTHREAD_LAST_SYSCALL_INFORMATION;
// private
typedef struct _THREAD_CYCLE_TIME_INFORMATION
{
ULONGLONG AccumulatedCycles;
ULONGLONG CurrentCycleCount;
} THREAD_CYCLE_TIME_INFORMATION, *PTHREAD_CYCLE_TIME_INFORMATION;
// private
typedef struct _THREAD_TEB_INFORMATION
{
PVOID TebInformation; // buffer to place data in
ULONG TebOffset; // offset in TEB to begin reading from
ULONG BytesToRead; // number of bytes to read
} THREAD_TEB_INFORMATION, *PTHREAD_TEB_INFORMATION;
// symbols
typedef struct _COUNTER_READING
{
HARDWARE_COUNTER_TYPE Type;
ULONG Index;
ULONG64 Start;
ULONG64 Total;
} COUNTER_READING, *PCOUNTER_READING;
// symbols
typedef struct _THREAD_PERFORMANCE_DATA
{
USHORT Size;
USHORT Version;
PROCESSOR_NUMBER ProcessorNumber;
ULONG ContextSwitches;
ULONG HwCountersCount;
ULONG64 UpdateCount;
ULONG64 WaitReasonBitMap;
ULONG64 HardwareCounters;
COUNTER_READING CycleTime;
COUNTER_READING HwCounters[MAX_HW_COUNTERS];
} THREAD_PERFORMANCE_DATA, *PTHREAD_PERFORMANCE_DATA;
// private
typedef struct _THREAD_PROFILING_INFORMATION
{
ULONG64 HardwareCounters;
ULONG Flags;
ULONG Enable;
PTHREAD_PERFORMANCE_DATA PerformanceData;
} THREAD_PROFILING_INFORMATION, *PTHREAD_PROFILING_INFORMATION;
// private
typedef struct _RTL_UMS_CONTEXT
{
SINGLE_LIST_ENTRY Link;
CONTEXT Context;
PVOID Teb;
PVOID UserContext;
volatile ULONG ScheduledThread;
volatile ULONG Suspended;
volatile ULONG VolatileContext;
volatile ULONG Terminated;
volatile ULONG DebugActive;
volatile ULONG RunningOnSelfThread;
volatile ULONG DenyRunningOnSelfThread;
volatile LONG Flags;
volatile ULONG64 KernelUpdateLock;
volatile ULONG64 PrimaryClientID;
volatile ULONG64 ContextLock;
struct _RTL_UMS_CONTEXT* PrimaryUmsContext;
ULONG SwitchCount;
ULONG KernelYieldCount;
ULONG MixedYieldCount;
ULONG YieldCount;
} RTL_UMS_CONTEXT, *PRTL_UMS_CONTEXT;
// private
typedef enum _THREAD_UMS_INFORMATION_COMMAND
{
UmsInformationCommandInvalid,
UmsInformationCommandAttach,
UmsInformationCommandDetach,
UmsInformationCommandQuery
} THREAD_UMS_INFORMATION_COMMAND;
// private
typedef struct _RTL_UMS_COMPLETION_LIST
{
PSINGLE_LIST_ENTRY ThreadListHead;
PVOID CompletionEvent;
ULONG CompletionFlags;
SINGLE_LIST_ENTRY InternalListHead;
} RTL_UMS_COMPLETION_LIST, *PRTL_UMS_COMPLETION_LIST;
// private
typedef struct _THREAD_UMS_INFORMATION
{
THREAD_UMS_INFORMATION_COMMAND Command;
PRTL_UMS_COMPLETION_LIST CompletionList;
PRTL_UMS_CONTEXT UmsContext;
union
{
ULONG Flags;
struct
{
ULONG IsUmsSchedulerThread : 1;
ULONG IsUmsWorkerThread : 1;
ULONG SpareBits : 30;
};
};
} THREAD_UMS_INFORMATION, *PTHREAD_UMS_INFORMATION;
// private
typedef struct _THREAD_NAME_INFORMATION
{
UNICODE_STRING ThreadName;
} THREAD_NAME_INFORMATION, *PTHREAD_NAME_INFORMATION;
// private
typedef enum _SUBSYSTEM_INFORMATION_TYPE
{
SubsystemInformationTypeWin32,
SubsystemInformationTypeWSL,
MaxSubsystemInformationType
} SUBSYSTEM_INFORMATION_TYPE;
// private
typedef enum _THREAD_WORKLOAD_CLASS
{
ThreadWorkloadClassDefault,
ThreadWorkloadClassGraphics,
MaxThreadWorkloadClass
} THREAD_WORKLOAD_CLASS;
// Processes
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateProcess(
_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ParentProcess,
_In_ BOOLEAN InheritObjectTable,
_In_opt_ HANDLE SectionHandle,
_In_opt_ HANDLE DebugPort,
_In_opt_ HANDLE ExceptionPort
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateProcess(
_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ParentProcess,
_In_ BOOLEAN InheritObjectTable,
_In_opt_ HANDLE SectionHandle,
_In_opt_ HANDLE DebugPort,
_In_opt_ HANDLE ExceptionPort
);
#define PROCESS_CREATE_FLAGS_BREAKAWAY 0x00000001
#define PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT 0x00000002
#define PROCESS_CREATE_FLAGS_INHERIT_HANDLES 0x00000004
#define PROCESS_CREATE_FLAGS_OVERRIDE_ADDRESS_SPACE 0x00000008
#define PROCESS_CREATE_FLAGS_LARGE_PAGES 0x00000010
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateProcessEx(
_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ParentProcess,
_In_ ULONG Flags,
_In_opt_ HANDLE SectionHandle,
_In_opt_ HANDLE DebugPort,
_In_opt_ HANDLE ExceptionPort,
_In_ ULONG JobMemberLevel
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateProcessEx(
_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ParentProcess,
_In_ ULONG Flags,
_In_opt_ HANDLE SectionHandle,
_In_opt_ HANDLE DebugPort,
_In_opt_ HANDLE ExceptionPort,
_In_ ULONG JobMemberLevel
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenProcess(
_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PCLIENT_ID ClientId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenProcess(
_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PCLIENT_ID ClientId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTerminateProcess(
_In_opt_ HANDLE ProcessHandle,
_In_ NTSTATUS ExitStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTerminateProcess(
_In_opt_ HANDLE ProcessHandle,
_In_ NTSTATUS ExitStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSuspendProcess(
_In_ HANDLE ProcessHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSuspendProcess(
_In_ HANDLE ProcessHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtResumeProcess(
_In_ HANDLE ProcessHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwResumeProcess(
_In_ HANDLE ProcessHandle
);
#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)
#define ZwCurrentProcess() NtCurrentProcess()
#define NtCurrentThread() ((HANDLE)(LONG_PTR)-2)
#define ZwCurrentThread() NtCurrentThread()
#define NtCurrentSession() ((HANDLE)(LONG_PTR)-3)
#define ZwCurrentSession() NtCurrentSession()
#define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock)
// Windows 8 and above
#define NtCurrentProcessToken() ((HANDLE)(LONG_PTR)-4)
#define NtCurrentThreadToken() ((HANDLE)(LONG_PTR)-5)
#define NtCurrentEffectiveToken() ((HANDLE)(LONG_PTR)-6)
#define NtCurrentSilo() ((HANDLE)(LONG_PTR)-1)
// Not NT, but useful.
#define NtCurrentProcessId() (NtCurrentTeb()->ClientId.UniqueProcess)
#define NtCurrentThreadId() (NtCurrentTeb()->ClientId.UniqueThread)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetNextProcess(
_In_ HANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_In_ ULONG Flags,
_Out_ PHANDLE NewProcessHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetNextProcess(
_In_ HANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_In_ ULONG Flags,
_Out_ PHANDLE NewProcessHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetNextThread(
_In_ HANDLE ProcessHandle,
_In_ HANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_In_ ULONG Flags,
_Out_ PHANDLE NewThreadHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetNextThread(
_In_ HANDLE ProcessHandle,
_In_ HANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_In_ ULONG Flags,
_Out_ PHANDLE NewThreadHandle
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_In_reads_bytes_(ProcessInformationLength) PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_In_reads_bytes_(ProcessInformationLength) PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryPortInformationProcess(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryPortInformationProcess(
VOID
);
// Threads
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateThread(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ProcessHandle,
_Out_ PCLIENT_ID ClientId,
_In_ PCONTEXT ThreadContext,
_In_ PINITIAL_TEB InitialTeb,
_In_ BOOLEAN CreateSuspended
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateThread(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ProcessHandle,
_Out_ PCLIENT_ID ClientId,
_In_ PCONTEXT ThreadContext,
_In_ PINITIAL_TEB InitialTeb,
_In_ BOOLEAN CreateSuspended
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenThread(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PCLIENT_ID ClientId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenThread(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PCLIENT_ID ClientId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTerminateThread(
_In_opt_ HANDLE ThreadHandle,
_In_ NTSTATUS ExitStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTerminateThread(
_In_opt_ HANDLE ThreadHandle,
_In_ NTSTATUS ExitStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSuspendThread(
_In_ HANDLE ThreadHandle,
_Out_opt_ PULONG PreviousSuspendCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSuspendThread(
_In_ HANDLE ThreadHandle,
_Out_opt_ PULONG PreviousSuspendCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtResumeThread(
_In_ HANDLE ThreadHandle,
_Out_opt_ PULONG PreviousSuspendCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwResumeThread(
_In_ HANDLE ThreadHandle,
_Out_opt_ PULONG PreviousSuspendCount
);
NTSYSCALLAPI
ULONG
NTAPI
NtGetCurrentProcessorNumber(
VOID
);
NTSYSCALLAPI
ULONG
NTAPI
ZwGetCurrentProcessorNumber(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetContextThread(
_In_ HANDLE ThreadHandle,
_Inout_ PCONTEXT ThreadContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetContextThread(
_In_ HANDLE ThreadHandle,
_Inout_ PCONTEXT ThreadContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetContextThread(
_In_ HANDLE ThreadHandle,
_In_ PCONTEXT ThreadContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetContextThread(
_In_ HANDLE ThreadHandle,
_In_ PCONTEXT ThreadContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationThread(
_In_ HANDLE ThreadHandle,
_In_ THREADINFOCLASS ThreadInformationClass,
_Out_writes_bytes_(ThreadInformationLength) PVOID ThreadInformation,
_In_ ULONG ThreadInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationThread(
_In_ HANDLE ThreadHandle,
_In_ THREADINFOCLASS ThreadInformationClass,
_Out_writes_bytes_(ThreadInformationLength) PVOID ThreadInformation,
_In_ ULONG ThreadInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationThread(
_In_ HANDLE ThreadHandle,
_In_ THREADINFOCLASS ThreadInformationClass,
_In_reads_bytes_(ThreadInformationLength) PVOID ThreadInformation,
_In_ ULONG ThreadInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationThread(
_In_ HANDLE ThreadHandle,
_In_ THREADINFOCLASS ThreadInformationClass,
_In_reads_bytes_(ThreadInformationLength) PVOID ThreadInformation,
_In_ ULONG ThreadInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlertThread(
_In_ HANDLE ThreadHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlertThread(
_In_ HANDLE ThreadHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlertResumeThread(
_In_ HANDLE ThreadHandle,
_Out_opt_ PULONG PreviousSuspendCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlertResumeThread(
_In_ HANDLE ThreadHandle,
_Out_opt_ PULONG PreviousSuspendCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTestAlert(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTestAlert(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtImpersonateThread(
_In_ HANDLE ServerThreadHandle,
_In_ HANDLE ClientThreadHandle,
_In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwImpersonateThread(
_In_ HANDLE ServerThreadHandle,
_In_ HANDLE ClientThreadHandle,
_In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRegisterThreadTerminatePort(
_In_ HANDLE PortHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRegisterThreadTerminatePort(
_In_ HANDLE PortHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetLdtEntries(
_In_ ULONG Selector0,
_In_ ULONG Entry0Low,
_In_ ULONG Entry0Hi,
_In_ ULONG Selector1,
_In_ ULONG Entry1Low,
_In_ ULONG Entry1Hi
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetLdtEntries(
_In_ ULONG Selector0,
_In_ ULONG Entry0Low,
_In_ ULONG Entry0Hi,
_In_ ULONG Selector1,
_In_ ULONG Entry1Low,
_In_ ULONG Entry1Hi
);
typedef VOID (*PPS_APC_ROUTINE)(
_In_opt_ PVOID ApcArgument1,
_In_opt_ PVOID ApcArgument2,
_In_opt_ PVOID ApcArgument3
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueueApcThread(
_In_ HANDLE ThreadHandle,
_In_ PPS_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcArgument1,
_In_opt_ PVOID ApcArgument2,
_In_opt_ PVOID ApcArgument3
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueueApcThread(
_In_ HANDLE ThreadHandle,
_In_ PPS_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcArgument1,
_In_opt_ PVOID ApcArgument2,
_In_opt_ PVOID ApcArgument3
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
#define APC_FORCE_THREAD_SIGNAL ((HANDLE)1) // UserApcReserveHandle
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueueApcThreadEx(
_In_ HANDLE ThreadHandle,
_In_opt_ HANDLE UserApcReserveHandle,
_In_ PPS_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcArgument1,
_In_opt_ PVOID ApcArgument2,
_In_opt_ PVOID ApcArgument3
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueueApcThreadEx(
_In_ HANDLE ThreadHandle,
_In_opt_ HANDLE UserApcReserveHandle,
_In_ PPS_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcArgument1,
_In_opt_ PVOID ApcArgument2,
_In_opt_ PVOID ApcArgument3
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN8)
// rev
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlertThreadByThreadId(
_In_ HANDLE ThreadId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlertThreadByThreadId(
_In_ HANDLE ThreadId
);
// rev
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForAlertByThreadId(
_In_ PVOID Address,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForAlertByThreadId(
_In_ PVOID Address,
_In_opt_ PLARGE_INTEGER Timeout
);
#endif
// User processes and threads
// Attributes
// private
#define PS_ATTRIBUTE_NUMBER_MASK 0x0000ffff
#define PS_ATTRIBUTE_THREAD 0x00010000 // may be used with thread creation
#define PS_ATTRIBUTE_INPUT 0x00020000 // input only
#define PS_ATTRIBUTE_ADDITIVE 0x00040000 // "accumulated" e.g. bitmasks, counters, etc.
// private
typedef enum _PS_ATTRIBUTE_NUM
{
PsAttributeParentProcess, // in HANDLE
PsAttributeDebugPort, // in HANDLE
PsAttributeToken, // in HANDLE
PsAttributeClientId, // out PCLIENT_ID
PsAttributeTebAddress, // out PTEB *
PsAttributeImageName, // in PWSTR
PsAttributeImageInfo, // out PSECTION_IMAGE_INFORMATION
PsAttributeMemoryReserve, // in PPS_MEMORY_RESERVE
PsAttributePriorityClass, // in UCHAR
PsAttributeErrorMode, // in ULONG
PsAttributeStdHandleInfo, // 10, in PPS_STD_HANDLE_INFO
PsAttributeHandleList, // in PHANDLE
PsAttributeGroupAffinity, // in PGROUP_AFFINITY
PsAttributePreferredNode, // in PUSHORT
PsAttributeIdealProcessor, // in PPROCESSOR_NUMBER
PsAttributeUmsThread, // ? in PUMS_CREATE_THREAD_ATTRIBUTES
PsAttributeMitigationOptions, // in UCHAR
PsAttributeProtectionLevel, // in ULONG
PsAttributeSecureProcess, // since THRESHOLD
PsAttributeJobList,
PsAttributeChildProcessPolicy, // since THRESHOLD2
PsAttributeAllApplicationPackagesPolicy, // since REDSTONE
PsAttributeWin32kFilter,
PsAttributeSafeOpenPromptOriginClaim,
PsAttributeBnoIsolation, // PS_BNO_ISOLATION_PARAMETERS
PsAttributeDesktopAppPolicy, // in ULONG
PsAttributeChpe, // since REDSTONE3
PsAttributeMax
} PS_ATTRIBUTE_NUM;
// begin_rev
#define PsAttributeValue(Number, Thread, Input, Additive) \
(((Number) & PS_ATTRIBUTE_NUMBER_MASK) | \
((Thread) ? PS_ATTRIBUTE_THREAD : 0) | \
((Input) ? PS_ATTRIBUTE_INPUT : 0) | \
((Additive) ? PS_ATTRIBUTE_ADDITIVE : 0))
#define PS_ATTRIBUTE_PARENT_PROCESS \
PsAttributeValue(PsAttributeParentProcess, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_DEBUG_PORT \
PsAttributeValue(PsAttributeDebugPort, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_TOKEN \
PsAttributeValue(PsAttributeToken, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_CLIENT_ID \
PsAttributeValue(PsAttributeClientId, TRUE, FALSE, FALSE)
#define PS_ATTRIBUTE_TEB_ADDRESS \
PsAttributeValue(PsAttributeTebAddress, TRUE, FALSE, FALSE)
#define PS_ATTRIBUTE_IMAGE_NAME \
PsAttributeValue(PsAttributeImageName, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_IMAGE_INFO \
PsAttributeValue(PsAttributeImageInfo, FALSE, FALSE, FALSE)
#define PS_ATTRIBUTE_MEMORY_RESERVE \
PsAttributeValue(PsAttributeMemoryReserve, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_PRIORITY_CLASS \
PsAttributeValue(PsAttributePriorityClass, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_ERROR_MODE \
PsAttributeValue(PsAttributeErrorMode, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_STD_HANDLE_INFO \
PsAttributeValue(PsAttributeStdHandleInfo, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_HANDLE_LIST \
PsAttributeValue(PsAttributeHandleList, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_GROUP_AFFINITY \
PsAttributeValue(PsAttributeGroupAffinity, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_PREFERRED_NODE \
PsAttributeValue(PsAttributePreferredNode, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_IDEAL_PROCESSOR \
PsAttributeValue(PsAttributeIdealProcessor, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_UMS_THREAD \
PsAttributeValue(PsAttributeUmsThread, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_MITIGATION_OPTIONS \
PsAttributeValue(PsAttributeMitigationOptions, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_PROTECTION_LEVEL \
PsAttributeValue(PsAttributeProtectionLevel, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_SECURE_PROCESS \
PsAttributeValue(PsAttributeSecureProcess, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_JOB_LIST \
PsAttributeValue(PsAttributeJobList, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_CHILD_PROCESS_POLICY \
PsAttributeValue(PsAttributeChildProcessPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY \
PsAttributeValue(PsAttributeAllApplicationPackagesPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_WIN32K_FILTER \
PsAttributeValue(PsAttributeWin32kFilter, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_SAFE_OPEN_PROMPT_ORIGIN_CLAIM \
PsAttributeValue(PsAttributeSafeOpenPromptOriginClaim, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_BNO_ISOLATION \
PsAttributeValue(PsAttributeBnoIsolation, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_DESKTOP_APP_POLICY \
PsAttributeValue(PsAttributeDesktopAppPolicy, FALSE, TRUE, FALSE)
// end_rev
// begin_private
typedef struct _PS_ATTRIBUTE
{
ULONG_PTR Attribute;
SIZE_T Size;
union
{
ULONG_PTR Value;
PVOID ValuePtr;
};
PSIZE_T ReturnLength;
} PS_ATTRIBUTE, *PPS_ATTRIBUTE;
typedef struct _PS_ATTRIBUTE_LIST
{
SIZE_T TotalLength;
PS_ATTRIBUTE Attributes[1];
} PS_ATTRIBUTE_LIST, *PPS_ATTRIBUTE_LIST;
typedef struct _PS_MEMORY_RESERVE
{
PVOID ReserveAddress;
SIZE_T ReserveSize;
} PS_MEMORY_RESERVE, *PPS_MEMORY_RESERVE;
typedef enum _PS_STD_HANDLE_STATE
{
PsNeverDuplicate,
PsRequestDuplicate, // duplicate standard handles specified by PseudoHandleMask, and only if StdHandleSubsystemType matches the image subsystem
PsAlwaysDuplicate, // always duplicate standard handles
PsMaxStdHandleStates
} PS_STD_HANDLE_STATE;
// begin_rev
#define PS_STD_INPUT_HANDLE 0x1
#define PS_STD_OUTPUT_HANDLE 0x2
#define PS_STD_ERROR_HANDLE 0x4
// end_rev
typedef struct _PS_STD_HANDLE_INFO
{
union
{
ULONG Flags;
struct
{
ULONG StdHandleState : 2; // PS_STD_HANDLE_STATE
ULONG PseudoHandleMask : 3; // PS_STD_*
};
};
ULONG StdHandleSubsystemType;
} PS_STD_HANDLE_INFO, *PPS_STD_HANDLE_INFO;
// private
typedef struct _PS_BNO_ISOLATION_PARAMETERS
{
UNICODE_STRING IsolationPrefix;
ULONG HandleCount;
PVOID *Handles;
BOOLEAN IsolationEnabled;
} PS_BNO_ISOLATION_PARAMETERS, *PPS_BNO_ISOLATION_PARAMETERS;
// private
typedef enum _PS_MITIGATION_OPTION
{
PS_MITIGATION_OPTION_NX,
PS_MITIGATION_OPTION_SEHOP,
PS_MITIGATION_OPTION_FORCE_RELOCATE_IMAGES,
PS_MITIGATION_OPTION_HEAP_TERMINATE,
PS_MITIGATION_OPTION_BOTTOM_UP_ASLR,
PS_MITIGATION_OPTION_HIGH_ENTROPY_ASLR,
PS_MITIGATION_OPTION_STRICT_HANDLE_CHECKS,
PS_MITIGATION_OPTION_WIN32K_SYSTEM_CALL_DISABLE,
PS_MITIGATION_OPTION_EXTENSION_POINT_DISABLE,
PS_MITIGATION_OPTION_PROHIBIT_DYNAMIC_CODE,
PS_MITIGATION_OPTION_CONTROL_FLOW_GUARD,
PS_MITIGATION_OPTION_BLOCK_NON_MICROSOFT_BINARIES,
PS_MITIGATION_OPTION_FONT_DISABLE,
PS_MITIGATION_OPTION_IMAGE_LOAD_NO_REMOTE,
PS_MITIGATION_OPTION_IMAGE_LOAD_NO_LOW_LABEL,
PS_MITIGATION_OPTION_IMAGE_LOAD_PREFER_SYSTEM32,
PS_MITIGATION_OPTION_RETURN_FLOW_GUARD,
PS_MITIGATION_OPTION_LOADER_INTEGRITY_CONTINUITY,
PS_MITIGATION_OPTION_STRICT_CONTROL_FLOW_GUARD,
PS_MITIGATION_OPTION_RESTRICT_SET_THREAD_CONTEXT,
PS_MITIGATION_OPTION_ROP_STACKPIVOT, // since REDSTONE3
PS_MITIGATION_OPTION_ROP_CALLER_CHECK,
PS_MITIGATION_OPTION_ROP_SIMEXEC,
PS_MITIGATION_OPTION_EXPORT_ADDRESS_FILTER,
PS_MITIGATION_OPTION_EXPORT_ADDRESS_FILTER_PLUS,
PS_MITIGATION_OPTION_RESTRICT_CHILD_PROCESS_CREATION,
PS_MITIGATION_OPTION_IMPORT_ADDRESS_FILTER,
PS_MITIGATION_OPTION_MODULE_TAMPERING_PROTECTION,
PS_MITIGATION_OPTION_RESTRICT_INDIRECT_BRANCH_PREDICTION,
PS_MITIGATION_OPTION_SPECULATIVE_STORE_BYPASS_DISABLE, // since REDSTONE5
PS_MITIGATION_OPTION_ALLOW_DOWNGRADE_DYNAMIC_CODE_POLICY,
PS_MITIGATION_OPTION_CET_SHADOW_STACKS
} PS_MITIGATION_OPTION;
// windows-internals-book:"Chapter 5"
typedef enum _PS_CREATE_STATE
{
PsCreateInitialState,
PsCreateFailOnFileOpen,
PsCreateFailOnSectionCreate,
PsCreateFailExeFormat,
PsCreateFailMachineMismatch,
PsCreateFailExeName, // Debugger specified
PsCreateSuccess,
PsCreateMaximumStates
} PS_CREATE_STATE;
typedef struct _PS_CREATE_INFO
{
SIZE_T Size;
PS_CREATE_STATE State;
union
{
// PsCreateInitialState
struct
{
union
{
ULONG InitFlags;
struct
{
UCHAR WriteOutputOnExit : 1;
UCHAR DetectManifest : 1;
UCHAR IFEOSkipDebugger : 1;
UCHAR IFEODoNotPropagateKeyState : 1;
UCHAR SpareBits1 : 4;
UCHAR SpareBits2 : 8;
USHORT ProhibitedImageCharacteristics : 16;
};
};
ACCESS_MASK AdditionalFileAccess;
} InitState;
// PsCreateFailOnSectionCreate
struct
{
HANDLE FileHandle;
} FailSection;
// PsCreateFailExeFormat
struct
{
USHORT DllCharacteristics;
} ExeFormat;
// PsCreateFailExeName
struct
{
HANDLE IFEOKey;
} ExeName;
// PsCreateSuccess
struct
{
union
{
ULONG OutputFlags;
struct
{
UCHAR ProtectedProcess : 1;
UCHAR AddressSpaceOverride : 1;
UCHAR DevOverrideEnabled : 1; // from Image File Execution Options
UCHAR ManifestDetected : 1;
UCHAR ProtectedProcessLight : 1;
UCHAR SpareBits1 : 3;
UCHAR SpareBits2 : 8;
USHORT SpareBits3 : 16;
};
};
HANDLE FileHandle;
HANDLE SectionHandle;
ULONGLONG UserProcessParametersNative;
ULONG UserProcessParametersWow64;
ULONG CurrentParameterFlags;
ULONGLONG PebAddressNative;
ULONG PebAddressWow64;
ULONGLONG ManifestAddress;
ULONG ManifestSize;
} SuccessState;
};
} PS_CREATE_INFO, *PPS_CREATE_INFO;
// end_private
// begin_rev
#define PROCESS_CREATE_FLAGS_BREAKAWAY 0x00000001
#define PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT 0x00000002
#define PROCESS_CREATE_FLAGS_INHERIT_HANDLES 0x00000004
#define PROCESS_CREATE_FLAGS_OVERRIDE_ADDRESS_SPACE 0x00000008
#define PROCESS_CREATE_FLAGS_LARGE_PAGES 0x00000010
#define PROCESS_CREATE_FLAGS_LARGE_PAGE_SYSTEM_DLL 0x00000020
// Extended PROCESS_CREATE_FLAGS_*
#define PROCESS_CREATE_FLAGS_PROTECTED_PROCESS 0x00000040
#define PROCESS_CREATE_FLAGS_CREATE_SESSION 0x00000080 // ?
#define PROCESS_CREATE_FLAGS_INHERIT_FROM_PARENT 0x00000100
#define PROCESS_CREATE_FLAGS_SUSPENDED 0x00000200
#define PROCESS_CREATE_FLAGS_EXTENDED_UNKNOWN 0x00000400
// end_rev
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateUserProcess(
_Out_ PHANDLE ProcessHandle,
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK ProcessDesiredAccess,
_In_ ACCESS_MASK ThreadDesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ProcessObjectAttributes,
_In_opt_ POBJECT_ATTRIBUTES ThreadObjectAttributes,
_In_ ULONG ProcessFlags, // PROCESS_CREATE_FLAGS_*
_In_ ULONG ThreadFlags, // THREAD_CREATE_FLAGS_*
_In_opt_ PVOID ProcessParameters, // PRTL_USER_PROCESS_PARAMETERS
_Inout_ PPS_CREATE_INFO CreateInfo,
_In_opt_ PPS_ATTRIBUTE_LIST AttributeList
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateUserProcess(
_Out_ PHANDLE ProcessHandle,
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK ProcessDesiredAccess,
_In_ ACCESS_MASK ThreadDesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ProcessObjectAttributes,
_In_opt_ POBJECT_ATTRIBUTES ThreadObjectAttributes,
_In_ ULONG ProcessFlags, // PROCESS_CREATE_FLAGS_*
_In_ ULONG ThreadFlags, // THREAD_CREATE_FLAGS_*
_In_opt_ PVOID ProcessParameters, // PRTL_USER_PROCESS_PARAMETERS
_Inout_ PPS_CREATE_INFO CreateInfo,
_In_opt_ PPS_ATTRIBUTE_LIST AttributeList
);
#endif
// begin_rev
#define THREAD_CREATE_FLAGS_CREATE_SUSPENDED 0x00000001
#define THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH 0x00000002 // ?
#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004
#define THREAD_CREATE_FLAGS_HAS_SECURITY_DESCRIPTOR 0x00000010 // ?
#define THREAD_CREATE_FLAGS_ACCESS_CHECK_IN_TARGET 0x00000020 // ?
#define THREAD_CREATE_FLAGS_INITIAL_THREAD 0x00000080
// end_rev
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateThreadEx(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ProcessHandle,
_In_ PVOID StartRoutine, // PUSER_THREAD_START_ROUTINE
_In_opt_ PVOID Argument,
_In_ ULONG CreateFlags, // THREAD_CREATE_FLAGS_*
_In_ SIZE_T ZeroBits,
_In_ SIZE_T StackSize,
_In_ SIZE_T MaximumStackSize,
_In_opt_ PPS_ATTRIBUTE_LIST AttributeList
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateThreadEx(
_Out_ PHANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE ProcessHandle,
_In_ PVOID StartRoutine, // PUSER_THREAD_START_ROUTINE
_In_opt_ PVOID Argument,
_In_ ULONG CreateFlags, // THREAD_CREATE_FLAGS_*
_In_ SIZE_T ZeroBits,
_In_ SIZE_T StackSize,
_In_ SIZE_T MaximumStackSize,
_In_opt_ PPS_ATTRIBUTE_LIST AttributeList
);
#endif
// Job objects
// JOBOBJECTINFOCLASS
// Note: We don't use an enum since it conflicts with the Windows SDK.
#define JobObjectBasicAccountingInformation 1 // JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
#define JobObjectBasicLimitInformation 2 // JOBOBJECT_BASIC_LIMIT_INFORMATION
#define JobObjectBasicProcessIdList 3 // JOBOBJECT_BASIC_PROCESS_ID_LIST
#define JobObjectBasicUIRestrictions 4 // JOBOBJECT_BASIC_UI_RESTRICTIONS
#define JobObjectSecurityLimitInformation 5 // JOBOBJECT_SECURITY_LIMIT_INFORMATION
#define JobObjectEndOfJobTimeInformation 6 // JOBOBJECT_END_OF_JOB_TIME_INFORMATION
#define JobObjectAssociateCompletionPortInformation 7 // JOBOBJECT_ASSOCIATE_COMPLETION_PORT
#define JobObjectBasicAndIoAccountingInformation 8 // JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION
#define JobObjectExtendedLimitInformation 9 // JOBOBJECT_EXTENDED_LIMIT_INFORMATION
#define JobObjectJobSetInformation 10 // JOBOBJECT_JOBSET_INFORMATION
#define JobObjectGroupInformation 11 // USHORT
#define JobObjectNotificationLimitInformation 12 // JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION
#define JobObjectLimitViolationInformation 13 // JOBOBJECT_LIMIT_VIOLATION_INFORMATION
#define JobObjectGroupInformationEx 14 // GROUP_AFFINITY (ARRAY)
#define JobObjectCpuRateControlInformation 15 // JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
#define JobObjectCompletionFilter 16
#define JobObjectCompletionCounter 17
#define JobObjectFreezeInformation 18 // JOBOBJECT_FREEZE_INFORMATION
#define JobObjectExtendedAccountingInformation 19 // JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION
#define JobObjectWakeInformation 20 // JOBOBJECT_WAKE_INFORMATION
#define JobObjectBackgroundInformation 21
#define JobObjectSchedulingRankBiasInformation 22
#define JobObjectTimerVirtualizationInformation 23
#define JobObjectCycleTimeNotification 24
#define JobObjectClearEvent 25
#define JobObjectInterferenceInformation 26 // JOBOBJECT_INTERFERENCE_INFORMATION
#define JobObjectClearPeakJobMemoryUsed 27
#define JobObjectMemoryUsageInformation 28 // JOBOBJECT_MEMORY_USAGE_INFORMATION // JOBOBJECT_MEMORY_USAGE_INFORMATION_V2
#define JobObjectSharedCommit 29
#define JobObjectContainerId 30
#define JobObjectIoRateControlInformation 31
#define JobObjectNetRateControlInformation 32 // JOBOBJECT_NET_RATE_CONTROL_INFORMATION
#define JobObjectNotificationLimitInformation2 33 // JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2
#define JobObjectLimitViolationInformation2 34 // JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2
#define JobObjectCreateSilo 35
#define JobObjectSiloBasicInformation 36 // SILOOBJECT_BASIC_INFORMATION
#define JobObjectSiloRootDirectory 37 // SILOOBJECT_ROOT_DIRECTORY
#define JobObjectServerSiloBasicInformation 38 // SERVERSILO_BASIC_INFORMATION
#define JobObjectServerSiloUserSharedData 39 // SILO_USER_SHARED_DATA
#define JobObjectServerSiloInitialize 40
#define JobObjectServerSiloRunningState 41
#define JobObjectIoAttribution 42
#define JobObjectMemoryPartitionInformation 43
#define JobObjectContainerTelemetryId 44
#define JobObjectSiloSystemRoot 45
#define JobObjectEnergyTrackingState 46 // JOBOBJECT_ENERGY_TRACKING_STATE
#define JobObjectThreadImpersonationInformation 47
#define MaxJobObjectInfoClass 48
// private
typedef struct _JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION
{
JOBOBJECT_BASIC_ACCOUNTING_INFORMATION BasicInfo;
IO_COUNTERS IoInfo;
PROCESS_DISK_COUNTERS DiskIoInfo;
ULONG64 ContextSwitches;
LARGE_INTEGER TotalCycleTime;
ULONG64 ReadyTime;
PROCESS_ENERGY_VALUES EnergyValues;
} JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION, *PJOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION;
// private
typedef struct _JOBOBJECT_WAKE_INFORMATION
{
HANDLE NotificationChannel;
ULONG64 WakeCounters[7];
} JOBOBJECT_WAKE_INFORMATION, *PJOBOBJECT_WAKE_INFORMATION;
// private
typedef struct _JOBOBJECT_WAKE_INFORMATION_V1
{
HANDLE NotificationChannel;
ULONG64 WakeCounters[4];
} JOBOBJECT_WAKE_INFORMATION_V1, *PJOBOBJECT_WAKE_INFORMATION_V1;
// private
typedef struct _JOBOBJECT_INTERFERENCE_INFORMATION
{
ULONG64 Count;
} JOBOBJECT_INTERFERENCE_INFORMATION, *PJOBOBJECT_INTERFERENCE_INFORMATION;
// private
typedef struct _JOBOBJECT_WAKE_FILTER
{
ULONG HighEdgeFilter;
ULONG LowEdgeFilter;
} JOBOBJECT_WAKE_FILTER, *PJOBOBJECT_WAKE_FILTER;
// private
typedef struct _JOBOBJECT_FREEZE_INFORMATION
{
union
{
ULONG Flags;
struct
{
ULONG FreezeOperation : 1;
ULONG FilterOperation : 1;
ULONG SwapOperation : 1;
ULONG Reserved : 29;
};
};
BOOLEAN Freeze;
BOOLEAN Swap;
UCHAR Reserved0[2];
JOBOBJECT_WAKE_FILTER WakeFilter;
} JOBOBJECT_FREEZE_INFORMATION, *PJOBOBJECT_FREEZE_INFORMATION;
// private
typedef struct _JOBOBJECT_MEMORY_USAGE_INFORMATION
{
ULONG64 JobMemory;
ULONG64 PeakJobMemoryUsed;
} JOBOBJECT_MEMORY_USAGE_INFORMATION, *PJOBOBJECT_MEMORY_USAGE_INFORMATION;
// private
typedef struct _JOBOBJECT_MEMORY_USAGE_INFORMATION_V2
{
JOBOBJECT_MEMORY_USAGE_INFORMATION BasicInfo;
ULONG64 JobSharedMemory;
ULONG64 Reserved[2];
} JOBOBJECT_MEMORY_USAGE_INFORMATION_V2, *PJOBOBJECT_MEMORY_USAGE_INFORMATION_V2;
// private
typedef struct _SILO_USER_SHARED_DATA
{
ULONG64 ServiceSessionId;
ULONG ActiveConsoleId;
LONGLONG ConsoleSessionForegroundProcessId;
NT_PRODUCT_TYPE NtProductType;
ULONG SuiteMask;
ULONG SharedUserSessionId;
BOOLEAN IsMultiSessionSku;
WCHAR NtSystemRoot[260];
USHORT UserModeGlobalLogger[16];
} SILO_USER_SHARED_DATA, *PSILO_USER_SHARED_DATA;
// private
typedef struct _SILOOBJECT_ROOT_DIRECTORY
{
ULONG ControlFlags;
UNICODE_STRING Path;
} SILOOBJECT_ROOT_DIRECTORY, *PSILOOBJECT_ROOT_DIRECTORY;
// private
typedef struct _JOBOBJECT_ENERGY_TRACKING_STATE
{
ULONG64 Value;
ULONG UpdateMask;
ULONG DesiredState;
} JOBOBJECT_ENERGY_TRACKING_STATE, *PJOBOBJECT_ENERGY_TRACKING_STATE;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateJobObject(
_Out_ PHANDLE JobHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateJobObject(
_Out_ PHANDLE JobHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenJobObject(
_Out_ PHANDLE JobHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenJobObject(
_Out_ PHANDLE JobHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAssignProcessToJobObject(
_In_ HANDLE JobHandle,
_In_ HANDLE ProcessHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAssignProcessToJobObject(
_In_ HANDLE JobHandle,
_In_ HANDLE ProcessHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTerminateJobObject(
_In_ HANDLE JobHandle,
_In_ NTSTATUS ExitStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTerminateJobObject(
_In_ HANDLE JobHandle,
_In_ NTSTATUS ExitStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtIsProcessInJob(
_In_ HANDLE ProcessHandle,
_In_opt_ HANDLE JobHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwIsProcessInJob(
_In_ HANDLE ProcessHandle,
_In_opt_ HANDLE JobHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationJobObject(
_In_opt_ HANDLE JobHandle,
_In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
_Out_writes_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
_In_ ULONG JobObjectInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationJobObject(
_In_opt_ HANDLE JobHandle,
_In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
_Out_writes_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
_In_ ULONG JobObjectInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationJobObject(
_In_ HANDLE JobHandle,
_In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
_In_reads_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
_In_ ULONG JobObjectInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationJobObject(
_In_ HANDLE JobHandle,
_In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
_In_reads_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
_In_ ULONG JobObjectInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateJobSet(
_In_ ULONG NumJob,
_In_reads_(NumJob) PJOB_SET_ARRAY UserJobSet,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateJobSet(
_In_ ULONG NumJob,
_In_reads_(NumJob) PJOB_SET_ARRAY UserJobSet,
_In_ ULONG Flags
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRevertContainerImpersonation(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRevertContainerImpersonation(
VOID
);
#endif
// Reserve objects
// private
typedef enum _MEMORY_RESERVE_TYPE
{
MemoryReserveUserApc,
MemoryReserveIoCompletion,
MemoryReserveTypeMax
} MEMORY_RESERVE_TYPE;
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAllocateReserveObject(
_Out_ PHANDLE MemoryReserveHandle,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ MEMORY_RESERVE_TYPE Type
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAllocateReserveObject(
_Out_ PHANDLE MemoryReserveHandle,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ MEMORY_RESERVE_TYPE Type
);
#endif
#include <cfg.h>
// #include <ntdbg.h>
// Debugging
NTSYSAPI
VOID
NTAPI
DbgUserBreakPoint(
VOID
);
NTSYSAPI
VOID
NTAPI
DbgBreakPoint(
VOID
);
NTSYSAPI
VOID
NTAPI
DbgBreakPointWithStatus(
_In_ ULONG Status
);
#define DBG_STATUS_CONTROL_C 1
#define DBG_STATUS_SYSRQ 2
#define DBG_STATUS_BUGCHECK_FIRST 3
#define DBG_STATUS_BUGCHECK_SECOND 4
#define DBG_STATUS_FATAL 5
#define DBG_STATUS_DEBUG_CONTROL 6
#define DBG_STATUS_WORKER 7
NTSYSAPI
ULONG
STDAPIVCALLTYPE
DbgPrint(
_In_z_ _Printf_format_string_ PSTR Format,
...
);
NTSYSAPI
ULONG
STDAPIVCALLTYPE
DbgPrintEx(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_z_ _Printf_format_string_ PSTR Format,
...
);
NTSYSAPI
ULONG
NTAPI
vDbgPrintEx(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_z_ PCH Format,
_In_ va_list arglist
);
NTSYSAPI
ULONG
NTAPI
vDbgPrintExWithPrefix(
_In_z_ PCH Prefix,
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_z_ PCH Format,
_In_ va_list arglist
);
NTSYSAPI
NTSTATUS
NTAPI
DbgQueryDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level
);
NTSYSAPI
NTSTATUS
NTAPI
DbgSetDebugFilterState(
_In_ ULONG ComponentId,
_In_ ULONG Level,
_In_ BOOLEAN State
);
NTSYSAPI
ULONG
NTAPI
DbgPrompt(
_In_ PCH Prompt,
_Out_writes_bytes_(Length) PCH Response,
_In_ ULONG Length
);
// Definitions
typedef struct _DBGKM_EXCEPTION
{
EXCEPTION_RECORD ExceptionRecord;
ULONG FirstChance;
} DBGKM_EXCEPTION, *PDBGKM_EXCEPTION;
typedef struct _DBGKM_CREATE_THREAD
{
ULONG SubSystemKey;
PVOID StartAddress;
} DBGKM_CREATE_THREAD, *PDBGKM_CREATE_THREAD;
typedef struct _DBGKM_CREATE_PROCESS
{
ULONG SubSystemKey;
HANDLE FileHandle;
PVOID BaseOfImage;
ULONG DebugInfoFileOffset;
ULONG DebugInfoSize;
DBGKM_CREATE_THREAD InitialThread;
} DBGKM_CREATE_PROCESS, *PDBGKM_CREATE_PROCESS;
typedef struct _DBGKM_EXIT_THREAD
{
NTSTATUS ExitStatus;
} DBGKM_EXIT_THREAD, *PDBGKM_EXIT_THREAD;
typedef struct _DBGKM_EXIT_PROCESS
{
NTSTATUS ExitStatus;
} DBGKM_EXIT_PROCESS, *PDBGKM_EXIT_PROCESS;
typedef struct _DBGKM_LOAD_DLL
{
HANDLE FileHandle;
PVOID BaseOfDll;
ULONG DebugInfoFileOffset;
ULONG DebugInfoSize;
PVOID NamePointer;
} DBGKM_LOAD_DLL, *PDBGKM_LOAD_DLL;
typedef struct _DBGKM_UNLOAD_DLL
{
PVOID BaseAddress;
} DBGKM_UNLOAD_DLL, *PDBGKM_UNLOAD_DLL;
typedef enum _DBG_STATE
{
DbgIdle,
DbgReplyPending,
DbgCreateThreadStateChange,
DbgCreateProcessStateChange,
DbgExitThreadStateChange,
DbgExitProcessStateChange,
DbgExceptionStateChange,
DbgBreakpointStateChange,
DbgSingleStepStateChange,
DbgLoadDllStateChange,
DbgUnloadDllStateChange
} DBG_STATE, *PDBG_STATE;
typedef struct _DBGUI_CREATE_THREAD
{
HANDLE HandleToThread;
DBGKM_CREATE_THREAD NewThread;
} DBGUI_CREATE_THREAD, *PDBGUI_CREATE_THREAD;
typedef struct _DBGUI_CREATE_PROCESS
{
HANDLE HandleToProcess;
HANDLE HandleToThread;
DBGKM_CREATE_PROCESS NewProcess;
} DBGUI_CREATE_PROCESS, *PDBGUI_CREATE_PROCESS;
typedef struct _DBGUI_WAIT_STATE_CHANGE
{
DBG_STATE NewState;
CLIENT_ID AppClientId;
union
{
DBGKM_EXCEPTION Exception;
DBGUI_CREATE_THREAD CreateThread;
DBGUI_CREATE_PROCESS CreateProcessInfo;
DBGKM_EXIT_THREAD ExitThread;
DBGKM_EXIT_PROCESS ExitProcess;
DBGKM_LOAD_DLL LoadDll;
DBGKM_UNLOAD_DLL UnloadDll;
} StateInfo;
} DBGUI_WAIT_STATE_CHANGE, *PDBGUI_WAIT_STATE_CHANGE;
#define DEBUG_READ_EVENT 0x0001
#define DEBUG_PROCESS_ASSIGN 0x0002
#define DEBUG_SET_INFORMATION 0x0004
#define DEBUG_QUERY_INFORMATION 0x0008
#define DEBUG_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
DEBUG_READ_EVENT | DEBUG_PROCESS_ASSIGN | DEBUG_SET_INFORMATION | \
DEBUG_QUERY_INFORMATION)
#define DEBUG_KILL_ON_CLOSE 0x1
typedef enum _DEBUGOBJECTINFOCLASS
{
DebugObjectUnusedInformation,
DebugObjectKillProcessOnExitInformation,
MaxDebugObjectInfoClass
} DEBUGOBJECTINFOCLASS, *PDEBUGOBJECTINFOCLASS;
// System calls
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateDebugObject(
_Out_ PHANDLE DebugObjectHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateDebugObject(
_Out_ PHANDLE DebugObjectHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDebugActiveProcess(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDebugActiveProcess(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDebugContinue(
_In_ HANDLE DebugObjectHandle,
_In_ PCLIENT_ID ClientId,
_In_ NTSTATUS ContinueStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDebugContinue(
_In_ HANDLE DebugObjectHandle,
_In_ PCLIENT_ID ClientId,
_In_ NTSTATUS ContinueStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRemoveProcessDebug(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRemoveProcessDebug(
_In_ HANDLE ProcessHandle,
_In_ HANDLE DebugObjectHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationDebugObject(
_In_ HANDLE DebugObjectHandle,
_In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
_In_ PVOID DebugInformation,
_In_ ULONG DebugInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationDebugObject(
_In_ HANDLE DebugObjectHandle,
_In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
_In_ PVOID DebugInformation,
_In_ ULONG DebugInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWaitForDebugEvent(
_In_ HANDLE DebugObjectHandle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout,
_Out_ PVOID WaitStateChange
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWaitForDebugEvent(
_In_ HANDLE DebugObjectHandle,
_In_ BOOLEAN Alertable,
_In_opt_ PLARGE_INTEGER Timeout,
_Out_ PVOID WaitStateChange
);
// Debugging UI
NTSYSAPI
NTSTATUS
NTAPI
DbgUiConnectToDbg(
VOID
);
NTSYSAPI
HANDLE
NTAPI
DbgUiGetThreadDebugObject(
VOID
);
NTSYSAPI
VOID
NTAPI
DbgUiSetThreadDebugObject(
_In_ HANDLE DebugObject
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiWaitStateChange(
_Out_ PDBGUI_WAIT_STATE_CHANGE StateChange,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiContinue(
_In_ PCLIENT_ID AppClientId,
_In_ NTSTATUS ContinueStatus
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiStopDebugging(
_In_ HANDLE Process
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiDebugActiveProcess(
_In_ HANDLE Process
);
NTSYSAPI
VOID
NTAPI
DbgUiRemoteBreakin(
_In_ PVOID Context
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiIssueRemoteBreakin(
_In_ HANDLE Process
);
NTSYSAPI
NTSTATUS
NTAPI
DbgUiConvertStateChangeStructure(
_In_ PDBGUI_WAIT_STATE_CHANGE StateChange,
_Out_ LPDEBUG_EVENT DebugEvent
);
struct _EVENT_FILTER_DESCRIPTOR;
typedef VOID (NTAPI *PENABLECALLBACK)(
_In_ LPCGUID SourceId,
_In_ ULONG IsEnabled,
_In_ UCHAR Level,
_In_ ULONGLONG MatchAnyKeyword,
_In_ ULONGLONG MatchAllKeyword,
_In_opt_ struct _EVENT_FILTER_DESCRIPTOR *FilterData,
_Inout_opt_ PVOID CallbackContext
);
typedef ULONGLONG REGHANDLE, *PREGHANDLE;
NTSYSAPI
NTSTATUS
NTAPI
EtwEventRegister(
_In_ LPCGUID ProviderId,
_In_opt_ PENABLECALLBACK EnableCallback,
_In_opt_ PVOID CallbackContext,
_Out_ PREGHANDLE RegHandle
);
// #include <ntioapi.h>
// Create disposition
#define FILE_SUPERSEDE 0x00000000
#define FILE_OPEN 0x00000001
#define FILE_CREATE 0x00000002
#define FILE_OPEN_IF 0x00000003
#define FILE_OVERWRITE 0x00000004
#define FILE_OVERWRITE_IF 0x00000005
#define FILE_MAXIMUM_DISPOSITION 0x00000005
// Create/open flags
#define FILE_DIRECTORY_FILE 0x00000001
#define FILE_WRITE_THROUGH 0x00000002
#define FILE_SEQUENTIAL_ONLY 0x00000004
#define FILE_NO_INTERMEDIATE_BUFFERING 0x00000008
#define FILE_SYNCHRONOUS_IO_ALERT 0x00000010
#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020
#define FILE_NON_DIRECTORY_FILE 0x00000040
#define FILE_CREATE_TREE_CONNECTION 0x00000080
#define FILE_COMPLETE_IF_OPLOCKED 0x00000100
#define FILE_NO_EA_KNOWLEDGE 0x00000200
#define FILE_OPEN_FOR_RECOVERY 0x00000400
#define FILE_RANDOM_ACCESS 0x00000800
#define FILE_DELETE_ON_CLOSE 0x00001000
#define FILE_OPEN_BY_FILE_ID 0x00002000
#define FILE_OPEN_FOR_BACKUP_INTENT 0x00004000
#define FILE_NO_COMPRESSION 0x00008000
#if (NTDDI_VERSION >= NTDDI_WIN7)
#define FILE_OPEN_REQUIRING_OPLOCK 0x00010000
#define FILE_DISALLOW_EXCLUSIVE 0x00020000
#endif
#if (NTDDI_VERSION >= NTDDI_WIN8)
#define FILE_SESSION_AWARE 0x00040000
#endif
#define FILE_RESERVE_OPFILTER 0x00100000
#define FILE_OPEN_REPARSE_POINT 0x00200000
#define FILE_OPEN_NO_RECALL 0x00400000
#define FILE_OPEN_FOR_FREE_SPACE_QUERY 0x00800000
#define FILE_COPY_STRUCTURED_STORAGE 0x00000041
#define FILE_STRUCTURED_STORAGE 0x00000441
// I/O status information values for NtCreateFile/NtOpenFile
#define FILE_SUPERSEDED 0x00000000
#define FILE_OPENED 0x00000001
#define FILE_CREATED 0x00000002
#define FILE_OVERWRITTEN 0x00000003
#define FILE_EXISTS 0x00000004
#define FILE_DOES_NOT_EXIST 0x00000005
// Special ByteOffset parameters
#define FILE_WRITE_TO_END_OF_FILE 0xffffffff
#define FILE_USE_FILE_POINTER_POSITION 0xfffffffe
// Alignment requirement values
#define FILE_BYTE_ALIGNMENT 0x00000000
#define FILE_WORD_ALIGNMENT 0x00000001
#define FILE_LONG_ALIGNMENT 0x00000003
#define FILE_QUAD_ALIGNMENT 0x00000007
#define FILE_OCTA_ALIGNMENT 0x0000000f
#define FILE_32_BYTE_ALIGNMENT 0x0000001f
#define FILE_64_BYTE_ALIGNMENT 0x0000003f
#define FILE_128_BYTE_ALIGNMENT 0x0000007f
#define FILE_256_BYTE_ALIGNMENT 0x000000ff
#define FILE_512_BYTE_ALIGNMENT 0x000001ff
// Maximum length of a filename string
#define MAXIMUM_FILENAME_LENGTH 256
// Extended attributes
#define FILE_NEED_EA 0x00000080
#define FILE_EA_TYPE_BINARY 0xfffe
#define FILE_EA_TYPE_ASCII 0xfffd
#define FILE_EA_TYPE_BITMAP 0xfffb
#define FILE_EA_TYPE_METAFILE 0xfffa
#define FILE_EA_TYPE_ICON 0xfff9
#define FILE_EA_TYPE_EA 0xffee
#define FILE_EA_TYPE_MVMT 0xffdf
#define FILE_EA_TYPE_MVST 0xffde
#define FILE_EA_TYPE_ASN1 0xffdd
#define FILE_EA_TYPE_FAMILY_IDS 0xff01
// Device characteristics
#define FILE_REMOVABLE_MEDIA 0x00000001
#define FILE_READ_ONLY_DEVICE 0x00000002
#define FILE_FLOPPY_DISKETTE 0x00000004
#define FILE_WRITE_ONCE_MEDIA 0x00000008
#define FILE_REMOTE_DEVICE 0x00000010
#define FILE_DEVICE_IS_MOUNTED 0x00000020
#define FILE_VIRTUAL_VOLUME 0x00000040
#define FILE_AUTOGENERATED_DEVICE_NAME 0x00000080
#define FILE_DEVICE_SECURE_OPEN 0x00000100
#define FILE_CHARACTERISTIC_PNP_DEVICE 0x00000800
#define FILE_CHARACTERISTIC_TS_DEVICE 0x00001000
#define FILE_CHARACTERISTIC_WEBDAV_DEVICE 0x00002000
#define FILE_CHARACTERISTIC_CSV 0x00010000
#define FILE_DEVICE_ALLOW_APPCONTAINER_TRAVERSAL 0x00020000
#define FILE_PORTABLE_DEVICE 0x00040000
// Named pipe values
// NamedPipeType for NtCreateNamedPipeFile
#define FILE_PIPE_BYTE_STREAM_TYPE 0x00000000
#define FILE_PIPE_MESSAGE_TYPE 0x00000001
#define FILE_PIPE_ACCEPT_REMOTE_CLIENTS 0x00000000
#define FILE_PIPE_REJECT_REMOTE_CLIENTS 0x00000002
#define FILE_PIPE_TYPE_VALID_MASK 0x00000003
// CompletionMode for NtCreateNamedPipeFile
#define FILE_PIPE_QUEUE_OPERATION 0x00000000
#define FILE_PIPE_COMPLETE_OPERATION 0x00000001
// ReadMode for NtCreateNamedPipeFile
#define FILE_PIPE_BYTE_STREAM_MODE 0x00000000
#define FILE_PIPE_MESSAGE_MODE 0x00000001
// NamedPipeConfiguration for NtQueryInformationFile
#define FILE_PIPE_INBOUND 0x00000000
#define FILE_PIPE_OUTBOUND 0x00000001
#define FILE_PIPE_FULL_DUPLEX 0x00000002
// NamedPipeState for NtQueryInformationFile
#define FILE_PIPE_DISCONNECTED_STATE 0x00000001
#define FILE_PIPE_LISTENING_STATE 0x00000002
#define FILE_PIPE_CONNECTED_STATE 0x00000003
#define FILE_PIPE_CLOSING_STATE 0x00000004
// NamedPipeEnd for NtQueryInformationFile
#define FILE_PIPE_CLIENT_END 0x00000000
#define FILE_PIPE_SERVER_END 0x00000001
// Mailslot values
#define MAILSLOT_SIZE_AUTO 0
typedef struct _IO_STATUS_BLOCK
{
union
{
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Information;
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
typedef VOID (NTAPI *PIO_APC_ROUTINE)(
_In_ PVOID ApcContext,
_In_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG Reserved
);
// private
typedef struct _FILE_IO_COMPLETION_INFORMATION
{
PVOID KeyContext;
PVOID ApcContext;
IO_STATUS_BLOCK IoStatusBlock;
} FILE_IO_COMPLETION_INFORMATION, *PFILE_IO_COMPLETION_INFORMATION;
typedef enum _FILE_INFORMATION_CLASS
{
FileDirectoryInformation = 1, // FILE_DIRECTORY_INFORMATION
FileFullDirectoryInformation, // FILE_FULL_DIR_INFORMATION
FileBothDirectoryInformation, // FILE_BOTH_DIR_INFORMATION
FileBasicInformation, // FILE_BASIC_INFORMATION
FileStandardInformation, // FILE_STANDARD_INFORMATION
FileInternalInformation, // FILE_INTERNAL_INFORMATION
FileEaInformation, // FILE_EA_INFORMATION
FileAccessInformation, // FILE_ACCESS_INFORMATION
FileNameInformation, // FILE_NAME_INFORMATION
FileRenameInformation, // FILE_RENAME_INFORMATION // 10
FileLinkInformation, // FILE_LINK_INFORMATION
FileNamesInformation, // FILE_NAMES_INFORMATION
FileDispositionInformation, // FILE_DISPOSITION_INFORMATION
FilePositionInformation, // FILE_POSITION_INFORMATION
FileFullEaInformation, // FILE_FULL_EA_INFORMATION
FileModeInformation, // FILE_MODE_INFORMATION
FileAlignmentInformation, // FILE_ALIGNMENT_INFORMATION
FileAllInformation, // FILE_ALL_INFORMATION
FileAllocationInformation, // FILE_ALLOCATION_INFORMATION
FileEndOfFileInformation, // FILE_END_OF_FILE_INFORMATION // 20
FileAlternateNameInformation, // FILE_NAME_INFORMATION
FileStreamInformation, // FILE_STREAM_INFORMATION
FilePipeInformation, // FILE_PIPE_INFORMATION
FilePipeLocalInformation, // FILE_PIPE_LOCAL_INFORMATION
FilePipeRemoteInformation, // FILE_PIPE_REMOTE_INFORMATION
FileMailslotQueryInformation, // FILE_MAILSLOT_QUERY_INFORMATION
FileMailslotSetInformation, // FILE_MAILSLOT_SET_INFORMATION
FileCompressionInformation, // FILE_COMPRESSION_INFORMATION
FileObjectIdInformation, // FILE_OBJECTID_INFORMATION
FileCompletionInformation, // FILE_COMPLETION_INFORMATION // 30
FileMoveClusterInformation, // FILE_MOVE_CLUSTER_INFORMATION
FileQuotaInformation, // FILE_QUOTA_INFORMATION
FileReparsePointInformation, // FILE_REPARSE_POINT_INFORMATION
FileNetworkOpenInformation, // FILE_NETWORK_OPEN_INFORMATION
FileAttributeTagInformation, // FILE_ATTRIBUTE_TAG_INFORMATION
FileTrackingInformation, // FILE_TRACKING_INFORMATION
FileIdBothDirectoryInformation, // FILE_ID_BOTH_DIR_INFORMATION
FileIdFullDirectoryInformation, // FILE_ID_FULL_DIR_INFORMATION
FileValidDataLengthInformation, // FILE_VALID_DATA_LENGTH_INFORMATION
FileShortNameInformation, // FILE_NAME_INFORMATION // 40
FileIoCompletionNotificationInformation, // FILE_IO_COMPLETION_NOTIFICATION_INFORMATION // since VISTA
FileIoStatusBlockRangeInformation, // FILE_IOSTATUSBLOCK_RANGE_INFORMATION
FileIoPriorityHintInformation, // FILE_IO_PRIORITY_HINT_INFORMATION
FileSfioReserveInformation, // FILE_SFIO_RESERVE_INFORMATION
FileSfioVolumeInformation, // FILE_SFIO_VOLUME_INFORMATION
FileHardLinkInformation, // FILE_LINKS_INFORMATION
FileProcessIdsUsingFileInformation, // FILE_PROCESS_IDS_USING_FILE_INFORMATION
FileNormalizedNameInformation, // FILE_NAME_INFORMATION
FileNetworkPhysicalNameInformation, // FILE_NETWORK_PHYSICAL_NAME_INFORMATION
FileIdGlobalTxDirectoryInformation, // FILE_ID_GLOBAL_TX_DIR_INFORMATION // since WIN7 // 50
FileIsRemoteDeviceInformation, // FILE_IS_REMOTE_DEVICE_INFORMATION
FileUnusedInformation,
FileNumaNodeInformation, // FILE_NUMA_NODE_INFORMATION
FileStandardLinkInformation, // FILE_STANDARD_LINK_INFORMATION
FileRemoteProtocolInformation, // FILE_REMOTE_PROTOCOL_INFORMATION
FileRenameInformationBypassAccessCheck, // (kernel-mode only); FILE_RENAME_INFORMATION // since WIN8
FileLinkInformationBypassAccessCheck, // (kernel-mode only); FILE_LINK_INFORMATION
FileVolumeNameInformation, // FILE_VOLUME_NAME_INFORMATION
FileIdInformation, // FILE_ID_INFORMATION
FileIdExtdDirectoryInformation, // FILE_ID_EXTD_DIR_INFORMATION // 60
FileReplaceCompletionInformation, // FILE_COMPLETION_INFORMATION // since WINBLUE
FileHardLinkFullIdInformation, // FILE_LINK_ENTRY_FULL_ID_INFORMATION
FileIdExtdBothDirectoryInformation, // FILE_ID_EXTD_BOTH_DIR_INFORMATION // since THRESHOLD
FileDispositionInformationEx, // FILE_DISPOSITION_INFO_EX // since REDSTONE
FileRenameInformationEx, // FILE_RENAME_INFORMATION
FileRenameInformationExBypassAccessCheck, // FILE_RENAME_INFORMATION
FileDesiredStorageClassInformation, // FILE_DESIRED_STORAGE_CLASS_INFORMATION // since REDSTONE2
FileStatInformation, // FILE_STAT_INFORMATION
FileMemoryPartitionInformation, // FILE_MEMORY_PARTITION_INFORMATION // since REDSTONE3
FileStatLxInformation, // FILE_STAT_LX_INFORMATION // since REDSTONE4 // 70
FileCaseSensitiveInformation, // FILE_CASE_SENSITIVE_INFORMATION
FileLinkInformationEx, // FILE_LINK_INFORMATION // since REDSTONE5
FileLinkInformationExBypassAccessCheck, // FILE_LINK_INFORMATION
FileStorageReserveIdInformation, // FILE_SET_STORAGE_RESERVE_ID_INFORMATION
FileCaseSensitiveInformationForceAccessCheck, // FILE_CASE_SENSITIVE_INFORMATION
FileMaximumInformation
} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
// NtQueryInformationFile/NtSetInformationFile types
typedef struct _FILE_BASIC_INFORMATION
{
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
ULONG FileAttributes;
} FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION;
typedef struct _FILE_STANDARD_INFORMATION
{
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;
ULONG NumberOfLinks;
BOOLEAN DeletePending;
BOOLEAN Directory;
} FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION;
typedef struct _FILE_STANDARD_INFORMATION_EX
{
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;
ULONG NumberOfLinks;
BOOLEAN DeletePending;
BOOLEAN Directory;
BOOLEAN AlternateStream;
BOOLEAN MetadataAttribute;
} FILE_STANDARD_INFORMATION_EX, *PFILE_STANDARD_INFORMATION_EX;
typedef struct _FILE_INTERNAL_INFORMATION
{
LARGE_INTEGER IndexNumber;
} FILE_INTERNAL_INFORMATION, *PFILE_INTERNAL_INFORMATION;
typedef struct _FILE_EA_INFORMATION
{
ULONG EaSize;
} FILE_EA_INFORMATION, *PFILE_EA_INFORMATION;
typedef struct _FILE_ACCESS_INFORMATION
{
ACCESS_MASK AccessFlags;
} FILE_ACCESS_INFORMATION, *PFILE_ACCESS_INFORMATION;
typedef struct _FILE_POSITION_INFORMATION
{
LARGE_INTEGER CurrentByteOffset;
} FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION;
typedef struct _FILE_MODE_INFORMATION
{
ULONG Mode;
} FILE_MODE_INFORMATION, *PFILE_MODE_INFORMATION;
typedef struct _FILE_ALIGNMENT_INFORMATION
{
ULONG AlignmentRequirement;
} FILE_ALIGNMENT_INFORMATION, *PFILE_ALIGNMENT_INFORMATION;
typedef struct _FILE_NAME_INFORMATION
{
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION;
typedef struct _FILE_ALL_INFORMATION
{
FILE_BASIC_INFORMATION BasicInformation;
FILE_STANDARD_INFORMATION StandardInformation;
FILE_INTERNAL_INFORMATION InternalInformation;
FILE_EA_INFORMATION EaInformation;
FILE_ACCESS_INFORMATION AccessInformation;
FILE_POSITION_INFORMATION PositionInformation;
FILE_MODE_INFORMATION ModeInformation;
FILE_ALIGNMENT_INFORMATION AlignmentInformation;
FILE_NAME_INFORMATION NameInformation;
} FILE_ALL_INFORMATION, *PFILE_ALL_INFORMATION;
typedef struct _FILE_NETWORK_OPEN_INFORMATION
{
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;
ULONG FileAttributes;
} FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION;
typedef struct _FILE_ATTRIBUTE_TAG_INFORMATION
{
ULONG FileAttributes;
ULONG ReparseTag;
} FILE_ATTRIBUTE_TAG_INFORMATION, *PFILE_ATTRIBUTE_TAG_INFORMATION;
typedef struct _FILE_ALLOCATION_INFORMATION
{
LARGE_INTEGER AllocationSize;
} FILE_ALLOCATION_INFORMATION, *PFILE_ALLOCATION_INFORMATION;
typedef struct _FILE_COMPRESSION_INFORMATION
{
LARGE_INTEGER CompressedFileSize;
USHORT CompressionFormat;
UCHAR CompressionUnitShift;
UCHAR ChunkShift;
UCHAR ClusterShift;
UCHAR Reserved[3];
} FILE_COMPRESSION_INFORMATION, *PFILE_COMPRESSION_INFORMATION;
typedef struct _FILE_DISPOSITION_INFORMATION
{
BOOLEAN DeleteFile;
} FILE_DISPOSITION_INFORMATION, *PFILE_DISPOSITION_INFORMATION;
typedef struct _FILE_END_OF_FILE_INFORMATION
{
LARGE_INTEGER EndOfFile;
} FILE_END_OF_FILE_INFORMATION, *PFILE_END_OF_FILE_INFORMATION;
typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION
{
LARGE_INTEGER ValidDataLength;
} FILE_VALID_DATA_LENGTH_INFORMATION, *PFILE_VALID_DATA_LENGTH_INFORMATION;
typedef struct _FILE_LINK_INFORMATION
{
BOOLEAN ReplaceIfExists;
HANDLE RootDirectory;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_LINK_INFORMATION, *PFILE_LINK_INFORMATION;
typedef struct _FILE_MOVE_CLUSTER_INFORMATION
{
ULONG ClusterCount;
HANDLE RootDirectory;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_MOVE_CLUSTER_INFORMATION, *PFILE_MOVE_CLUSTER_INFORMATION;
typedef struct _FILE_RENAME_INFORMATION
{
BOOLEAN ReplaceIfExists;
HANDLE RootDirectory;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_RENAME_INFORMATION, *PFILE_RENAME_INFORMATION;
typedef struct _FILE_STREAM_INFORMATION
{
ULONG NextEntryOffset;
ULONG StreamNameLength;
LARGE_INTEGER StreamSize;
LARGE_INTEGER StreamAllocationSize;
WCHAR StreamName[1];
} FILE_STREAM_INFORMATION, *PFILE_STREAM_INFORMATION;
typedef struct _FILE_TRACKING_INFORMATION
{
HANDLE DestinationFile;
ULONG ObjectInformationLength;
CHAR ObjectInformation[1];
} FILE_TRACKING_INFORMATION, *PFILE_TRACKING_INFORMATION;
typedef struct _FILE_COMPLETION_INFORMATION
{
HANDLE Port;
PVOID Key;
} FILE_COMPLETION_INFORMATION, *PFILE_COMPLETION_INFORMATION;
typedef struct _FILE_PIPE_INFORMATION
{
ULONG ReadMode;
ULONG CompletionMode;
} FILE_PIPE_INFORMATION, *PFILE_PIPE_INFORMATION;
typedef struct _FILE_PIPE_LOCAL_INFORMATION
{
ULONG NamedPipeType;
ULONG NamedPipeConfiguration;
ULONG MaximumInstances;
ULONG CurrentInstances;
ULONG InboundQuota;
ULONG ReadDataAvailable;
ULONG OutboundQuota;
ULONG WriteQuotaAvailable;
ULONG NamedPipeState;
ULONG NamedPipeEnd;
} FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION;
typedef struct _FILE_PIPE_REMOTE_INFORMATION
{
LARGE_INTEGER CollectDataTime;
ULONG MaximumCollectionCount;
} FILE_PIPE_REMOTE_INFORMATION, *PFILE_PIPE_REMOTE_INFORMATION;
typedef struct _FILE_MAILSLOT_QUERY_INFORMATION
{
ULONG MaximumMessageSize;
ULONG MailslotQuota;
ULONG NextMessageSize;
ULONG MessagesAvailable;
LARGE_INTEGER ReadTimeout;
} FILE_MAILSLOT_QUERY_INFORMATION, *PFILE_MAILSLOT_QUERY_INFORMATION;
typedef struct _FILE_MAILSLOT_SET_INFORMATION
{
PLARGE_INTEGER ReadTimeout;
} FILE_MAILSLOT_SET_INFORMATION, *PFILE_MAILSLOT_SET_INFORMATION;
typedef struct _FILE_REPARSE_POINT_INFORMATION
{
LONGLONG FileReference;
ULONG Tag;
} FILE_REPARSE_POINT_INFORMATION, *PFILE_REPARSE_POINT_INFORMATION;
typedef struct _FILE_LINK_ENTRY_INFORMATION
{
ULONG NextEntryOffset;
LONGLONG ParentFileId;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_LINK_ENTRY_INFORMATION, *PFILE_LINK_ENTRY_INFORMATION;
typedef struct _FILE_LINKS_INFORMATION
{
ULONG BytesNeeded;
ULONG EntriesReturned;
FILE_LINK_ENTRY_INFORMATION Entry;
} FILE_LINKS_INFORMATION, *PFILE_LINKS_INFORMATION;
typedef struct _FILE_NETWORK_PHYSICAL_NAME_INFORMATION
{
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_NETWORK_PHYSICAL_NAME_INFORMATION, *PFILE_NETWORK_PHYSICAL_NAME_INFORMATION;
typedef struct _FILE_STANDARD_LINK_INFORMATION
{
ULONG NumberOfAccessibleLinks;
ULONG TotalNumberOfLinks;
BOOLEAN DeletePending;
BOOLEAN Directory;
} FILE_STANDARD_LINK_INFORMATION, *PFILE_STANDARD_LINK_INFORMATION;
typedef struct _FILE_SFIO_RESERVE_INFORMATION
{
ULONG RequestsPerPeriod;
ULONG Period;
BOOLEAN RetryFailures;
BOOLEAN Discardable;
ULONG RequestSize;
ULONG NumOutstandingRequests;
} FILE_SFIO_RESERVE_INFORMATION, *PFILE_SFIO_RESERVE_INFORMATION;
typedef struct _FILE_SFIO_VOLUME_INFORMATION
{
ULONG MaximumRequestsPerPeriod;
ULONG MinimumPeriod;
ULONG MinimumTransferSize;
} FILE_SFIO_VOLUME_INFORMATION, *PFILE_SFIO_VOLUME_INFORMATION;
typedef enum _IO_PRIORITY_HINT
{
IoPriorityVeryLow = 0, // Defragging, content indexing and other background I/Os.
IoPriorityLow, // Prefetching for applications.
IoPriorityNormal, // Normal I/Os.
IoPriorityHigh, // Used by filesystems for checkpoint I/O.
IoPriorityCritical, // Used by memory manager. Not available for applications.
MaxIoPriorityTypes
} IO_PRIORITY_HINT;
typedef struct _FILE_IO_PRIORITY_HINT_INFORMATION
{
IO_PRIORITY_HINT PriorityHint;
} FILE_IO_PRIORITY_HINT_INFORMATION, *PFILE_IO_PRIORITY_HINT_INFORMATION;
typedef struct _FILE_IO_PRIORITY_HINT_INFORMATION_EX
{
IO_PRIORITY_HINT PriorityHint;
BOOLEAN BoostOutstanding;
} FILE_IO_PRIORITY_HINT_INFORMATION_EX, *PFILE_IO_PRIORITY_HINT_INFORMATION_EX;
#define FILE_SKIP_COMPLETION_PORT_ON_SUCCESS 0x1
#define FILE_SKIP_SET_EVENT_ON_HANDLE 0x2
#define FILE_SKIP_SET_USER_EVENT_ON_FAST_IO 0x4
typedef struct _FILE_IO_COMPLETION_NOTIFICATION_INFORMATION
{
ULONG Flags;
} FILE_IO_COMPLETION_NOTIFICATION_INFORMATION, *PFILE_IO_COMPLETION_NOTIFICATION_INFORMATION;
typedef struct _FILE_PROCESS_IDS_USING_FILE_INFORMATION
{
ULONG NumberOfProcessIdsInList;
ULONG_PTR ProcessIdList[1];
} FILE_PROCESS_IDS_USING_FILE_INFORMATION, *PFILE_PROCESS_IDS_USING_FILE_INFORMATION;
typedef struct _FILE_IS_REMOTE_DEVICE_INFORMATION
{
BOOLEAN IsRemote;
} FILE_IS_REMOTE_DEVICE_INFORMATION, *PFILE_IS_REMOTE_DEVICE_INFORMATION;
typedef struct _FILE_NUMA_NODE_INFORMATION
{
USHORT NodeNumber;
} FILE_NUMA_NODE_INFORMATION, *PFILE_NUMA_NODE_INFORMATION;
typedef struct _FILE_IOSTATUSBLOCK_RANGE_INFORMATION
{
PUCHAR IoStatusBlockRange;
ULONG Length;
} FILE_IOSTATUSBLOCK_RANGE_INFORMATION, *PFILE_IOSTATUSBLOCK_RANGE_INFORMATION;
typedef struct _FILE_REMOTE_PROTOCOL_INFORMATION
{
USHORT StructureVersion; // 1
USHORT StructureSize;
ULONG Protocol; // WNNC_NET_*
USHORT ProtocolMajorVersion;
USHORT ProtocolMinorVersion;
USHORT ProtocolRevision;
USHORT Reserved;
// Generic information
ULONG Flags;
struct
{
ULONG Reserved[8];
} GenericReserved;
// Specific information
#if (NTDDI_VERSION < NTDDI_WIN8)
struct
{
ULONG Reserved[16];
} ProtocolSpecificReserved;
#else
union
{
struct
{
struct
{
ULONG Capabilities;
} Server;
struct
{
ULONG Capabilities;
ULONG CachingFlags;
} Share;
} Smb2;
ULONG Reserved[16];
} ProtocolSpecific;
#endif
} FILE_REMOTE_PROTOCOL_INFORMATION, *PFILE_REMOTE_PROTOCOL_INFORMATION;
#define CHECKSUM_ENFORCEMENT_OFF 0x00000001
typedef struct _FILE_INTEGRITY_STREAM_INFORMATION
{
USHORT ChecksumAlgorithm;
UCHAR ChecksumChunkShift;
UCHAR ClusterShift;
ULONG Flags;
} FILE_INTEGRITY_STREAM_INFORMATION, *PFILE_INTEGRITY_STREAM_INFORMATION;
typedef struct _FILE_VOLUME_NAME_INFORMATION
{
ULONG DeviceNameLength;
WCHAR DeviceName[1];
} FILE_VOLUME_NAME_INFORMATION, *PFILE_VOLUME_NAME_INFORMATION;
typedef struct _FILE_ID_INFORMATION
{
ULONGLONG VolumeSerialNumber;
FILE_ID_128 FileId;
} FILE_ID_INFORMATION, *PFILE_ID_INFORMATION;
typedef struct _FILE_ID_EXTD_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
ULONG EaSize;
ULONG ReparsePointTag;
FILE_ID_128 FileId;
WCHAR FileName[1];
} FILE_ID_EXTD_DIR_INFORMATION, *PFILE_ID_EXTD_DIR_INFORMATION;
typedef struct _FILE_LINK_ENTRY_FULL_ID_INFORMATION
{
ULONG NextEntryOffset;
FILE_ID_128 ParentFileId;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_LINK_ENTRY_FULL_ID_INFORMATION, *PFILE_LINK_ENTRY_FULL_ID_INFORMATION;
typedef struct _FILE_ID_EXTD_BOTH_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
ULONG EaSize;
ULONG ReparsePointTag;
FILE_ID_128 FileId;
CCHAR ShortNameLength;
WCHAR ShortName[12];
WCHAR FileName[1];
} FILE_ID_EXTD_BOTH_DIR_INFORMATION, *PFILE_ID_EXTD_BOTH_DIR_INFORMATION;
// private
typedef struct _FILE_STAT_INFORMATION
{
LARGE_INTEGER FileId;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;
ULONG FileAttributes;
ULONG ReparseTag;
ULONG NumberOfLinks;
ULONG EffectiveAccess;
} FILE_STAT_INFORMATION, *PFILE_STAT_INFORMATION;
// private
typedef struct _FILE_MEMORY_PARTITION_INFORMATION
{
HANDLE OwnerPartitionHandle;
union
{
struct
{
UCHAR NoCrossPartitionAccess;
UCHAR Spare[3];
};
ULONG AllFlags;
} Flags;
} FILE_MEMORY_PARTITION_INFORMATION, *PFILE_MEMORY_PARTITION_INFORMATION;
// private
typedef struct _FILE_STAT_LX_INFORMATION
{
LARGE_INTEGER FileId;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER AllocationSize;
LARGE_INTEGER EndOfFile;
ULONG FileAttributes;
ULONG ReparseTag;
ULONG NumberOfLinks;
ULONG EffectiveAccess;
ULONG LxFlags;
ULONG LxUid;
ULONG LxGid;
ULONG LxMode;
ULONG LxDeviceIdMajor;
ULONG LxDeviceIdMinor;
} FILE_STAT_LX_INFORMATION, *PFILE_STAT_LX_INFORMATION;
// private
typedef struct _FILE_CASE_SENSITIVE_INFORMATION
{
ULONG Flags;
} FILE_CASE_SENSITIVE_INFORMATION, *PFILE_CASE_SENSITIVE_INFORMATION;
// NtQueryDirectoryFile types
typedef struct _FILE_DIRECTORY_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_DIRECTORY_INFORMATION, *PFILE_DIRECTORY_INFORMATION;
typedef struct _FILE_FULL_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
ULONG EaSize;
WCHAR FileName[1];
} FILE_FULL_DIR_INFORMATION, *PFILE_FULL_DIR_INFORMATION;
typedef struct _FILE_ID_FULL_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
ULONG EaSize;
LARGE_INTEGER FileId;
WCHAR FileName[1];
} FILE_ID_FULL_DIR_INFORMATION, *PFILE_ID_FULL_DIR_INFORMATION;
typedef struct _FILE_BOTH_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
ULONG EaSize;
CCHAR ShortNameLength;
WCHAR ShortName[12];
WCHAR FileName[1];
} FILE_BOTH_DIR_INFORMATION, *PFILE_BOTH_DIR_INFORMATION;
typedef struct _FILE_ID_BOTH_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
ULONG EaSize;
CCHAR ShortNameLength;
WCHAR ShortName[12];
LARGE_INTEGER FileId;
WCHAR FileName[1];
} FILE_ID_BOTH_DIR_INFORMATION, *PFILE_ID_BOTH_DIR_INFORMATION;
typedef struct _FILE_NAMES_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_NAMES_INFORMATION, *PFILE_NAMES_INFORMATION;
typedef struct _FILE_ID_GLOBAL_TX_DIR_INFORMATION
{
ULONG NextEntryOffset;
ULONG FileIndex;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER LastWriteTime;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER EndOfFile;
LARGE_INTEGER AllocationSize;
ULONG FileAttributes;
ULONG FileNameLength;
LARGE_INTEGER FileId;
GUID LockingTransactionId;
ULONG TxInfoFlags;
WCHAR FileName[1];
} FILE_ID_GLOBAL_TX_DIR_INFORMATION, *PFILE_ID_GLOBAL_TX_DIR_INFORMATION;
#define FILE_ID_GLOBAL_TX_DIR_INFO_FLAG_WRITELOCKED 0x00000001
#define FILE_ID_GLOBAL_TX_DIR_INFO_FLAG_VISIBLE_TO_TX 0x00000002
#define FILE_ID_GLOBAL_TX_DIR_INFO_FLAG_VISIBLE_OUTSIDE_TX 0x00000004
typedef struct _FILE_OBJECTID_INFORMATION
{
LONGLONG FileReference;
UCHAR ObjectId[16];
union
{
struct
{
UCHAR BirthVolumeId[16];
UCHAR BirthObjectId[16];
UCHAR DomainId[16];
};
UCHAR ExtendedInfo[48];
};
} FILE_OBJECTID_INFORMATION, *PFILE_OBJECTID_INFORMATION;
// NtQueryEaFile/NtSetEaFile types
typedef struct _FILE_FULL_EA_INFORMATION
{
ULONG NextEntryOffset;
UCHAR Flags;
UCHAR EaNameLength;
USHORT EaValueLength;
CHAR EaName[1];
} FILE_FULL_EA_INFORMATION, *PFILE_FULL_EA_INFORMATION;
typedef struct _FILE_GET_EA_INFORMATION
{
ULONG NextEntryOffset;
UCHAR EaNameLength;
CHAR EaName[1];
} FILE_GET_EA_INFORMATION, *PFILE_GET_EA_INFORMATION;
// NtQueryQuotaInformationFile/NtSetQuotaInformationFile types
typedef struct _FILE_GET_QUOTA_INFORMATION
{
ULONG NextEntryOffset;
ULONG SidLength;
SID Sid;
} FILE_GET_QUOTA_INFORMATION, *PFILE_GET_QUOTA_INFORMATION;
typedef struct _FILE_QUOTA_INFORMATION
{
ULONG NextEntryOffset;
ULONG SidLength;
LARGE_INTEGER ChangeTime;
LARGE_INTEGER QuotaUsed;
LARGE_INTEGER QuotaThreshold;
LARGE_INTEGER QuotaLimit;
SID Sid;
} FILE_QUOTA_INFORMATION, *PFILE_QUOTA_INFORMATION;
typedef enum _FSINFOCLASS
{
FileFsVolumeInformation = 1, // FILE_FS_VOLUME_INFORMATION
FileFsLabelInformation, // FILE_FS_LABEL_INFORMATION
FileFsSizeInformation, // FILE_FS_SIZE_INFORMATION
FileFsDeviceInformation, // FILE_FS_DEVICE_INFORMATION
FileFsAttributeInformation, // FILE_FS_ATTRIBUTE_INFORMATION
FileFsControlInformation, // FILE_FS_CONTROL_INFORMATION
FileFsFullSizeInformation, // FILE_FS_FULL_SIZE_INFORMATION
FileFsObjectIdInformation, // FILE_FS_OBJECTID_INFORMATION
FileFsDriverPathInformation, // FILE_FS_DRIVER_PATH_INFORMATION
FileFsVolumeFlagsInformation, // FILE_FS_VOLUME_FLAGS_INFORMATION // 10
FileFsSectorSizeInformation, // FILE_FS_SECTOR_SIZE_INFORMATION // since WIN8
FileFsDataCopyInformation, // FILE_FS_DATA_COPY_INFORMATION
FileFsMetadataSizeInformation, // FILE_FS_METADATA_SIZE_INFORMATION // since THRESHOLD
FileFsFullSizeInformationEx, // FILE_FS_FULL_SIZE_INFORMATION_EX // since REDSTONE5
FileFsMaximumInformation
} FSINFOCLASS, *PFSINFOCLASS;
// NtQueryVolumeInformation/NtSetVolumeInformation types
// private
typedef struct _FILE_FS_VOLUME_INFORMATION
{
LARGE_INTEGER VolumeCreationTime;
ULONG VolumeSerialNumber;
ULONG VolumeLabelLength;
BOOLEAN SupportsObjects;
WCHAR VolumeLabel[1];
} FILE_FS_VOLUME_INFORMATION, *PFILE_FS_VOLUME_INFORMATION;
// private
typedef struct _FILE_FS_LABEL_INFORMATION
{
ULONG VolumeLabelLength;
WCHAR VolumeLabel[1];
} FILE_FS_LABEL_INFORMATION, * PFILE_FS_LABEL_INFORMATION;
// private
typedef struct _FILE_FS_SIZE_INFORMATION
{
LARGE_INTEGER TotalAllocationUnits;
LARGE_INTEGER AvailableAllocationUnits;
ULONG SectorsPerAllocationUnit;
ULONG BytesPerSector;
} FILE_FS_SIZE_INFORMATION, *PFILE_FS_SIZE_INFORMATION;
// private
typedef struct _FILE_FS_CONTROL_INFORMATION
{
LARGE_INTEGER FreeSpaceStartFiltering;
LARGE_INTEGER FreeSpaceThreshold;
LARGE_INTEGER FreeSpaceStopFiltering;
LARGE_INTEGER DefaultQuotaThreshold;
LARGE_INTEGER DefaultQuotaLimit;
ULONG FileSystemControlFlags;
} FILE_FS_CONTROL_INFORMATION, *PFILE_FS_CONTROL_INFORMATION;
// private
typedef struct _FILE_FS_FULL_SIZE_INFORMATION
{
LARGE_INTEGER TotalAllocationUnits;
LARGE_INTEGER CallerAvailableAllocationUnits;
LARGE_INTEGER ActualAvailableAllocationUnits;
ULONG SectorsPerAllocationUnit;
ULONG BytesPerSector;
} FILE_FS_FULL_SIZE_INFORMATION, *PFILE_FS_FULL_SIZE_INFORMATION;
// private
typedef struct _FILE_FS_OBJECTID_INFORMATION
{
UCHAR ObjectId[16];
UCHAR ExtendedInfo[48];
} FILE_FS_OBJECTID_INFORMATION, *PFILE_FS_OBJECTID_INFORMATION;
// private
typedef struct _FILE_FS_DEVICE_INFORMATION
{
DEVICE_TYPE DeviceType;
ULONG Characteristics;
} FILE_FS_DEVICE_INFORMATION, *PFILE_FS_DEVICE_INFORMATION;
// private
typedef struct _FILE_FS_ATTRIBUTE_INFORMATION
{
ULONG FileSystemAttributes;
LONG MaximumComponentNameLength;
ULONG FileSystemNameLength;
WCHAR FileSystemName[1];
} FILE_FS_ATTRIBUTE_INFORMATION, *PFILE_FS_ATTRIBUTE_INFORMATION;
// private
typedef struct _FILE_FS_DRIVER_PATH_INFORMATION
{
BOOLEAN DriverInPath;
ULONG DriverNameLength;
WCHAR DriverName[1];
} FILE_FS_DRIVER_PATH_INFORMATION, *PFILE_FS_DRIVER_PATH_INFORMATION;
// private
typedef struct _FILE_FS_VOLUME_FLAGS_INFORMATION
{
ULONG Flags;
} FILE_FS_VOLUME_FLAGS_INFORMATION, *PFILE_FS_VOLUME_FLAGS_INFORMATION;
#define SSINFO_FLAGS_ALIGNED_DEVICE 0x00000001
#define SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE 0x00000002
// If set for Sector and Partition fields, alignment is not known.
#define SSINFO_OFFSET_UNKNOWN 0xffffffff
typedef struct _FILE_FS_SECTOR_SIZE_INFORMATION
{
ULONG LogicalBytesPerSector;
ULONG PhysicalBytesPerSectorForAtomicity;
ULONG PhysicalBytesPerSectorForPerformance;
ULONG FileSystemEffectivePhysicalBytesPerSectorForAtomicity;
ULONG Flags;
ULONG ByteOffsetForSectorAlignment;
ULONG ByteOffsetForPartitionAlignment;
} FILE_FS_SECTOR_SIZE_INFORMATION, *PFILE_FS_SECTOR_SIZE_INFORMATION;
// private
typedef struct _FILE_FS_DATA_COPY_INFORMATION
{
ULONG NumberOfCopies;
} FILE_FS_DATA_COPY_INFORMATION, *PFILE_FS_DATA_COPY_INFORMATION;
// private
typedef struct _FILE_FS_METADATA_SIZE_INFORMATION
{
LARGE_INTEGER TotalMetadataAllocationUnits;
ULONG SectorsPerAllocationUnit;
ULONG BytesPerSector;
} FILE_FS_METADATA_SIZE_INFORMATION, *PFILE_FS_METADATA_SIZE_INFORMATION;
// private
typedef struct _FILE_FS_FULL_SIZE_INFORMATION_EX
{
ULONGLONG ActualTotalAllocationUnits;
ULONGLONG ActualAvailableAllocationUnits;
ULONGLONG ActualPoolUnavailableAllocationUnits;
ULONGLONG CallerTotalAllocationUnits;
ULONGLONG CallerAvailableAllocationUnits;
ULONGLONG CallerPoolUnavailableAllocationUnits;
ULONGLONG UsedAllocationUnits;
ULONGLONG TotalReservedAllocationUnits;
ULONGLONG VolumeStorageReserveAllocationUnits;
ULONGLONG AvailableCommittedAllocationUnits;
ULONGLONG PoolAvailableAllocationUnits;
ULONG SectorsPerAllocationUnit;
ULONG BytesPerSector;
} FILE_FS_FULL_SIZE_INFORMATION_EX, *PFILE_FS_FULL_SIZE_INFORMATION_EX;
// System calls
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateFile(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_opt_ PLARGE_INTEGER AllocationSize,
_In_ ULONG FileAttributes,
_In_ ULONG ShareAccess,
_In_ ULONG CreateDisposition,
_In_ ULONG CreateOptions,
_In_reads_bytes_opt_(EaLength) PVOID EaBuffer,
_In_ ULONG EaLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateFile(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_opt_ PLARGE_INTEGER AllocationSize,
_In_ ULONG FileAttributes,
_In_ ULONG ShareAccess,
_In_ ULONG CreateDisposition,
_In_ ULONG CreateOptions,
_In_reads_bytes_opt_(EaLength) PVOID EaBuffer,
_In_ ULONG EaLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateNamedPipeFile(
_Out_ PHANDLE FileHandle,
_In_ ULONG DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG ShareAccess,
_In_ ULONG CreateDisposition,
_In_ ULONG CreateOptions,
_In_ ULONG NamedPipeType,
_In_ ULONG ReadMode,
_In_ ULONG CompletionMode,
_In_ ULONG MaximumInstances,
_In_ ULONG InboundQuota,
_In_ ULONG OutboundQuota,
_In_opt_ PLARGE_INTEGER DefaultTimeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateNamedPipeFile(
_Out_ PHANDLE FileHandle,
_In_ ULONG DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG ShareAccess,
_In_ ULONG CreateDisposition,
_In_ ULONG CreateOptions,
_In_ ULONG NamedPipeType,
_In_ ULONG ReadMode,
_In_ ULONG CompletionMode,
_In_ ULONG MaximumInstances,
_In_ ULONG InboundQuota,
_In_ ULONG OutboundQuota,
_In_opt_ PLARGE_INTEGER DefaultTimeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateMailslotFile(
_Out_ PHANDLE FileHandle,
_In_ ULONG DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG CreateOptions,
_In_ ULONG MailslotQuota,
_In_ ULONG MaximumMessageSize,
_In_ PLARGE_INTEGER ReadTimeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateMailslotFile(
_Out_ PHANDLE FileHandle,
_In_ ULONG DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG CreateOptions,
_In_ ULONG MailslotQuota,
_In_ ULONG MaximumMessageSize,
_In_ PLARGE_INTEGER ReadTimeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenFile(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG ShareAccess,
_In_ ULONG OpenOptions
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenFile(
_Out_ PHANDLE FileHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG ShareAccess,
_In_ ULONG OpenOptions
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteFile(
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteFile(
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFlushBuffersFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFlushBuffersFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
#define FLUSH_FLAGS_FILE_DATA_ONLY 0x00000001
#define FLUSH_FLAGS_NO_SYNC 0x00000002
#define FLUSH_FLAGS_FILE_DATA_SYNC_ONLY 0x00000004 // REDSTONE1
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFlushBuffersFileEx(
_In_ HANDLE FileHandle,
_In_ ULONG Flags,
_In_reads_bytes_(ParametersSize) PVOID Parameters,
_In_ ULONG ParametersSize,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFlushBuffersFileEx(
_In_ HANDLE FileHandle,
_In_ ULONG Flags,
_In_reads_bytes_(ParametersSize) PVOID Parameters,
_In_ ULONG ParametersSize,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS2)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationByName(
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationByName(
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDirectoryFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass,
_In_ BOOLEAN ReturnSingleEntry,
_In_opt_ PUNICODE_STRING FileName,
_In_ BOOLEAN RestartScan
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDirectoryFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass,
_In_ BOOLEAN ReturnSingleEntry,
_In_opt_ PUNICODE_STRING FileName,
_In_ BOOLEAN RestartScan
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS3)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryDirectoryFileEx(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_ PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass,
_In_ ULONG QueryFlags,
_In_opt_ PUNICODE_STRING FileName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryDirectoryFileEx(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_ PVOID FileInformation,
_In_ ULONG Length,
_In_ FILE_INFORMATION_CLASS FileInformationClass,
_In_ ULONG QueryFlags,
_In_opt_ PUNICODE_STRING FileName
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryEaFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ BOOLEAN ReturnSingleEntry,
_In_reads_bytes_opt_(EaListLength) PVOID EaList,
_In_ ULONG EaListLength,
_In_opt_ PULONG EaIndex,
_In_ BOOLEAN RestartScan
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryEaFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ BOOLEAN ReturnSingleEntry,
_In_reads_bytes_opt_(EaListLength) PVOID EaList,
_In_ ULONG EaListLength,
_In_opt_ PULONG EaIndex,
_In_ BOOLEAN RestartScan
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetEaFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID Buffer,
_In_ ULONG Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetEaFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID Buffer,
_In_ ULONG Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryQuotaInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ BOOLEAN ReturnSingleEntry,
_In_reads_bytes_opt_(SidListLength) PVOID SidList,
_In_ ULONG SidListLength,
_In_opt_ PSID StartSid,
_In_ BOOLEAN RestartScan
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryQuotaInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ BOOLEAN ReturnSingleEntry,
_In_reads_bytes_opt_(SidListLength) PVOID SidList,
_In_ ULONG SidListLength,
_In_opt_ PSID StartSid,
_In_ BOOLEAN RestartScan
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetQuotaInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID Buffer,
_In_ ULONG Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetQuotaInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID Buffer,
_In_ ULONG Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryVolumeInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FsInformation,
_In_ ULONG Length,
_In_ FSINFOCLASS FsInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryVolumeInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID FsInformation,
_In_ ULONG Length,
_In_ FSINFOCLASS FsInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetVolumeInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID FsInformation,
_In_ ULONG Length,
_In_ FSINFOCLASS FsInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetVolumeInformationFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID FsInformation,
_In_ ULONG Length,
_In_ FSINFOCLASS FsInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCancelIoFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCancelIoFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCancelIoFileEx(
_In_ HANDLE FileHandle,
_In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCancelIoFileEx(
_In_ HANDLE FileHandle,
_In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCancelSynchronousIoFile(
_In_ HANDLE ThreadHandle,
_In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCancelSynchronousIoFile(
_In_ HANDLE ThreadHandle,
_In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
_Out_ PIO_STATUS_BLOCK IoStatusBlock
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeviceIoControlFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG IoControlCode,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeviceIoControlFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG IoControlCode,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFsControlFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG FsControlCode,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFsControlFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG FsControlCode,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReadFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReadFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWriteFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWriteFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_reads_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReadFileScatter(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PFILE_SEGMENT_ELEMENT SegmentArray,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReadFileScatter(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PFILE_SEGMENT_ELEMENT SegmentArray,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWriteFileGather(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PFILE_SEGMENT_ELEMENT SegmentArray,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWriteFileGather(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PFILE_SEGMENT_ELEMENT SegmentArray,
_In_ ULONG Length,
_In_opt_ PLARGE_INTEGER ByteOffset,
_In_opt_ PULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLockFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PLARGE_INTEGER ByteOffset,
_In_ PLARGE_INTEGER Length,
_In_ ULONG Key,
_In_ BOOLEAN FailImmediately,
_In_ BOOLEAN ExclusiveLock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLockFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PLARGE_INTEGER ByteOffset,
_In_ PLARGE_INTEGER Length,
_In_ ULONG Key,
_In_ BOOLEAN FailImmediately,
_In_ BOOLEAN ExclusiveLock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnlockFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PLARGE_INTEGER ByteOffset,
_In_ PLARGE_INTEGER Length,
_In_ ULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnlockFile(
_In_ HANDLE FileHandle,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ PLARGE_INTEGER ByteOffset,
_In_ PLARGE_INTEGER Length,
_In_ ULONG Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryAttributesFile(
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PFILE_BASIC_INFORMATION FileInformation
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryAttributesFile(
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PFILE_BASIC_INFORMATION FileInformation
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryFullAttributesFile(
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryFullAttributesFile(
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtNotifyChangeDirectoryFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer, // FILE_NOTIFY_INFORMATION
_In_ ULONG Length,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwNotifyChangeDirectoryFile(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer, // FILE_NOTIFY_INFORMATION
_In_ ULONG Length,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree
);
// private
typedef enum _DIRECTORY_NOTIFY_INFORMATION_CLASS
{
DirectoryNotifyInformation, // FILE_NOTIFY_INFORMATION
DirectoryNotifyExtendedInformation // FILE_NOTIFY_EXTENDED_INFORMATION
} DIRECTORY_NOTIFY_INFORMATION_CLASS, *PDIRECTORY_NOTIFY_INFORMATION_CLASS;
#if (NTDDI_VERSION >= NTDDI_WIN10_RS3)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtNotifyChangeDirectoryFileEx(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree,
_In_opt_ DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwNotifyChangeDirectoryFileEx(
_In_ HANDLE FileHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_Out_writes_bytes_(Length) PVOID Buffer,
_In_ ULONG Length,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree,
_In_opt_ DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLoadDriver(
_In_ PUNICODE_STRING DriverServiceName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLoadDriver(
_In_ PUNICODE_STRING DriverServiceName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnloadDriver(
_In_ PUNICODE_STRING DriverServiceName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnloadDriver(
_In_ PUNICODE_STRING DriverServiceName
);
// I/O completion port
#ifndef IO_COMPLETION_QUERY_STATE
#define IO_COMPLETION_QUERY_STATE 0x0001
#endif
typedef enum _IO_COMPLETION_INFORMATION_CLASS
{
IoCompletionBasicInformation
} IO_COMPLETION_INFORMATION_CLASS;
typedef struct _IO_COMPLETION_BASIC_INFORMATION
{
LONG Depth;
} IO_COMPLETION_BASIC_INFORMATION, *PIO_COMPLETION_BASIC_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateIoCompletion(
_Out_ PHANDLE IoCompletionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ ULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateIoCompletion(
_Out_ PHANDLE IoCompletionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ ULONG Count
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenIoCompletion(
_Out_ PHANDLE IoCompletionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenIoCompletion(
_Out_ PHANDLE IoCompletionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryIoCompletion(
_In_ HANDLE IoCompletionHandle,
_In_ IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass,
_Out_writes_bytes_(IoCompletionInformationLength) PVOID IoCompletionInformation,
_In_ ULONG IoCompletionInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryIoCompletion(
_In_ HANDLE IoCompletionHandle,
_In_ IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass,
_Out_writes_bytes_(IoCompletionInformationLength) PVOID IoCompletionInformation,
_In_ ULONG IoCompletionInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetIoCompletion(
_In_ HANDLE IoCompletionHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetIoCompletion(
_In_ HANDLE IoCompletionHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetIoCompletionEx(
_In_ HANDLE IoCompletionHandle,
_In_ HANDLE IoCompletionPacketHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetIoCompletionEx(
_In_ HANDLE IoCompletionHandle,
_In_ HANDLE IoCompletionPacketHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRemoveIoCompletion(
_In_ HANDLE IoCompletionHandle,
_Out_ PVOID *KeyContext,
_Out_ PVOID *ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRemoveIoCompletion(
_In_ HANDLE IoCompletionHandle,
_Out_ PVOID *KeyContext,
_Out_ PVOID *ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_opt_ PLARGE_INTEGER Timeout
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRemoveIoCompletionEx(
_In_ HANDLE IoCompletionHandle,
_Out_writes_to_(Count, *NumEntriesRemoved) PFILE_IO_COMPLETION_INFORMATION IoCompletionInformation,
_In_ ULONG Count,
_Out_ PULONG NumEntriesRemoved,
_In_opt_ PLARGE_INTEGER Timeout,
_In_ BOOLEAN Alertable
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRemoveIoCompletionEx(
_In_ HANDLE IoCompletionHandle,
_Out_writes_to_(Count, *NumEntriesRemoved) PFILE_IO_COMPLETION_INFORMATION IoCompletionInformation,
_In_ ULONG Count,
_Out_ PULONG NumEntriesRemoved,
_In_opt_ PLARGE_INTEGER Timeout,
_In_ BOOLEAN Alertable
);
#endif
// Wait completion packet
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateWaitCompletionPacket(
_Out_ PHANDLE WaitCompletionPacketHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateWaitCompletionPacket(
_Out_ PHANDLE WaitCompletionPacketHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAssociateWaitCompletionPacket(
_In_ HANDLE WaitCompletionPacketHandle,
_In_ HANDLE IoCompletionHandle,
_In_ HANDLE TargetObjectHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation,
_Out_opt_ PBOOLEAN AlreadySignaled
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAssociateWaitCompletionPacket(
_In_ HANDLE WaitCompletionPacketHandle,
_In_ HANDLE IoCompletionHandle,
_In_ HANDLE TargetObjectHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation,
_Out_opt_ PBOOLEAN AlreadySignaled
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCancelWaitCompletionPacket(
_In_ HANDLE WaitCompletionPacketHandle,
_In_ BOOLEAN RemoveSignaledPacket
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCancelWaitCompletionPacket(
_In_ HANDLE WaitCompletionPacketHandle,
_In_ BOOLEAN RemoveSignaledPacket
);
#endif
// Sessions
typedef enum _IO_SESSION_EVENT
{
IoSessionEventIgnore,
IoSessionEventCreated,
IoSessionEventTerminated,
IoSessionEventConnected,
IoSessionEventDisconnected,
IoSessionEventLogon,
IoSessionEventLogoff,
IoSessionEventMax
} IO_SESSION_EVENT;
typedef enum _IO_SESSION_STATE
{
IoSessionStateCreated,
IoSessionStateInitialized,
IoSessionStateConnected,
IoSessionStateDisconnected,
IoSessionStateDisconnectedLoggedOn,
IoSessionStateLoggedOn,
IoSessionStateLoggedOff,
IoSessionStateTerminated,
IoSessionStateMax
} IO_SESSION_STATE;
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtNotifyChangeSession(
_In_ HANDLE SessionHandle,
_In_ ULONG ChangeSequenceNumber,
_In_ PLARGE_INTEGER ChangeTimeStamp,
_In_ IO_SESSION_EVENT Event,
_In_ IO_SESSION_STATE NewState,
_In_ IO_SESSION_STATE PreviousState,
_In_reads_bytes_opt_(PayloadSize) PVOID Payload,
_In_ ULONG PayloadSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwNotifyChangeSession(
_In_ HANDLE SessionHandle,
_In_ ULONG ChangeSequenceNumber,
_In_ PLARGE_INTEGER ChangeTimeStamp,
_In_ IO_SESSION_EVENT Event,
_In_ IO_SESSION_STATE NewState,
_In_ IO_SESSION_STATE PreviousState,
_In_reads_bytes_opt_(PayloadSize) PVOID Payload,
_In_ ULONG PayloadSize
);
#endif
// Other types
typedef enum _INTERFACE_TYPE
{
InterfaceTypeUndefined = -1,
Internal,
Isa,
Eisa,
MicroChannel,
TurboChannel,
PCIBus,
VMEBus,
NuBus,
PCMCIABus,
CBus,
MPIBus,
MPSABus,
ProcessorInternal,
InternalPowerBus,
PNPISABus,
PNPBus,
Vmcs,
MaximumInterfaceType
} INTERFACE_TYPE, *PINTERFACE_TYPE;
typedef enum _DMA_WIDTH
{
Width8Bits,
Width16Bits,
Width32Bits,
MaximumDmaWidth
} DMA_WIDTH, *PDMA_WIDTH;
typedef enum _DMA_SPEED
{
Compatible,
TypeA,
TypeB,
TypeC,
TypeF,
MaximumDmaSpeed
} DMA_SPEED, *PDMA_SPEED;
typedef enum _BUS_DATA_TYPE
{
ConfigurationSpaceUndefined = -1,
Cmos,
EisaConfiguration,
Pos,
CbusConfiguration,
PCIConfiguration,
VMEConfiguration,
NuBusConfiguration,
PCMCIAConfiguration,
MPIConfiguration,
MPSAConfiguration,
PNPISAConfiguration,
SgiInternalConfiguration,
MaximumBusDataType
} BUS_DATA_TYPE, *PBUS_DATA_TYPE;
// Control structures
// Reparse structure for FSCTL_SET_REPARSE_POINT, FSCTL_GET_REPARSE_POINT, FSCTL_DELETE_REPARSE_POINT
#define SYMLINK_FLAG_RELATIVE 1
typedef struct _REPARSE_DATA_BUFFER
{
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union
{
struct
{
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags;
WCHAR PathBuffer[1];
} SymbolicLinkReparseBuffer;
struct
{
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct
{
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
// Named pipe FS control definitions
#define DEVICE_NAMED_PIPE L"\\Device\\NamedPipe\\"
#define FSCTL_PIPE_ASSIGN_EVENT CTL_CODE(FILE_DEVICE_NAMED_PIPE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_DISCONNECT CTL_CODE(FILE_DEVICE_NAMED_PIPE, 1, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_LISTEN CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_PEEK CTL_CODE(FILE_DEVICE_NAMED_PIPE, 3, METHOD_BUFFERED, FILE_READ_DATA)
#define FSCTL_PIPE_QUERY_EVENT CTL_CODE(FILE_DEVICE_NAMED_PIPE, 4, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_TRANSCEIVE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 5, METHOD_NEITHER, FILE_READ_DATA | FILE_WRITE_DATA)
#define FSCTL_PIPE_WAIT CTL_CODE(FILE_DEVICE_NAMED_PIPE, 6, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_IMPERSONATE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 7, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_CLIENT_PROCESS CTL_CODE(FILE_DEVICE_NAMED_PIPE, 8, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_QUERY_CLIENT_PROCESS CTL_CODE(FILE_DEVICE_NAMED_PIPE, 9, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_GET_PIPE_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 10, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_PIPE_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 11, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_GET_CONNECTION_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_CONNECTION_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 13, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_GET_HANDLE_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 14, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_HANDLE_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 15, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_FLUSH CTL_CODE(FILE_DEVICE_NAMED_PIPE, 16, METHOD_BUFFERED, FILE_WRITE_DATA)
#define FSCTL_PIPE_INTERNAL_READ CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2045, METHOD_BUFFERED, FILE_READ_DATA)
#define FSCTL_PIPE_INTERNAL_WRITE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2046, METHOD_BUFFERED, FILE_WRITE_DATA)
#define FSCTL_PIPE_INTERNAL_TRANSCEIVE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2047, METHOD_NEITHER, FILE_READ_DATA | FILE_WRITE_DATA)
#define FSCTL_PIPE_INTERNAL_READ_OVFLOW CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2048, METHOD_BUFFERED, FILE_READ_DATA)
// Flags for query event
#define FILE_PIPE_READ_DATA 0x00000000
#define FILE_PIPE_WRITE_SPACE 0x00000001
// Input for FSCTL_PIPE_ASSIGN_EVENT
typedef struct _FILE_PIPE_ASSIGN_EVENT_BUFFER
{
HANDLE EventHandle;
ULONG KeyValue;
} FILE_PIPE_ASSIGN_EVENT_BUFFER, *PFILE_PIPE_ASSIGN_EVENT_BUFFER;
// Output for FILE_PIPE_PEEK_BUFFER
typedef struct _FILE_PIPE_PEEK_BUFFER
{
ULONG NamedPipeState;
ULONG ReadDataAvailable;
ULONG NumberOfMessages;
ULONG MessageLength;
CHAR Data[1];
} FILE_PIPE_PEEK_BUFFER, *PFILE_PIPE_PEEK_BUFFER;
// Output for FSCTL_PIPE_QUERY_EVENT
typedef struct _FILE_PIPE_EVENT_BUFFER
{
ULONG NamedPipeState;
ULONG EntryType;
ULONG ByteCount;
ULONG KeyValue;
ULONG NumberRequests;
} FILE_PIPE_EVENT_BUFFER, *PFILE_PIPE_EVENT_BUFFER;
// Input for FSCTL_PIPE_WAIT
typedef struct _FILE_PIPE_WAIT_FOR_BUFFER
{
LARGE_INTEGER Timeout;
ULONG NameLength;
BOOLEAN TimeoutSpecified;
WCHAR Name[1];
} FILE_PIPE_WAIT_FOR_BUFFER, *PFILE_PIPE_WAIT_FOR_BUFFER;
// Input for FSCTL_PIPE_SET_CLIENT_PROCESS, Output for FSCTL_PIPE_QUERY_CLIENT_PROCESS
typedef struct _FILE_PIPE_CLIENT_PROCESS_BUFFER
{
#if !defined(BUILD_WOW6432)
PVOID ClientSession;
PVOID ClientProcess;
#else
ULONGLONG ClientSession;
ULONGLONG ClientProcess;
#endif
} FILE_PIPE_CLIENT_PROCESS_BUFFER, *PFILE_PIPE_CLIENT_PROCESS_BUFFER;
#define FILE_PIPE_COMPUTER_NAME_LENGTH 15
// Input for FSCTL_PIPE_SET_CLIENT_PROCESS, Output for FSCTL_PIPE_QUERY_CLIENT_PROCESS
typedef struct _FILE_PIPE_CLIENT_PROCESS_BUFFER_EX
{
#if !defined(BUILD_WOW6432)
PVOID ClientSession;
PVOID ClientProcess;
#else
ULONGLONG ClientSession;
ULONGLONG ClientProcess;
#endif
USHORT ClientComputerNameLength; // in bytes
WCHAR ClientComputerBuffer[FILE_PIPE_COMPUTER_NAME_LENGTH + 1]; // null-terminated
} FILE_PIPE_CLIENT_PROCESS_BUFFER_EX, *PFILE_PIPE_CLIENT_PROCESS_BUFFER_EX;
// Mailslot FS control definitions
#define MAILSLOT_CLASS_FIRSTCLASS 1
#define MAILSLOT_CLASS_SECONDCLASS 2
#define FSCTL_MAILSLOT_PEEK CTL_CODE(FILE_DEVICE_MAILSLOT, 0, METHOD_NEITHER, FILE_READ_DATA)
// Output for FSCTL_MAILSLOT_PEEK
typedef struct _FILE_MAILSLOT_PEEK_BUFFER
{
ULONG ReadDataAvailable;
ULONG NumberOfMessages;
ULONG MessageLength;
} FILE_MAILSLOT_PEEK_BUFFER, *PFILE_MAILSLOT_PEEK_BUFFER;
// #include <ntlpcapi.h>
// Local Inter-process Communication
#define PORT_CONNECT 0x0001
#define PORT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1)
typedef struct _PORT_MESSAGE
{
union
{
struct
{
CSHORT DataLength;
CSHORT TotalLength;
} s1;
ULONG Length;
} u1;
union
{
struct
{
CSHORT Type;
CSHORT DataInfoOffset;
} s2;
ULONG ZeroInit;
} u2;
union
{
CLIENT_ID ClientId;
double DoNotUseThisField;
};
ULONG MessageId;
union
{
SIZE_T ClientViewSize; // only valid for LPC_CONNECTION_REQUEST messages
ULONG CallbackId; // only valid for LPC_REQUEST messages
};
} PORT_MESSAGE, *PPORT_MESSAGE;
typedef struct _PORT_DATA_ENTRY
{
PVOID Base;
ULONG Size;
} PORT_DATA_ENTRY, *PPORT_DATA_ENTRY;
typedef struct _PORT_DATA_INFORMATION
{
ULONG CountDataEntries;
PORT_DATA_ENTRY DataEntries[1];
} PORT_DATA_INFORMATION, *PPORT_DATA_INFORMATION;
#define LPC_REQUEST 1
#define LPC_REPLY 2
#define LPC_DATAGRAM 3
#define LPC_LOST_REPLY 4
#define LPC_PORT_CLOSED 5
#define LPC_CLIENT_DIED 6
#define LPC_EXCEPTION 7
#define LPC_DEBUG_EVENT 8
#define LPC_ERROR_EVENT 9
#define LPC_CONNECTION_REQUEST 10
#define LPC_KERNELMODE_MESSAGE (CSHORT)0x8000
#define LPC_NO_IMPERSONATE (CSHORT)0x4000
#define PORT_VALID_OBJECT_ATTRIBUTES OBJ_CASE_INSENSITIVE
#ifdef _WIN64
#define PORT_MAXIMUM_MESSAGE_LENGTH 512
#else
#define PORT_MAXIMUM_MESSAGE_LENGTH 256
#endif
#define LPC_MAX_CONNECTION_INFO_SIZE (16 * sizeof(ULONG_PTR))
#define PORT_TOTAL_MAXIMUM_MESSAGE_LENGTH \
((PORT_MAXIMUM_MESSAGE_LENGTH + sizeof(PORT_MESSAGE) + LPC_MAX_CONNECTION_INFO_SIZE + 0xf) & ~0xf)
typedef struct _LPC_CLIENT_DIED_MSG
{
PORT_MESSAGE PortMsg;
LARGE_INTEGER CreateTime;
} LPC_CLIENT_DIED_MSG, *PLPC_CLIENT_DIED_MSG;
typedef struct _PORT_VIEW
{
ULONG Length;
HANDLE SectionHandle;
ULONG SectionOffset;
SIZE_T ViewSize;
PVOID ViewBase;
PVOID ViewRemoteBase;
} PORT_VIEW, *PPORT_VIEW;
typedef struct _REMOTE_PORT_VIEW
{
ULONG Length;
SIZE_T ViewSize;
PVOID ViewBase;
} REMOTE_PORT_VIEW, *PREMOTE_PORT_VIEW;
// WOW64 definitions
// Except in a small number of special cases, WOW64 programs using the LPC APIs must use the 64-bit versions of the
// PORT_MESSAGE, PORT_VIEW and REMOTE_PORT_VIEW data structures. Note that we take a different approach than the
// official NT headers, which produce 64-bit versions in a 32-bit environment when USE_LPC6432 is defined.
typedef struct _PORT_MESSAGE64
{
union
{
struct
{
CSHORT DataLength;
CSHORT TotalLength;
} s1;
ULONG Length;
} u1;
union
{
struct
{
CSHORT Type;
CSHORT DataInfoOffset;
} s2;
ULONG ZeroInit;
} u2;
union
{
CLIENT_ID64 ClientId;
double DoNotUseThisField;
};
ULONG MessageId;
union
{
ULONGLONG ClientViewSize; // only valid for LPC_CONNECTION_REQUEST messages
ULONG CallbackId; // only valid for LPC_REQUEST messages
};
} PORT_MESSAGE64, *PPORT_MESSAGE64;
typedef struct _LPC_CLIENT_DIED_MSG64
{
PORT_MESSAGE64 PortMsg;
LARGE_INTEGER CreateTime;
} LPC_CLIENT_DIED_MSG64, *PLPC_CLIENT_DIED_MSG64;
typedef struct _PORT_VIEW64
{
ULONG Length;
ULONGLONG SectionHandle;
ULONG SectionOffset;
ULONGLONG ViewSize;
ULONGLONG ViewBase;
ULONGLONG ViewRemoteBase;
} PORT_VIEW64, *PPORT_VIEW64;
typedef struct _REMOTE_PORT_VIEW64
{
ULONG Length;
ULONGLONG ViewSize;
ULONGLONG ViewBase;
} REMOTE_PORT_VIEW64, *PREMOTE_PORT_VIEW64;
// Port creation
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreatePort(
_Out_ PHANDLE PortHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG MaxConnectionInfoLength,
_In_ ULONG MaxMessageLength,
_In_opt_ ULONG MaxPoolUsage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreatePort(
_Out_ PHANDLE PortHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG MaxConnectionInfoLength,
_In_ ULONG MaxMessageLength,
_In_opt_ ULONG MaxPoolUsage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateWaitablePort(
_Out_ PHANDLE PortHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG MaxConnectionInfoLength,
_In_ ULONG MaxMessageLength,
_In_opt_ ULONG MaxPoolUsage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateWaitablePort(
_Out_ PHANDLE PortHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG MaxConnectionInfoLength,
_In_ ULONG MaxMessageLength,
_In_opt_ ULONG MaxPoolUsage
);
// Port connection (client)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtConnectPort(
_Out_ PHANDLE PortHandle,
_In_ PUNICODE_STRING PortName,
_In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
_Inout_opt_ PPORT_VIEW ClientView,
_Inout_opt_ PREMOTE_PORT_VIEW ServerView,
_Out_opt_ PULONG MaxMessageLength,
_Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
_Inout_opt_ PULONG ConnectionInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwConnectPort(
_Out_ PHANDLE PortHandle,
_In_ PUNICODE_STRING PortName,
_In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
_Inout_opt_ PPORT_VIEW ClientView,
_Inout_opt_ PREMOTE_PORT_VIEW ServerView,
_Out_opt_ PULONG MaxMessageLength,
_Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
_Inout_opt_ PULONG ConnectionInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSecureConnectPort(
_Out_ PHANDLE PortHandle,
_In_ PUNICODE_STRING PortName,
_In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
_Inout_opt_ PPORT_VIEW ClientView,
_In_opt_ PSID RequiredServerSid,
_Inout_opt_ PREMOTE_PORT_VIEW ServerView,
_Out_opt_ PULONG MaxMessageLength,
_Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
_Inout_opt_ PULONG ConnectionInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSecureConnectPort(
_Out_ PHANDLE PortHandle,
_In_ PUNICODE_STRING PortName,
_In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
_Inout_opt_ PPORT_VIEW ClientView,
_In_opt_ PSID RequiredServerSid,
_Inout_opt_ PREMOTE_PORT_VIEW ServerView,
_Out_opt_ PULONG MaxMessageLength,
_Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
_Inout_opt_ PULONG ConnectionInformationLength
);
// Port connection (server)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtListenPort(
_In_ HANDLE PortHandle,
_Out_ PPORT_MESSAGE ConnectionRequest
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwListenPort(
_In_ HANDLE PortHandle,
_Out_ PPORT_MESSAGE ConnectionRequest
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAcceptConnectPort(
_Out_ PHANDLE PortHandle,
_In_opt_ PVOID PortContext,
_In_ PPORT_MESSAGE ConnectionRequest,
_In_ BOOLEAN AcceptConnection,
_Inout_opt_ PPORT_VIEW ServerView,
_Out_opt_ PREMOTE_PORT_VIEW ClientView
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAcceptConnectPort(
_Out_ PHANDLE PortHandle,
_In_opt_ PVOID PortContext,
_In_ PPORT_MESSAGE ConnectionRequest,
_In_ BOOLEAN AcceptConnection,
_Inout_opt_ PPORT_VIEW ServerView,
_Out_opt_ PREMOTE_PORT_VIEW ClientView
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCompleteConnectPort(
_In_ HANDLE PortHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCompleteConnectPort(
_In_ HANDLE PortHandle
);
// General
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRequestPort(
_In_ HANDLE PortHandle,
_In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRequestPort(
_In_ HANDLE PortHandle,
_In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRequestWaitReplyPort(
_In_ HANDLE PortHandle,
_In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage,
_Out_ PPORT_MESSAGE ReplyMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRequestWaitReplyPort(
_In_ HANDLE PortHandle,
_In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage,
_Out_ PPORT_MESSAGE ReplyMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReplyPort(
_In_ HANDLE PortHandle,
_In_reads_bytes_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReplyPort(
_In_ HANDLE PortHandle,
_In_reads_bytes_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReplyWaitReplyPort(
_In_ HANDLE PortHandle,
_Inout_ PPORT_MESSAGE ReplyMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReplyWaitReplyPort(
_In_ HANDLE PortHandle,
_Inout_ PPORT_MESSAGE ReplyMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReplyWaitReceivePort(
_In_ HANDLE PortHandle,
_Out_opt_ PVOID *PortContext,
_In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
_Out_ PPORT_MESSAGE ReceiveMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReplyWaitReceivePort(
_In_ HANDLE PortHandle,
_Out_opt_ PVOID *PortContext,
_In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
_Out_ PPORT_MESSAGE ReceiveMessage
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReplyWaitReceivePortEx(
_In_ HANDLE PortHandle,
_Out_opt_ PVOID *PortContext,
_In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
_Out_ PPORT_MESSAGE ReceiveMessage,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReplyWaitReceivePortEx(
_In_ HANDLE PortHandle,
_Out_opt_ PVOID *PortContext,
_In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
_Out_ PPORT_MESSAGE ReceiveMessage,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtImpersonateClientOfPort(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwImpersonateClientOfPort(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReadRequestData(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ ULONG DataEntryIndex,
_Out_writes_bytes_to_(BufferSize, *NumberOfBytesRead) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesRead
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReadRequestData(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ ULONG DataEntryIndex,
_Out_writes_bytes_to_(BufferSize, *NumberOfBytesRead) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesRead
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtWriteRequestData(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ ULONG DataEntryIndex,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesWritten
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwWriteRequestData(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ ULONG DataEntryIndex,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ SIZE_T BufferSize,
_Out_opt_ PSIZE_T NumberOfBytesWritten
);
typedef enum _PORT_INFORMATION_CLASS
{
PortBasicInformation,
PortDumpInformation
} PORT_INFORMATION_CLASS;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationPort(
_In_ HANDLE PortHandle,
_In_ PORT_INFORMATION_CLASS PortInformationClass,
_Out_writes_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationPort(
_In_ HANDLE PortHandle,
_In_ PORT_INFORMATION_CLASS PortInformationClass,
_Out_writes_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
// Asynchronous Local Inter-process Communication
// rev
typedef HANDLE ALPC_HANDLE, *PALPC_HANDLE;
#define ALPC_PORFLG_ALLOW_LPC_REQUESTS 0x20000 // rev
#define ALPC_PORFLG_WAITABLE_PORT 0x40000 // dbg
#define ALPC_PORFLG_SYSTEM_PROCESS 0x100000 // dbg
// symbols
typedef struct _ALPC_PORT_ATTRIBUTES
{
ULONG Flags;
SECURITY_QUALITY_OF_SERVICE SecurityQos;
SIZE_T MaxMessageLength;
SIZE_T MemoryBandwidth;
SIZE_T MaxPoolUsage;
SIZE_T MaxSectionSize;
SIZE_T MaxViewSize;
SIZE_T MaxTotalSectionSize;
ULONG DupObjectTypes;
#ifdef _WIN64
ULONG Reserved;
#endif
} ALPC_PORT_ATTRIBUTES, *PALPC_PORT_ATTRIBUTES;
// begin_rev
#define ALPC_MESSAGE_SECURITY_ATTRIBUTE 0x80000000
#define ALPC_MESSAGE_VIEW_ATTRIBUTE 0x40000000
#define ALPC_MESSAGE_CONTEXT_ATTRIBUTE 0x20000000
#define ALPC_MESSAGE_HANDLE_ATTRIBUTE 0x10000000
// end_rev
// symbols
typedef struct _ALPC_MESSAGE_ATTRIBUTES
{
ULONG AllocatedAttributes;
ULONG ValidAttributes;
} ALPC_MESSAGE_ATTRIBUTES, *PALPC_MESSAGE_ATTRIBUTES;
// symbols
typedef struct _ALPC_COMPLETION_LIST_STATE
{
union
{
struct
{
ULONG64 Head : 24;
ULONG64 Tail : 24;
ULONG64 ActiveThreadCount : 16;
} s1;
ULONG64 Value;
} u1;
} ALPC_COMPLETION_LIST_STATE, *PALPC_COMPLETION_LIST_STATE;
#define ALPC_COMPLETION_LIST_BUFFER_GRANULARITY_MASK 0x3f // dbg
// symbols
typedef struct DECLSPEC_ALIGN(128) _ALPC_COMPLETION_LIST_HEADER
{
ULONG64 StartMagic;
ULONG TotalSize;
ULONG ListOffset;
ULONG ListSize;
ULONG BitmapOffset;
ULONG BitmapSize;
ULONG DataOffset;
ULONG DataSize;
ULONG AttributeFlags;
ULONG AttributeSize;
DECLSPEC_ALIGN(128) ALPC_COMPLETION_LIST_STATE State;
ULONG LastMessageId;
ULONG LastCallbackId;
DECLSPEC_ALIGN(128) ULONG PostCount;
DECLSPEC_ALIGN(128) ULONG ReturnCount;
DECLSPEC_ALIGN(128) ULONG LogSequenceNumber;
DECLSPEC_ALIGN(128) RTL_SRWLOCK UserLock;
ULONG64 EndMagic;
} ALPC_COMPLETION_LIST_HEADER, *PALPC_COMPLETION_LIST_HEADER;
// private
typedef struct _ALPC_CONTEXT_ATTR
{
PVOID PortContext;
PVOID MessageContext;
ULONG Sequence;
ULONG MessageId;
ULONG CallbackId;
} ALPC_CONTEXT_ATTR, *PALPC_CONTEXT_ATTR;
// begin_rev
#define ALPC_HANDLEFLG_DUPLICATE_SAME_ACCESS 0x10000
#define ALPC_HANDLEFLG_DUPLICATE_SAME_ATTRIBUTES 0x20000
#define ALPC_HANDLEFLG_DUPLICATE_INHERIT 0x80000
// end_rev
// private
typedef struct _ALPC_HANDLE_ATTR32
{
ULONG Flags;
ULONG Reserved0;
ULONG SameAccess;
ULONG SameAttributes;
ULONG Indirect;
ULONG Inherit;
ULONG Reserved1;
ULONG Handle;
ULONG ObjectType; // ObjectTypeCode, not ObjectTypeIndex
ULONG DesiredAccess;
ULONG GrantedAccess;
} ALPC_HANDLE_ATTR32, *PALPC_HANDLE_ATTR32;
// private
typedef struct _ALPC_HANDLE_ATTR
{
ULONG Flags;
ULONG Reserved0;
ULONG SameAccess;
ULONG SameAttributes;
ULONG Indirect;
ULONG Inherit;
ULONG Reserved1;
HANDLE Handle;
PALPC_HANDLE_ATTR32 HandleAttrArray;
ULONG ObjectType; // ObjectTypeCode, not ObjectTypeIndex
ULONG HandleCount;
ACCESS_MASK DesiredAccess;
ACCESS_MASK GrantedAccess;
} ALPC_HANDLE_ATTR, *PALPC_HANDLE_ATTR;
#define ALPC_SECFLG_CREATE_HANDLE 0x20000 // dbg
#define ALPC_SECFLG_NOSECTIONHANDLE 0x40000
// private
typedef struct _ALPC_SECURITY_ATTR
{
ULONG Flags;
PSECURITY_QUALITY_OF_SERVICE QoS;
ALPC_HANDLE ContextHandle; // dbg
} ALPC_SECURITY_ATTR, *PALPC_SECURITY_ATTR;
// begin_rev
#define ALPC_VIEWFLG_NOT_SECURE 0x40000
// end_rev
// private
typedef struct _ALPC_DATA_VIEW_ATTR
{
ULONG Flags;
ALPC_HANDLE SectionHandle;
PVOID ViewBase; // must be zero on input
SIZE_T ViewSize;
} ALPC_DATA_VIEW_ATTR, *PALPC_DATA_VIEW_ATTR;
// private
typedef enum _ALPC_PORT_INFORMATION_CLASS
{
AlpcBasicInformation, // q: out ALPC_BASIC_INFORMATION
AlpcPortInformation, // s: in ALPC_PORT_ATTRIBUTES
AlpcAssociateCompletionPortInformation, // s: in ALPC_PORT_ASSOCIATE_COMPLETION_PORT
AlpcConnectedSIDInformation, // q: in SID
AlpcServerInformation, // q: inout ALPC_SERVER_INFORMATION
AlpcMessageZoneInformation, // s: in ALPC_PORT_MESSAGE_ZONE_INFORMATION
AlpcRegisterCompletionListInformation, // s: in ALPC_PORT_COMPLETION_LIST_INFORMATION
AlpcUnregisterCompletionListInformation, // s: VOID
AlpcAdjustCompletionListConcurrencyCountInformation, // s: in ULONG
AlpcRegisterCallbackInformation, // kernel-mode only
AlpcCompletionListRundownInformation, // s: VOID
AlpcWaitForPortReferences
} ALPC_PORT_INFORMATION_CLASS;
// private
typedef struct _ALPC_BASIC_INFORMATION
{
ULONG Flags;
ULONG SequenceNo;
PVOID PortContext;
} ALPC_BASIC_INFORMATION, *PALPC_BASIC_INFORMATION;
// private
typedef struct _ALPC_PORT_ASSOCIATE_COMPLETION_PORT
{
PVOID CompletionKey;
HANDLE CompletionPort;
} ALPC_PORT_ASSOCIATE_COMPLETION_PORT, *PALPC_PORT_ASSOCIATE_COMPLETION_PORT;
// private
typedef struct _ALPC_SERVER_INFORMATION
{
union
{
struct
{
HANDLE ThreadHandle;
} In;
struct
{
BOOLEAN ThreadBlocked;
HANDLE ConnectedProcessId;
UNICODE_STRING ConnectionPortName;
} Out;
};
} ALPC_SERVER_INFORMATION, *PALPC_SERVER_INFORMATION;
// private
typedef struct _ALPC_PORT_MESSAGE_ZONE_INFORMATION
{
PVOID Buffer;
ULONG Size;
} ALPC_PORT_MESSAGE_ZONE_INFORMATION, *PALPC_PORT_MESSAGE_ZONE_INFORMATION;
// private
typedef struct _ALPC_PORT_COMPLETION_LIST_INFORMATION
{
PVOID Buffer; // PALPC_COMPLETION_LIST_HEADER
ULONG Size;
ULONG ConcurrencyCount;
ULONG AttributeFlags;
} ALPC_PORT_COMPLETION_LIST_INFORMATION, *PALPC_PORT_COMPLETION_LIST_INFORMATION;
// private
typedef enum _ALPC_MESSAGE_INFORMATION_CLASS
{
AlpcMessageSidInformation, // q: out SID
AlpcMessageTokenModifiedIdInformation, // q: out LUID
AlpcMessageDirectStatusInformation,
AlpcMessageHandleInformation, // ALPC_MESSAGE_HANDLE_INFORMATION
MaxAlpcMessageInfoClass
} ALPC_MESSAGE_INFORMATION_CLASS, *PALPC_MESSAGE_INFORMATION_CLASS;
typedef struct _ALPC_MESSAGE_HANDLE_INFORMATION
{
ULONG Index;
ULONG Flags;
ULONG Handle;
ULONG ObjectType;
ACCESS_MASK GrantedAccess;
} ALPC_MESSAGE_HANDLE_INFORMATION, *PALPC_MESSAGE_HANDLE_INFORMATION;
// begin_private
#if (NTDDI_VERSION >= NTDDI_VISTA)
// System calls
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcCreatePort(
_Out_ PHANDLE PortHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcCreatePort(
_Out_ PHANDLE PortHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcDisconnectPort(
_In_ HANDLE PortHandle,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcDisconnectPort(
_In_ HANDLE PortHandle,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcQueryInformation(
_In_opt_ HANDLE PortHandle,
_In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
_Inout_updates_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcQueryInformation(
_In_opt_ HANDLE PortHandle,
_In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
_Inout_updates_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcSetInformation(
_In_ HANDLE PortHandle,
_In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
_In_reads_bytes_opt_(Length) PVOID PortInformation,
_In_ ULONG Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcSetInformation(
_In_ HANDLE PortHandle,
_In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
_In_reads_bytes_opt_(Length) PVOID PortInformation,
_In_ ULONG Length
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcCreatePortSection(
_In_ HANDLE PortHandle,
_In_ ULONG Flags,
_In_opt_ HANDLE SectionHandle,
_In_ SIZE_T SectionSize,
_Out_ PALPC_HANDLE AlpcSectionHandle,
_Out_ PSIZE_T ActualSectionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcCreatePortSection(
_In_ HANDLE PortHandle,
_In_ ULONG Flags,
_In_opt_ HANDLE SectionHandle,
_In_ SIZE_T SectionSize,
_Out_ PALPC_HANDLE AlpcSectionHandle,
_Out_ PSIZE_T ActualSectionSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcDeletePortSection(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE SectionHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcDeletePortSection(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE SectionHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcCreateResourceReserve(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ SIZE_T MessageSize,
_Out_ PALPC_HANDLE ResourceId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcCreateResourceReserve(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ SIZE_T MessageSize,
_Out_ PALPC_HANDLE ResourceId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcDeleteResourceReserve(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE ResourceId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcDeleteResourceReserve(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE ResourceId
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcCreateSectionView(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_Inout_ PALPC_DATA_VIEW_ATTR ViewAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcCreateSectionView(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_Inout_ PALPC_DATA_VIEW_ATTR ViewAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcDeleteSectionView(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ PVOID ViewBase
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcDeleteSectionView(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ PVOID ViewBase
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcCreateSecurityContext(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_Inout_ PALPC_SECURITY_ATTR SecurityAttribute
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcCreateSecurityContext(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_Inout_ PALPC_SECURITY_ATTR SecurityAttribute
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcDeleteSecurityContext(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE ContextHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcDeleteSecurityContext(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE ContextHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcRevokeSecurityContext(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE ContextHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcRevokeSecurityContext(
_In_ HANDLE PortHandle,
_Reserved_ ULONG Flags,
_In_ ALPC_HANDLE ContextHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcQueryInformationMessage(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE PortMessage,
_In_ ALPC_MESSAGE_INFORMATION_CLASS MessageInformationClass,
_Out_writes_bytes_to_opt_(Length, *ReturnLength) PVOID MessageInformation,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcQueryInformationMessage(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE PortMessage,
_In_ ALPC_MESSAGE_INFORMATION_CLASS MessageInformationClass,
_Out_writes_bytes_to_opt_(Length, *ReturnLength) PVOID MessageInformation,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
#define ALPC_MSGFLG_REPLY_MESSAGE 0x1
#define ALPC_MSGFLG_LPC_MODE 0x2 // ?
#define ALPC_MSGFLG_RELEASE_MESSAGE 0x10000 // dbg
#define ALPC_MSGFLG_SYNC_REQUEST 0x20000 // dbg
#define ALPC_MSGFLG_WAIT_USER_MODE 0x100000
#define ALPC_MSGFLG_WAIT_ALERTABLE 0x200000
#define ALPC_MSGFLG_WOW64_CALL 0x80000000 // dbg
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcConnectPort(
_Out_ PHANDLE PortHandle,
_In_ PUNICODE_STRING PortName,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
_In_ ULONG Flags,
_In_opt_ PSID RequiredServerSid,
_Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
_Inout_opt_ PULONG BufferLength,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcConnectPort(
_Out_ PHANDLE PortHandle,
_In_ PUNICODE_STRING PortName,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
_In_ ULONG Flags,
_In_opt_ PSID RequiredServerSid,
_Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
_Inout_opt_ PULONG BufferLength,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
_In_opt_ PLARGE_INTEGER Timeout
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcConnectPortEx(
_Out_ PHANDLE PortHandle,
_In_ POBJECT_ATTRIBUTES ConnectionPortObjectAttributes,
_In_opt_ POBJECT_ATTRIBUTES ClientPortObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
_In_ ULONG Flags,
_In_opt_ PSECURITY_DESCRIPTOR ServerSecurityRequirements,
_Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
_Inout_opt_ PSIZE_T BufferLength,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcConnectPortEx(
_Out_ PHANDLE PortHandle,
_In_ POBJECT_ATTRIBUTES ConnectionPortObjectAttributes,
_In_opt_ POBJECT_ATTRIBUTES ClientPortObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
_In_ ULONG Flags,
_In_opt_ PSECURITY_DESCRIPTOR ServerSecurityRequirements,
_Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
_Inout_opt_ PSIZE_T BufferLength,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
_In_opt_ PLARGE_INTEGER Timeout
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcAcceptConnectPort(
_Out_ PHANDLE PortHandle,
_In_ HANDLE ConnectionPortHandle,
_In_ ULONG Flags,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
_In_opt_ PVOID PortContext,
_In_reads_bytes_(ConnectionRequest->u1.s1.TotalLength) PPORT_MESSAGE ConnectionRequest,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes,
_In_ BOOLEAN AcceptConnection
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcAcceptConnectPort(
_Out_ PHANDLE PortHandle,
_In_ HANDLE ConnectionPortHandle,
_In_ ULONG Flags,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
_In_opt_ PVOID PortContext,
_In_reads_bytes_(ConnectionRequest->u1.s1.TotalLength) PPORT_MESSAGE ConnectionRequest,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes,
_In_ BOOLEAN AcceptConnection
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcSendWaitReceivePort(
_In_ HANDLE PortHandle,
_In_ ULONG Flags,
_In_reads_bytes_opt_(SendMessage->u1.s1.TotalLength) PPORT_MESSAGE SendMessage,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES SendMessageAttributes,
_Out_writes_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ReceiveMessage,
_Inout_opt_ PSIZE_T BufferLength,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ReceiveMessageAttributes,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcSendWaitReceivePort(
_In_ HANDLE PortHandle,
_In_ ULONG Flags,
_In_reads_bytes_opt_(SendMessage->u1.s1.TotalLength) PPORT_MESSAGE SendMessage,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES SendMessageAttributes,
_Out_writes_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ReceiveMessage,
_Inout_opt_ PSIZE_T BufferLength,
_Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ReceiveMessageAttributes,
_In_opt_ PLARGE_INTEGER Timeout
);
#define ALPC_CANCELFLG_TRY_CANCEL 0x1 // dbg
#define ALPC_CANCELFLG_NO_CONTEXT_CHECK 0x8
#define ALPC_CANCELFLGP_FLUSH 0x10000 // dbg
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcCancelMessage(
_In_ HANDLE PortHandle,
_In_ ULONG Flags,
_In_ PALPC_CONTEXT_ATTR MessageContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcCancelMessage(
_In_ HANDLE PortHandle,
_In_ ULONG Flags,
_In_ PALPC_CONTEXT_ATTR MessageContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcImpersonateClientOfPort(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ PVOID Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcImpersonateClientOfPort(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ PVOID Flags
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcImpersonateClientContainerOfPort(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcImpersonateClientContainerOfPort(
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE Message,
_In_ ULONG Flags
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcOpenSenderProcess(
_Out_ PHANDLE ProcessHandle,
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE PortMessage,
_In_ ULONG Flags,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcOpenSenderProcess(
_Out_ PHANDLE ProcessHandle,
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE PortMessage,
_In_ ULONG Flags,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAlpcOpenSenderThread(
_Out_ PHANDLE ThreadHandle,
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE PortMessage,
_In_ ULONG Flags,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAlpcOpenSenderThread(
_Out_ PHANDLE ThreadHandle,
_In_ HANDLE PortHandle,
_In_ PPORT_MESSAGE PortMessage,
_In_ ULONG Flags,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
// Support functions
NTSYSAPI
ULONG
NTAPI
AlpcMaxAllowedMessageLength(
VOID
);
NTSYSAPI
ULONG
NTAPI
AlpcGetHeaderSize(
_In_ ULONG Flags
);
#define ALPC_ATTRFLG_ALLOCATEDATTR 0x20000000
#define ALPC_ATTRFLG_VALIDATTR 0x40000000
#define ALPC_ATTRFLG_KEEPRUNNINGATTR 0x60000000
NTSYSAPI
NTSTATUS
NTAPI
AlpcInitializeMessageAttribute(
_In_ ULONG AttributeFlags,
_Out_opt_ PALPC_MESSAGE_ATTRIBUTES Buffer,
_In_ ULONG BufferSize,
_Out_ PULONG RequiredBufferSize
);
NTSYSAPI
PVOID
NTAPI
AlpcGetMessageAttribute(
_In_ PALPC_MESSAGE_ATTRIBUTES Buffer,
_In_ ULONG AttributeFlag
);
NTSYSAPI
NTSTATUS
NTAPI
AlpcRegisterCompletionList(
_In_ HANDLE PortHandle,
_Out_ PALPC_COMPLETION_LIST_HEADER Buffer,
_In_ ULONG Size,
_In_ ULONG ConcurrencyCount,
_In_ ULONG AttributeFlags
);
NTSYSAPI
NTSTATUS
NTAPI
AlpcUnregisterCompletionList(
_In_ HANDLE PortHandle
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
AlpcRundownCompletionList(
_In_ HANDLE PortHandle
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
AlpcAdjustCompletionListConcurrencyCount(
_In_ HANDLE PortHandle,
_In_ ULONG ConcurrencyCount
);
NTSYSAPI
BOOLEAN
NTAPI
AlpcRegisterCompletionListWorkerThread(
_Inout_ PVOID CompletionList
);
NTSYSAPI
BOOLEAN
NTAPI
AlpcUnregisterCompletionListWorkerThread(
_Inout_ PVOID CompletionList
);
NTSYSAPI
VOID
NTAPI
AlpcGetCompletionListLastMessageInformation(
_In_ PVOID CompletionList,
_Out_ PULONG LastMessageId,
_Out_ PULONG LastCallbackId
);
NTSYSAPI
ULONG
NTAPI
AlpcGetOutstandingCompletionListMessageCount(
_In_ PVOID CompletionList
);
NTSYSAPI
PPORT_MESSAGE
NTAPI
AlpcGetMessageFromCompletionList(
_In_ PVOID CompletionList,
_Out_opt_ PALPC_MESSAGE_ATTRIBUTES *MessageAttributes
);
NTSYSAPI
VOID
NTAPI
AlpcFreeCompletionListMessage(
_Inout_ PVOID CompletionList,
_In_ PPORT_MESSAGE Message
);
NTSYSAPI
PALPC_MESSAGE_ATTRIBUTES
NTAPI
AlpcGetCompletionListMessageAttributes(
_In_ PVOID CompletionList,
_In_ PPORT_MESSAGE Message
);
#endif
// end_private
// #include <ntpfapi.h>
// begin_private
// Prefetch
typedef enum _PF_BOOT_PHASE_ID
{
PfKernelInitPhase = 0,
PfBootDriverInitPhase = 90,
PfSystemDriverInitPhase = 120,
PfSessionManagerInitPhase = 150,
PfSMRegistryInitPhase = 180,
PfVideoInitPhase = 210,
PfPostVideoInitPhase = 240,
PfBootAcceptedRegistryInitPhase = 270,
PfUserShellReadyPhase = 300,
PfMaxBootPhaseId = 900
} PF_BOOT_PHASE_ID;
typedef enum _PF_ENABLE_STATUS
{
PfSvNotSpecified,
PfSvEnabled,
PfSvDisabled,
PfSvMaxEnableStatus
} PF_ENABLE_STATUS;
typedef struct _PF_TRACE_LIMITS
{
ULONG MaxNumPages;
ULONG MaxNumSections;
LONGLONG TimerPeriod;
} PF_TRACE_LIMITS, *PPF_TRACE_LIMITS;
typedef struct _PF_SYSTEM_PREFETCH_PARAMETERS
{
PF_ENABLE_STATUS EnableStatus[2];
PF_TRACE_LIMITS TraceLimits[2];
ULONG MaxNumActiveTraces;
ULONG MaxNumSavedTraces;
WCHAR RootDirPath[32];
WCHAR HostingApplicationList[128];
} PF_SYSTEM_PREFETCH_PARAMETERS, *PPF_SYSTEM_PREFETCH_PARAMETERS;
#define PF_BOOT_CONTROL_VERSION 1
typedef struct _PF_BOOT_CONTROL
{
ULONG Version;
ULONG DisableBootPrefetching;
} PF_BOOT_CONTROL, *PPF_BOOT_CONTROL;
typedef enum _PREFETCHER_INFORMATION_CLASS
{
PrefetcherRetrieveTrace = 1, // q: CHAR[]
PrefetcherSystemParameters, // q: PF_SYSTEM_PREFETCH_PARAMETERS
PrefetcherBootPhase, // s: PF_BOOT_PHASE_ID
PrefetcherRetrieveBootLoaderTrace, // q: CHAR[]
PrefetcherBootControl // s: PF_BOOT_CONTROL
} PREFETCHER_INFORMATION_CLASS;
#define PREFETCHER_INFORMATION_VERSION 23 // rev
#define PREFETCHER_INFORMATION_MAGIC ('kuhC') // rev
typedef struct _PREFETCHER_INFORMATION
{
ULONG Version;
ULONG Magic;
PREFETCHER_INFORMATION_CLASS PrefetcherInformationClass;
PVOID PrefetcherInformation;
ULONG PrefetcherInformationLength;
} PREFETCHER_INFORMATION, *PPREFETCHER_INFORMATION;
// Superfetch
typedef struct _PF_SYSTEM_SUPERFETCH_PARAMETERS
{
ULONG EnabledComponents;
ULONG BootID;
ULONG SavedSectInfoTracesMax;
ULONG SavedPageAccessTracesMax;
ULONG ScenarioPrefetchTimeoutStandby;
ULONG ScenarioPrefetchTimeoutHibernate;
} PF_SYSTEM_SUPERFETCH_PARAMETERS, *PPF_SYSTEM_SUPERFETCH_PARAMETERS;
#define PF_PFN_PRIO_REQUEST_VERSION 1
#define PF_PFN_PRIO_REQUEST_QUERY_MEMORY_LIST 0x1
#define PF_PFN_PRIO_REQUEST_VALID_FLAGS 0x1
typedef struct _PF_PFN_PRIO_REQUEST
{
ULONG Version;
ULONG RequestFlags;
ULONG_PTR PfnCount;
SYSTEM_MEMORY_LIST_INFORMATION MemInfo;
MMPFN_IDENTITY PageData[256];
} PF_PFN_PRIO_REQUEST, *PPF_PFN_PRIO_REQUEST;
typedef enum _PFS_PRIVATE_PAGE_SOURCE_TYPE
{
PfsPrivateSourceKernel,
PfsPrivateSourceSession,
PfsPrivateSourceProcess,
PfsPrivateSourceMax
} PFS_PRIVATE_PAGE_SOURCE_TYPE;
typedef struct _PFS_PRIVATE_PAGE_SOURCE
{
PFS_PRIVATE_PAGE_SOURCE_TYPE Type;
union
{
ULONG SessionId;
ULONG ProcessId;
};
ULONG ImagePathHash;
ULONG_PTR UniqueProcessHash;
} PFS_PRIVATE_PAGE_SOURCE, *PPFS_PRIVATE_PAGE_SOURCE;
typedef struct _PF_PRIVSOURCE_INFO
{
PFS_PRIVATE_PAGE_SOURCE DbInfo;
PVOID EProcess;
SIZE_T WsPrivatePages;
SIZE_T TotalPrivatePages;
ULONG SessionID;
CHAR ImageName[16];
union {
ULONG_PTR WsSwapPages; // process only PF_PRIVSOURCE_QUERY_WS_SWAP_PAGES.
ULONG_PTR SessionPagedPoolPages; // session only.
ULONG_PTR StoreSizePages; // process only PF_PRIVSOURCE_QUERY_STORE_INFO.
};
ULONG_PTR WsTotalPages; // process/session only.
ULONG DeepFreezeTimeMs; // process only.
ULONG ModernApp : 1; // process only.
ULONG DeepFrozen : 1; // process only. If set, DeepFreezeTimeMs contains the time at which the freeze occurred
ULONG Foreground : 1; // process only.
ULONG PerProcessStore : 1; // process only.
ULONG Spare : 28;
} PF_PRIVSOURCE_INFO, *PPF_PRIVSOURCE_INFO;
#define PF_PRIVSOURCE_QUERY_REQUEST_VERSION 8
typedef struct _PF_PRIVSOURCE_QUERY_REQUEST
{
ULONG Version;
ULONG Flags;
ULONG InfoCount;
PF_PRIVSOURCE_INFO InfoArray[1];
} PF_PRIVSOURCE_QUERY_REQUEST, *PPF_PRIVSOURCE_QUERY_REQUEST;
typedef enum _PF_PHASED_SCENARIO_TYPE
{
PfScenarioTypeNone,
PfScenarioTypeStandby,
PfScenarioTypeHibernate,
PfScenarioTypeFUS,
PfScenarioTypeMax
} PF_PHASED_SCENARIO_TYPE;
#define PF_SCENARIO_PHASE_INFO_VERSION 4
typedef struct _PF_SCENARIO_PHASE_INFO
{
ULONG Version;
PF_PHASED_SCENARIO_TYPE ScenType;
ULONG PhaseId;
ULONG SequenceNumber;
ULONG Flags;
ULONG FUSUserId;
} PF_SCENARIO_PHASE_INFO, *PPF_SCENARIO_PHASE_INFO;
typedef struct _PF_MEMORY_LIST_NODE
{
ULONGLONG Node : 8;
ULONGLONG Spare : 56;
ULONGLONG StandbyLowPageCount;
ULONGLONG StandbyMediumPageCount;
ULONGLONG StandbyHighPageCount;
ULONGLONG FreePageCount;
ULONGLONG ModifiedPageCount;
} PF_MEMORY_LIST_NODE, *PPF_MEMORY_LIST_NODE;
#define PF_MEMORY_LIST_INFO_VERSION 1
typedef struct _PF_MEMORY_LIST_INFO
{
ULONG Version;
ULONG Size;
ULONG NodeCount;
PF_MEMORY_LIST_NODE Nodes[1];
} PF_MEMORY_LIST_INFO, *PPF_MEMORY_LIST_INFO;
typedef struct _PF_PHYSICAL_MEMORY_RANGE
{
ULONG_PTR BasePfn;
ULONG_PTR PageCount;
} PF_PHYSICAL_MEMORY_RANGE, *PPF_PHYSICAL_MEMORY_RANGE;
#define PF_PHYSICAL_MEMORY_RANGE_INFO_VERSION 1
typedef struct _PF_PHYSICAL_MEMORY_RANGE_INFO
{
ULONG Version;
ULONG RangeCount;
PF_PHYSICAL_MEMORY_RANGE Ranges[1];
} PF_PHYSICAL_MEMORY_RANGE_INFO, *PPF_PHYSICAL_MEMORY_RANGE_INFO;
// begin_rev
#define PF_REPURPOSED_BY_PREFETCH_INFO_VERSION 1
typedef struct _PF_REPURPOSED_BY_PREFETCH_INFO
{
ULONG Version;
ULONG RepurposedByPrefetch;
} PF_REPURPOSED_BY_PREFETCH_INFO, *PPF_REPURPOSED_BY_PREFETCH_INFO;
// end_rev
typedef enum _SUPERFETCH_INFORMATION_CLASS
{
SuperfetchRetrieveTrace = 1, // q: CHAR[]
SuperfetchSystemParameters, // q: PF_SYSTEM_SUPERFETCH_PARAMETERS
SuperfetchLogEvent,
SuperfetchGenerateTrace,
SuperfetchPrefetch,
SuperfetchPfnQuery, // q: PF_PFN_PRIO_REQUEST
SuperfetchPfnSetPriority,
SuperfetchPrivSourceQuery, // q: PF_PRIVSOURCE_QUERY_REQUEST
SuperfetchSequenceNumberQuery, // q: ULONG
SuperfetchScenarioPhase, // 10
SuperfetchWorkerPriority,
SuperfetchScenarioQuery, // q: PF_SCENARIO_PHASE_INFO
SuperfetchScenarioPrefetch,
SuperfetchRobustnessControl,
SuperfetchTimeControl,
SuperfetchMemoryListQuery, // q: PF_MEMORY_LIST_INFO
SuperfetchMemoryRangesQuery, // q: PF_PHYSICAL_MEMORY_RANGE_INFO
SuperfetchTracingControl,
SuperfetchTrimWhileAgingControl,
SuperfetchRepurposedByPrefetch, // q: PF_REPURPOSED_BY_PREFETCH_INFO // rev
SuperfetchInformationMax
} SUPERFETCH_INFORMATION_CLASS;
#define SUPERFETCH_INFORMATION_VERSION 45 // rev
#define SUPERFETCH_INFORMATION_MAGIC ('kuhC') // rev
typedef struct _SUPERFETCH_INFORMATION
{
_In_ ULONG Version;
_In_ ULONG Magic;
_In_ SUPERFETCH_INFORMATION_CLASS InfoClass;
_Inout_ PVOID Data;
_Inout_ ULONG Length;
} SUPERFETCH_INFORMATION, *PSUPERFETCH_INFORMATION;
// end_private
// #include <ntpnpapi.h>
typedef enum _PLUGPLAY_EVENT_CATEGORY
{
HardwareProfileChangeEvent,
TargetDeviceChangeEvent,
DeviceClassChangeEvent,
CustomDeviceEvent,
DeviceInstallEvent,
DeviceArrivalEvent,
PowerEvent,
VetoEvent,
BlockedDriverEvent,
InvalidIDEvent,
MaxPlugEventCategory
} PLUGPLAY_EVENT_CATEGORY, *PPLUGPLAY_EVENT_CATEGORY;
typedef struct _PLUGPLAY_EVENT_BLOCK
{
GUID EventGuid;
PLUGPLAY_EVENT_CATEGORY EventCategory;
PULONG Result;
ULONG Flags;
ULONG TotalSize;
PVOID DeviceObject;
union
{
struct
{
GUID ClassGuid;
WCHAR SymbolicLinkName[1];
} DeviceClass;
struct
{
WCHAR DeviceIds[1];
} TargetDevice;
struct
{
WCHAR DeviceId[1];
} InstallDevice;
struct
{
PVOID NotificationStructure;
WCHAR DeviceIds[1];
} CustomNotification;
struct
{
PVOID Notification;
} ProfileNotification;
struct
{
ULONG NotificationCode;
ULONG NotificationData;
} PowerNotification;
struct
{
PNP_VETO_TYPE VetoType;
WCHAR DeviceIdVetoNameBuffer[1]; // DeviceId<null>VetoName<null><null>
} VetoNotification;
struct
{
GUID BlockedDriverGuid;
} BlockedDriverNotification;
struct
{
WCHAR ParentId[1];
} InvalidIDNotification;
} u;
} PLUGPLAY_EVENT_BLOCK, *PPLUGPLAY_EVENT_BLOCK;
typedef enum _PLUGPLAY_CONTROL_CLASS
{
PlugPlayControlEnumerateDevice,
PlugPlayControlRegisterNewDevice,
PlugPlayControlDeregisterDevice,
PlugPlayControlInitializeDevice,
PlugPlayControlStartDevice,
PlugPlayControlUnlockDevice,
PlugPlayControlQueryAndRemoveDevice,
PlugPlayControlUserResponse,
PlugPlayControlGenerateLegacyDevice,
PlugPlayControlGetInterfaceDeviceList,
PlugPlayControlProperty,
PlugPlayControlDeviceClassAssociation,
PlugPlayControlGetRelatedDevice,
PlugPlayControlGetInterfaceDeviceAlias,
PlugPlayControlDeviceStatus,
PlugPlayControlGetDeviceDepth,
PlugPlayControlQueryDeviceRelations,
PlugPlayControlTargetDeviceRelation,
PlugPlayControlQueryConflictList,
PlugPlayControlRetrieveDock,
PlugPlayControlResetDevice,
PlugPlayControlHaltDevice,
PlugPlayControlGetBlockedDriverList,
PlugPlayControlGetDeviceInterfaceEnabled,
MaxPlugPlayControl
} PLUGPLAY_CONTROL_CLASS, *PPLUGPLAY_CONTROL_CLASS;
#if (NTDDI_VERSION < NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetPlugPlayEvent(
_In_ HANDLE EventHandle,
_In_opt_ PVOID Context,
_Out_writes_bytes_(EventBufferSize) PPLUGPLAY_EVENT_BLOCK EventBlock,
_In_ ULONG EventBufferSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetPlugPlayEvent(
_In_ HANDLE EventHandle,
_In_opt_ PVOID Context,
_Out_writes_bytes_(EventBufferSize) PPLUGPLAY_EVENT_BLOCK EventBlock,
_In_ ULONG EventBufferSize
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPlugPlayControl(
_In_ PLUGPLAY_CONTROL_CLASS PnPControlClass,
_Inout_updates_bytes_(PnPControlDataLength) PVOID PnPControlData,
_In_ ULONG PnPControlDataLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPlugPlayControl(
_In_ PLUGPLAY_CONTROL_CLASS PnPControlClass,
_Inout_updates_bytes_(PnPControlDataLength) PVOID PnPControlData,
_In_ ULONG PnPControlDataLength
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSerializeBoot(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSerializeBoot(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnableLastKnownGood(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnableLastKnownGood(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDisableLastKnownGood(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDisableLastKnownGood(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReplacePartitionUnit(
_In_ PUNICODE_STRING TargetInstancePath,
_In_ PUNICODE_STRING SpareInstancePath,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReplacePartitionUnit(
_In_ PUNICODE_STRING TargetInstancePath,
_In_ PUNICODE_STRING SpareInstancePath,
_In_ ULONG Flags
);
#endif
// #include <ntpoapi.h>
typedef union _POWER_STATE
{
SYSTEM_POWER_STATE SystemState;
DEVICE_POWER_STATE DeviceState;
} POWER_STATE, *PPOWER_STATE;
typedef enum _POWER_STATE_TYPE
{
SystemPowerState = 0,
DevicePowerState
} POWER_STATE_TYPE, *PPOWER_STATE_TYPE;
#if (NTDDI_VERSION >= NTDDI_VISTA)
// wdm
typedef struct _SYSTEM_POWER_STATE_CONTEXT
{
union
{
struct
{
ULONG Reserved1 : 8;
ULONG TargetSystemState : 4;
ULONG EffectiveSystemState : 4;
ULONG CurrentSystemState : 4;
ULONG IgnoreHibernationPath : 1;
ULONG PseudoTransition : 1;
ULONG Reserved2 : 10;
};
ULONG ContextAsUlong;
};
} SYSTEM_POWER_STATE_CONTEXT, *PSYSTEM_POWER_STATE_CONTEXT;
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
/** \cond NEVER */ // disable doxygen warning
// wdm
typedef struct _COUNTED_REASON_CONTEXT
{
ULONG Version;
ULONG Flags;
union
{
struct
{
UNICODE_STRING ResourceFileName;
USHORT ResourceReasonId;
ULONG StringCount;
PUNICODE_STRING _Field_size_(StringCount) ReasonStrings;
};
UNICODE_STRING SimpleString;
};
} COUNTED_REASON_CONTEXT, *PCOUNTED_REASON_CONTEXT;
/** \endcond */
#endif
typedef enum _POWER_STATE_HANDLER_TYPE
{
PowerStateSleeping1 = 0,
PowerStateSleeping2 = 1,
PowerStateSleeping3 = 2,
PowerStateSleeping4 = 3,
PowerStateShutdownOff = 4,
PowerStateShutdownReset = 5,
PowerStateSleeping4Firmware = 6,
PowerStateMaximum = 7
} POWER_STATE_HANDLER_TYPE, *PPOWER_STATE_HANDLER_TYPE;
typedef NTSTATUS (NTAPI *PENTER_STATE_SYSTEM_HANDLER)(
_In_ PVOID SystemContext
);
typedef NTSTATUS (NTAPI *PENTER_STATE_HANDLER)(
_In_ PVOID Context,
_In_opt_ PENTER_STATE_SYSTEM_HANDLER SystemHandler,
_In_ PVOID SystemContext,
_In_ LONG NumberProcessors,
_In_ volatile PLONG Number
);
typedef struct _POWER_STATE_HANDLER
{
POWER_STATE_HANDLER_TYPE Type;
BOOLEAN RtcWake;
UCHAR Spare[3];
PENTER_STATE_HANDLER Handler;
PVOID Context;
} POWER_STATE_HANDLER, *PPOWER_STATE_HANDLER;
typedef NTSTATUS (NTAPI *PENTER_STATE_NOTIFY_HANDLER)(
_In_ POWER_STATE_HANDLER_TYPE State,
_In_ PVOID Context,
_In_ BOOLEAN Entering
);
typedef struct _POWER_STATE_NOTIFY_HANDLER
{
PENTER_STATE_NOTIFY_HANDLER Handler;
PVOID Context;
} POWER_STATE_NOTIFY_HANDLER, *PPOWER_STATE_NOTIFY_HANDLER;
typedef struct _PROCESSOR_POWER_INFORMATION
{
ULONG Number;
ULONG MaxMhz;
ULONG CurrentMhz;
ULONG MhzLimit;
ULONG MaxIdleState;
ULONG CurrentIdleState;
} PROCESSOR_POWER_INFORMATION, *PPROCESSOR_POWER_INFORMATION;
typedef struct _SYSTEM_POWER_INFORMATION
{
ULONG MaxIdlenessAllowed;
ULONG Idleness;
ULONG TimeRemaining;
UCHAR CoolingMode;
} SYSTEM_POWER_INFORMATION, *PSYSTEM_POWER_INFORMATION;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPowerInformation(
_In_ POWER_INFORMATION_LEVEL InformationLevel,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPowerInformation(
_In_ POWER_INFORMATION_LEVEL InformationLevel,
_In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
_In_ ULONG InputBufferLength,
_Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetThreadExecutionState(
_In_ EXECUTION_STATE NewFlags, // ES_* flags
_Out_ EXECUTION_STATE *PreviousFlags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetThreadExecutionState(
_In_ EXECUTION_STATE NewFlags, // ES_* flags
_Out_ EXECUTION_STATE *PreviousFlags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRequestWakeupLatency(
_In_ LATENCY_TIME latency
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRequestWakeupLatency(
_In_ LATENCY_TIME latency
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtInitiatePowerAction(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags, // POWER_ACTION_* flags
_In_ BOOLEAN Asynchronous
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwInitiatePowerAction(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags, // POWER_ACTION_* flags
_In_ BOOLEAN Asynchronous
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetSystemPowerState(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags // POWER_ACTION_* flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetSystemPowerState(
_In_ POWER_ACTION SystemAction,
_In_ SYSTEM_POWER_STATE LightestSystemState,
_In_ ULONG Flags // POWER_ACTION_* flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetDevicePowerState(
_In_ HANDLE Device,
_Out_ PDEVICE_POWER_STATE State
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetDevicePowerState(
_In_ HANDLE Device,
_Out_ PDEVICE_POWER_STATE State
);
NTSYSCALLAPI
BOOLEAN
NTAPI
NtIsSystemResumeAutomatic(
VOID
);
NTSYSCALLAPI
BOOLEAN
NTAPI
ZwIsSystemResumeAutomatic(
VOID
);
// #include <ntregapi.h>
// Boot condition flags (NtInitializeRegistry)
#define REG_INIT_BOOT_SM 0x0000
#define REG_INIT_BOOT_SETUP 0x0001
#define REG_INIT_BOOT_ACCEPTED_BASE 0x0002
#define REG_INIT_BOOT_ACCEPTED_MAX REG_INIT_BOOT_ACCEPTED_BASE + 999
#define REG_MAX_KEY_VALUE_NAME_LENGTH 32767
#define REG_MAX_KEY_NAME_LENGTH 512
typedef enum _KEY_INFORMATION_CLASS
{
KeyBasicInformation, // KEY_BASIC_INFORMATION
KeyNodeInformation, // KEY_NODE_INFORMATION
KeyFullInformation, // KEY_FULL_INFORMATION
KeyNameInformation, // KEY_NAME_INFORMATION
KeyCachedInformation, // KEY_CACHED_INFORMATION
KeyFlagsInformation, // KEY_FLAGS_INFORMATION
KeyVirtualizationInformation, // KEY_VIRTUALIZATION_INFORMATION
KeyHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION
KeyTrustInformation, // KEY_TRUST_INFORMATION
KeyLayerInformation, // KEY_LAYER_INFORMATION
MaxKeyInfoClass
} KEY_INFORMATION_CLASS;
typedef struct _KEY_BASIC_INFORMATION
{
LARGE_INTEGER LastWriteTime;
ULONG TitleIndex;
ULONG NameLength;
WCHAR Name[1];
} KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION;
typedef struct _KEY_NODE_INFORMATION
{
LARGE_INTEGER LastWriteTime;
ULONG TitleIndex;
ULONG ClassOffset;
ULONG ClassLength;
ULONG NameLength;
WCHAR Name[1];
// ...
// WCHAR Class[1];
} KEY_NODE_INFORMATION, *PKEY_NODE_INFORMATION;
typedef struct _KEY_FULL_INFORMATION
{
LARGE_INTEGER LastWriteTime;
ULONG TitleIndex;
ULONG ClassOffset;
ULONG ClassLength;
ULONG SubKeys;
ULONG MaxNameLen;
ULONG MaxClassLen;
ULONG Values;
ULONG MaxValueNameLen;
ULONG MaxValueDataLen;
WCHAR Class[1];
} KEY_FULL_INFORMATION, *PKEY_FULL_INFORMATION;
typedef struct _KEY_NAME_INFORMATION
{
ULONG NameLength;
WCHAR Name[1];
} KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION;
typedef struct _KEY_CACHED_INFORMATION
{
LARGE_INTEGER LastWriteTime;
ULONG TitleIndex;
ULONG SubKeys;
ULONG MaxNameLen;
ULONG Values;
ULONG MaxValueNameLen;
ULONG MaxValueDataLen;
ULONG NameLength;
WCHAR Name[1];
} KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION;
typedef struct _KEY_FLAGS_INFORMATION
{
ULONG UserFlags;
} KEY_FLAGS_INFORMATION, *PKEY_FLAGS_INFORMATION;
typedef struct _KEY_VIRTUALIZATION_INFORMATION
{
ULONG VirtualizationCandidate : 1; // Tells whether the key is part of the virtualization namespace scope (only HKLM\Software for now).
ULONG VirtualizationEnabled : 1; // Tells whether virtualization is enabled on this key. Can be 1 only if above flag is 1.
ULONG VirtualTarget : 1; // Tells if the key is a virtual key. Can be 1 only if above 2 are 0. Valid only on the virtual store key handles.
ULONG VirtualStore : 1; // Tells if the key is a part of the virtual store path. Valid only on the virtual store key handles.
ULONG VirtualSource : 1; // Tells if the key has ever been virtualized, can be 1 only if VirtualizationCandidate is 1.
ULONG Reserved : 27;
} KEY_VIRTUALIZATION_INFORMATION, *PKEY_VIRTUALIZATION_INFORMATION;
// private
typedef struct _KEY_TRUST_INFORMATION
{
ULONG TrustedKey : 1;
ULONG Reserved : 31;
} KEY_TRUST_INFORMATION, *PKEY_TRUST_INFORMATION;
// private
typedef struct _KEY_LAYER_INFORMATION
{
ULONG IsTombstone;
ULONG IsSupersedeLocal;
ULONG IsSupersedeTree;
ULONG ClassIsInherited;
ULONG Reserved;
} KEY_LAYER_INFORMATION, *PKEY_LAYER_INFORMATION;
typedef enum _KEY_SET_INFORMATION_CLASS
{
KeyWriteTimeInformation, // KEY_WRITE_TIME_INFORMATION
KeyWow64FlagsInformation, // KEY_WOW64_FLAGS_INFORMATION
KeyControlFlagsInformation, // KEY_CONTROL_FLAGS_INFORMATION
KeySetVirtualizationInformation, // KEY_SET_VIRTUALIZATION_INFORMATION
KeySetDebugInformation,
KeySetHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION
KeySetLayerInformation, // KEY_SET_LAYER_INFORMATION
MaxKeySetInfoClass
} KEY_SET_INFORMATION_CLASS;
typedef struct _KEY_WRITE_TIME_INFORMATION
{
LARGE_INTEGER LastWriteTime;
} KEY_WRITE_TIME_INFORMATION, *PKEY_WRITE_TIME_INFORMATION;
typedef struct _KEY_WOW64_FLAGS_INFORMATION
{
ULONG UserFlags;
} KEY_WOW64_FLAGS_INFORMATION, *PKEY_WOW64_FLAGS_INFORMATION;
typedef struct _KEY_HANDLE_TAGS_INFORMATION
{
ULONG HandleTags;
} KEY_HANDLE_TAGS_INFORMATION, *PKEY_HANDLE_TAGS_INFORMATION;
typedef struct _KEY_SET_LAYER_INFORMATION
{
ULONG IsTombstone : 1;
ULONG IsSupersedeLocal : 1;
ULONG IsSupersedeTree : 1;
ULONG ClassIsInherited : 1;
ULONG Reserved : 28;
} KEY_SET_LAYER_INFORMATION, *PKEY_SET_LAYER_INFORMATION;
typedef struct _KEY_CONTROL_FLAGS_INFORMATION
{
ULONG ControlFlags;
} KEY_CONTROL_FLAGS_INFORMATION, *PKEY_CONTROL_FLAGS_INFORMATION;
typedef struct _KEY_SET_VIRTUALIZATION_INFORMATION
{
ULONG VirtualTarget : 1;
ULONG VirtualStore : 1;
ULONG VirtualSource : 1; // true if key has been virtualized at least once
ULONG Reserved : 29;
} KEY_SET_VIRTUALIZATION_INFORMATION, *PKEY_SET_VIRTUALIZATION_INFORMATION;
typedef enum _KEY_VALUE_INFORMATION_CLASS
{
KeyValueBasicInformation, // KEY_VALUE_BASIC_INFORMATION
KeyValueFullInformation, // KEY_VALUE_FULL_INFORMATION
KeyValuePartialInformation, // KEY_VALUE_PARTIAL_INFORMATION
KeyValueFullInformationAlign64,
KeyValuePartialInformationAlign64, // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64
KeyValueLayerInformation, // KEY_VALUE_LAYER_INFORMATION
MaxKeyValueInfoClass
} KEY_VALUE_INFORMATION_CLASS;
typedef struct _KEY_VALUE_BASIC_INFORMATION
{
ULONG TitleIndex;
ULONG Type;
ULONG NameLength;
WCHAR Name[1];
} KEY_VALUE_BASIC_INFORMATION, *PKEY_VALUE_BASIC_INFORMATION;
typedef struct _KEY_VALUE_FULL_INFORMATION
{
ULONG TitleIndex;
ULONG Type;
ULONG DataOffset;
ULONG DataLength;
ULONG NameLength;
WCHAR Name[1];
// ...
// UCHAR Data[1];
} KEY_VALUE_FULL_INFORMATION, *PKEY_VALUE_FULL_INFORMATION;
typedef struct _KEY_VALUE_PARTIAL_INFORMATION
{
ULONG TitleIndex;
ULONG Type;
ULONG DataLength;
UCHAR Data[1];
} KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION;
typedef struct _KEY_VALUE_PARTIAL_INFORMATION_ALIGN64
{
ULONG Type;
ULONG DataLength;
UCHAR Data[1];
} KEY_VALUE_PARTIAL_INFORMATION_ALIGN64, *PKEY_VALUE_PARTIAL_INFORMATION_ALIGN64;
// private
typedef struct _KEY_VALUE_LAYER_INFORMATION
{
ULONG IsTombstone;
ULONG Reserved;
} KEY_VALUE_LAYER_INFORMATION, *PKEY_VALUE_LAYER_INFORMATION;
typedef struct _KEY_VALUE_ENTRY
{
PUNICODE_STRING ValueName;
ULONG DataLength;
ULONG DataOffset;
ULONG Type;
} KEY_VALUE_ENTRY, *PKEY_VALUE_ENTRY;
typedef enum _REG_ACTION
{
KeyAdded,
KeyRemoved,
KeyModified
} REG_ACTION;
typedef struct _REG_NOTIFY_INFORMATION
{
ULONG NextEntryOffset;
REG_ACTION Action;
ULONG KeyLength;
WCHAR Key[1];
} REG_NOTIFY_INFORMATION, *PREG_NOTIFY_INFORMATION;
typedef struct _KEY_PID_ARRAY
{
HANDLE PID;
UNICODE_STRING KeyName;
} KEY_PID_ARRAY, *PKEY_PID_ARRAY;
typedef struct _KEY_OPEN_SUBKEYS_INFORMATION
{
ULONG Count;
KEY_PID_ARRAY KeyArray[1];
} KEY_OPEN_SUBKEYS_INFORMATION, *PKEY_OPEN_SUBKEYS_INFORMATION;
// System calls
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateKey(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Reserved_ ULONG TitleIndex,
_In_opt_ PUNICODE_STRING Class,
_In_ ULONG CreateOptions,
_Out_opt_ PULONG Disposition
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateKey(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Reserved_ ULONG TitleIndex,
_In_opt_ PUNICODE_STRING Class,
_In_ ULONG CreateOptions,
_Out_opt_ PULONG Disposition
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateKeyTransacted(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Reserved_ ULONG TitleIndex,
_In_opt_ PUNICODE_STRING Class,
_In_ ULONG CreateOptions,
_In_ HANDLE TransactionHandle,
_Out_opt_ PULONG Disposition
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateKeyTransacted(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_Reserved_ ULONG TitleIndex,
_In_opt_ PUNICODE_STRING Class,
_In_ ULONG CreateOptions,
_In_ HANDLE TransactionHandle,
_Out_opt_ PULONG Disposition
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenKey(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenKey(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenKeyTransacted(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE TransactionHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenKeyTransacted(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ HANDLE TransactionHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenKeyEx(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG OpenOptions
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenKeyEx(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG OpenOptions
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenKeyTransactedEx(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG OpenOptions,
_In_ HANDLE TransactionHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenKeyTransactedEx(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ ULONG OpenOptions,
_In_ HANDLE TransactionHandle
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteKey(
_In_ HANDLE KeyHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteKey(
_In_ HANDLE KeyHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRenameKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING NewName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRenameKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING NewName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteValueKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING ValueName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteValueKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING ValueName
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryKey(
_In_ HANDLE KeyHandle,
_In_ KEY_INFORMATION_CLASS KeyInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryKey(
_In_ HANDLE KeyHandle,
_In_ KEY_INFORMATION_CLASS KeyInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationKey(
_In_ HANDLE KeyHandle,
_In_ KEY_SET_INFORMATION_CLASS KeySetInformationClass,
_In_reads_bytes_(KeySetInformationLength) PVOID KeySetInformation,
_In_ ULONG KeySetInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationKey(
_In_ HANDLE KeyHandle,
_In_ KEY_SET_INFORMATION_CLASS KeySetInformationClass,
_In_reads_bytes_(KeySetInformationLength) PVOID KeySetInformation,
_In_ ULONG KeySetInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryValueKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING ValueName,
_In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryValueKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING ValueName,
_In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetValueKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING ValueName,
_In_opt_ ULONG TitleIndex,
_In_ ULONG Type,
_In_reads_bytes_opt_(DataSize) PVOID Data,
_In_ ULONG DataSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetValueKey(
_In_ HANDLE KeyHandle,
_In_ PUNICODE_STRING ValueName,
_In_opt_ ULONG TitleIndex,
_In_ ULONG Type,
_In_reads_bytes_opt_(DataSize) PVOID Data,
_In_ ULONG DataSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryMultipleValueKey(
_In_ HANDLE KeyHandle,
_Inout_updates_(EntryCount) PKEY_VALUE_ENTRY ValueEntries,
_In_ ULONG EntryCount,
_Out_writes_bytes_(*BufferLength) PVOID ValueBuffer,
_Inout_ PULONG BufferLength,
_Out_opt_ PULONG RequiredBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryMultipleValueKey(
_In_ HANDLE KeyHandle,
_Inout_updates_(EntryCount) PKEY_VALUE_ENTRY ValueEntries,
_In_ ULONG EntryCount,
_Out_writes_bytes_(*BufferLength) PVOID ValueBuffer,
_Inout_ PULONG BufferLength,
_Out_opt_ PULONG RequiredBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnumerateKey(
_In_ HANDLE KeyHandle,
_In_ ULONG Index,
_In_ KEY_INFORMATION_CLASS KeyInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnumerateKey(
_In_ HANDLE KeyHandle,
_In_ ULONG Index,
_In_ KEY_INFORMATION_CLASS KeyInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnumerateValueKey(
_In_ HANDLE KeyHandle,
_In_ ULONG Index,
_In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnumerateValueKey(
_In_ HANDLE KeyHandle,
_In_ ULONG Index,
_In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
_Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
_In_ ULONG Length,
_Out_ PULONG ResultLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFlushKey(
_In_ HANDLE KeyHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFlushKey(
_In_ HANDLE KeyHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCompactKeys(
_In_ ULONG Count,
_In_reads_(Count) HANDLE KeyArray[]
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCompactKeys(
_In_ ULONG Count,
_In_reads_(Count) HANDLE KeyArray[]
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCompressKey(
_In_ HANDLE Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCompressKey(
_In_ HANDLE Key
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLoadKey(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ POBJECT_ATTRIBUTES SourceFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLoadKey(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ POBJECT_ATTRIBUTES SourceFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLoadKey2(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ POBJECT_ATTRIBUTES SourceFile,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLoadKey2(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ POBJECT_ATTRIBUTES SourceFile,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLoadKeyEx(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ POBJECT_ATTRIBUTES SourceFile,
_In_ ULONG Flags,
_In_opt_ HANDLE TrustClassKey,
_In_opt_ HANDLE Event,
_In_opt_ ACCESS_MASK DesiredAccess,
_Out_opt_ PHANDLE RootHandle,
_Out_opt_ PIO_STATUS_BLOCK IoStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLoadKeyEx(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ POBJECT_ATTRIBUTES SourceFile,
_In_ ULONG Flags,
_In_opt_ HANDLE TrustClassKey,
_In_opt_ HANDLE Event,
_In_opt_ ACCESS_MASK DesiredAccess,
_Out_opt_ PHANDLE RootHandle,
_Out_opt_ PIO_STATUS_BLOCK IoStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReplaceKey(
_In_ POBJECT_ATTRIBUTES NewFile,
_In_ HANDLE TargetHandle,
_In_ POBJECT_ATTRIBUTES OldFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReplaceKey(
_In_ POBJECT_ATTRIBUTES NewFile,
_In_ HANDLE TargetHandle,
_In_ POBJECT_ATTRIBUTES OldFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSaveKey(
_In_ HANDLE KeyHandle,
_In_ HANDLE FileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSaveKey(
_In_ HANDLE KeyHandle,
_In_ HANDLE FileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSaveKeyEx(
_In_ HANDLE KeyHandle,
_In_ HANDLE FileHandle,
_In_ ULONG Format
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSaveKeyEx(
_In_ HANDLE KeyHandle,
_In_ HANDLE FileHandle,
_In_ ULONG Format
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSaveMergedKeys(
_In_ HANDLE HighPrecedenceKeyHandle,
_In_ HANDLE LowPrecedenceKeyHandle,
_In_ HANDLE FileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSaveMergedKeys(
_In_ HANDLE HighPrecedenceKeyHandle,
_In_ HANDLE LowPrecedenceKeyHandle,
_In_ HANDLE FileHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRestoreKey(
_In_ HANDLE KeyHandle,
_In_ HANDLE FileHandle,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRestoreKey(
_In_ HANDLE KeyHandle,
_In_ HANDLE FileHandle,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnloadKey(
_In_ POBJECT_ATTRIBUTES TargetKey
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnloadKey(
_In_ POBJECT_ATTRIBUTES TargetKey
);
//
// NtUnloadKey2 Flags (from winnt.h)
//
//#define REG_FORCE_UNLOAD 1
//#define REG_UNLOAD_LEGAL_FLAGS (REG_FORCE_UNLOAD)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnloadKey2(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnloadKey2(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ ULONG Flags
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtUnloadKeyEx(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_opt_ HANDLE Event
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwUnloadKeyEx(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_opt_ HANDLE Event
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtNotifyChangeKey(
_In_ HANDLE KeyHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree,
_Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
_In_ ULONG BufferSize,
_In_ BOOLEAN Asynchronous
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwNotifyChangeKey(
_In_ HANDLE KeyHandle,
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree,
_Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
_In_ ULONG BufferSize,
_In_ BOOLEAN Asynchronous
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtNotifyChangeMultipleKeys(
_In_ HANDLE MasterKeyHandle,
_In_opt_ ULONG Count,
_In_reads_opt_(Count) OBJECT_ATTRIBUTES SubordinateObjects[],
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree,
_Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
_In_ ULONG BufferSize,
_In_ BOOLEAN Asynchronous
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwNotifyChangeMultipleKeys(
_In_ HANDLE MasterKeyHandle,
_In_opt_ ULONG Count,
_In_reads_opt_(Count) OBJECT_ATTRIBUTES SubordinateObjects[],
_In_opt_ HANDLE Event,
_In_opt_ PIO_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcContext,
_Out_ PIO_STATUS_BLOCK IoStatusBlock,
_In_ ULONG CompletionFilter,
_In_ BOOLEAN WatchTree,
_Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
_In_ ULONG BufferSize,
_In_ BOOLEAN Asynchronous
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryOpenSubKeys(
_In_ POBJECT_ATTRIBUTES TargetKey,
_Out_ PULONG HandleCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryOpenSubKeys(
_In_ POBJECT_ATTRIBUTES TargetKey,
_Out_ PULONG HandleCount
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryOpenSubKeysEx(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ ULONG BufferLength,
_Out_writes_bytes_(BufferLength) PVOID Buffer,
_Out_ PULONG RequiredSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryOpenSubKeysEx(
_In_ POBJECT_ATTRIBUTES TargetKey,
_In_ ULONG BufferLength,
_Out_writes_bytes_(BufferLength) PVOID Buffer,
_Out_ PULONG RequiredSize
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtInitializeRegistry(
_In_ USHORT BootCondition
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwInitializeRegistry(
_In_ USHORT BootCondition
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLockRegistryKey(
_In_ HANDLE KeyHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLockRegistryKey(
_In_ HANDLE KeyHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtLockProductActivationKeys(
_Inout_opt_ ULONG *pPrivateVer,
_Out_opt_ ULONG *pSafeMode
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwLockProductActivationKeys(
_Inout_opt_ ULONG *pPrivateVer,
_Out_opt_ ULONG *pSafeMode
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFreezeRegistry(
_In_ ULONG TimeOutInSeconds
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFreezeRegistry(
_In_ ULONG TimeOutInSeconds
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtThawRegistry(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwThawRegistry(
VOID
);
#endif
// #include <ntrtl.h>
#define RtlOffsetToPointer(Base, Offset) ((PCHAR)(((PCHAR)(Base)) + ((ULONG_PTR)(Offset))))
#define RtlPointerToOffset(Base, Pointer) ((ULONG)(((PCHAR)(Pointer)) - ((PCHAR)(Base))))
// Linked lists
FORCEINLINE VOID InitializeListHead(
_Out_ PLIST_ENTRY ListHead
)
{
ListHead->Flink = ListHead->Blink = ListHead;
}
_Check_return_ FORCEINLINE BOOLEAN IsListEmpty(
_In_ PLIST_ENTRY ListHead
)
{
return ListHead->Flink == ListHead;
}
FORCEINLINE BOOLEAN RemoveEntryList(
_In_ PLIST_ENTRY Entry
)
{
PLIST_ENTRY Blink;
PLIST_ENTRY Flink;
Flink = Entry->Flink;
Blink = Entry->Blink;
Blink->Flink = Flink;
Flink->Blink = Blink;
return Flink == Blink;
}
FORCEINLINE PLIST_ENTRY RemoveHeadList(
_Inout_ PLIST_ENTRY ListHead
)
{
PLIST_ENTRY Flink;
PLIST_ENTRY Entry;
Entry = ListHead->Flink;
Flink = Entry->Flink;
ListHead->Flink = Flink;
Flink->Blink = ListHead;
return Entry;
}
FORCEINLINE PLIST_ENTRY RemoveTailList(
_Inout_ PLIST_ENTRY ListHead
)
{
PLIST_ENTRY Blink;
PLIST_ENTRY Entry;
Entry = ListHead->Blink;
Blink = Entry->Blink;
ListHead->Blink = Blink;
Blink->Flink = ListHead;
return Entry;
}
FORCEINLINE VOID InsertTailList(
_Inout_ PLIST_ENTRY ListHead,
_Inout_ PLIST_ENTRY Entry
)
{
PLIST_ENTRY Blink;
Blink = ListHead->Blink;
Entry->Flink = ListHead;
Entry->Blink = Blink;
Blink->Flink = Entry;
ListHead->Blink = Entry;
}
FORCEINLINE VOID InsertHeadList(
_Inout_ PLIST_ENTRY ListHead,
_Inout_ PLIST_ENTRY Entry
)
{
PLIST_ENTRY Flink;
Flink = ListHead->Flink;
Entry->Flink = Flink;
Entry->Blink = ListHead;
Flink->Blink = Entry;
ListHead->Flink = Entry;
}
FORCEINLINE VOID AppendTailList(
_Inout_ PLIST_ENTRY ListHead,
_Inout_ PLIST_ENTRY ListToAppend
)
{
PLIST_ENTRY ListEnd = ListHead->Blink;
ListHead->Blink->Flink = ListToAppend;
ListHead->Blink = ListToAppend->Blink;
ListToAppend->Blink->Flink = ListHead;
ListToAppend->Blink = ListEnd;
}
FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList(
_Inout_ PSINGLE_LIST_ENTRY ListHead
)
{
PSINGLE_LIST_ENTRY FirstEntry;
FirstEntry = ListHead->Next;
if (FirstEntry)
ListHead->Next = FirstEntry->Next;
return FirstEntry;
}
FORCEINLINE VOID PushEntryList(
_Inout_ PSINGLE_LIST_ENTRY ListHead,
_Inout_ PSINGLE_LIST_ENTRY Entry
)
{
Entry->Next = ListHead->Next;
ListHead->Next = Entry;
}
// AVL and splay trees
typedef enum _TABLE_SEARCH_RESULT
{
TableEmptyTree,
TableFoundNode,
TableInsertAsLeft,
TableInsertAsRight
} TABLE_SEARCH_RESULT;
typedef enum _RTL_GENERIC_COMPARE_RESULTS
{
GenericLessThan,
GenericGreaterThan,
GenericEqual
} RTL_GENERIC_COMPARE_RESULTS;
typedef RTL_GENERIC_COMPARE_RESULTS (NTAPI *PRTL_AVL_COMPARE_ROUTINE)(
_In_ struct _RTL_AVL_TABLE *Table,
_In_ PVOID FirstStruct,
_In_ PVOID SecondStruct
);
typedef PVOID (NTAPI *PRTL_AVL_ALLOCATE_ROUTINE)(
_In_ struct _RTL_AVL_TABLE *Table,
_In_ CLONG ByteSize
);
typedef VOID (NTAPI *PRTL_AVL_FREE_ROUTINE)(
_In_ struct _RTL_AVL_TABLE *Table,
_In_ _Post_invalid_ PVOID Buffer
);
typedef NTSTATUS (NTAPI *PRTL_AVL_MATCH_FUNCTION)(
_In_ struct _RTL_AVL_TABLE *Table,
_In_ PVOID UserData,
_In_ PVOID MatchData
);
typedef struct _RTL_BALANCED_LINKS
{
struct _RTL_BALANCED_LINKS *Parent;
struct _RTL_BALANCED_LINKS *LeftChild;
struct _RTL_BALANCED_LINKS *RightChild;
CHAR Balance;
UCHAR Reserved[3];
} RTL_BALANCED_LINKS, *PRTL_BALANCED_LINKS;
typedef struct _RTL_AVL_TABLE
{
RTL_BALANCED_LINKS BalancedRoot;
PVOID OrderedPointer;
ULONG WhichOrderedElement;
ULONG NumberGenericTableElements;
ULONG DepthOfTree;
PRTL_BALANCED_LINKS RestartKey;
ULONG DeleteCount;
PRTL_AVL_COMPARE_ROUTINE CompareRoutine;
PRTL_AVL_ALLOCATE_ROUTINE AllocateRoutine;
PRTL_AVL_FREE_ROUTINE FreeRoutine;
PVOID TableContext;
} RTL_AVL_TABLE, *PRTL_AVL_TABLE;
NTSYSAPI
VOID
NTAPI
RtlInitializeGenericTableAvl(
_Out_ PRTL_AVL_TABLE Table,
_In_ PRTL_AVL_COMPARE_ROUTINE CompareRoutine,
_In_ PRTL_AVL_ALLOCATE_ROUTINE AllocateRoutine,
_In_ PRTL_AVL_FREE_ROUTINE FreeRoutine,
_In_opt_ PVOID TableContext
);
NTSYSAPI
PVOID
NTAPI
RtlInsertElementGenericTableAvl(
_In_ PRTL_AVL_TABLE Table,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ CLONG BufferSize,
_Out_opt_ PBOOLEAN NewElement
);
NTSYSAPI
PVOID
NTAPI
RtlInsertElementGenericTableFullAvl(
_In_ PRTL_AVL_TABLE Table,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ CLONG BufferSize,
_Out_opt_ PBOOLEAN NewElement,
_In_ PVOID NodeOrParent,
_In_ TABLE_SEARCH_RESULT SearchResult
);
NTSYSAPI
BOOLEAN
NTAPI
RtlDeleteElementGenericTableAvl(
_In_ PRTL_AVL_TABLE Table,
_In_ PVOID Buffer
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlLookupElementGenericTableAvl(
_In_ PRTL_AVL_TABLE Table,
_In_ PVOID Buffer
);
NTSYSAPI
PVOID
NTAPI
RtlLookupElementGenericTableFullAvl(
_In_ PRTL_AVL_TABLE Table,
_In_ PVOID Buffer,
_Out_ PVOID *NodeOrParent,
_Out_ TABLE_SEARCH_RESULT *SearchResult
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlEnumerateGenericTableAvl(
_In_ PRTL_AVL_TABLE Table,
_In_ BOOLEAN Restart
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlEnumerateGenericTableWithoutSplayingAvl(
_In_ PRTL_AVL_TABLE Table,
_Inout_ PVOID *RestartKey
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlLookupFirstMatchingElementGenericTableAvl(
_In_ PRTL_AVL_TABLE Table,
_In_ PVOID Buffer,
_Out_ PVOID *RestartKey
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlEnumerateGenericTableLikeADirectory(
_In_ PRTL_AVL_TABLE Table,
_In_opt_ PRTL_AVL_MATCH_FUNCTION MatchFunction,
_In_opt_ PVOID MatchData,
_In_ ULONG NextFlag,
_Inout_ PVOID *RestartKey,
_Inout_ PULONG DeleteCount,
_In_ PVOID Buffer
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlGetElementGenericTableAvl(
_In_ PRTL_AVL_TABLE Table,
_In_ ULONG I
);
NTSYSAPI
ULONG
NTAPI
RtlNumberGenericTableElementsAvl(
_In_ PRTL_AVL_TABLE Table
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlIsGenericTableEmptyAvl(
_In_ PRTL_AVL_TABLE Table
);
typedef struct _RTL_SPLAY_LINKS
{
struct _RTL_SPLAY_LINKS *Parent;
struct _RTL_SPLAY_LINKS *LeftChild;
struct _RTL_SPLAY_LINKS *RightChild;
} RTL_SPLAY_LINKS, *PRTL_SPLAY_LINKS;
#define RtlInitializeSplayLinks(Links) \
{ \
PRTL_SPLAY_LINKS _SplayLinks; \
_SplayLinks = (PRTL_SPLAY_LINKS)(Links); \
_SplayLinks->Parent = _SplayLinks; \
_SplayLinks->LeftChild = NULL; \
_SplayLinks->RightChild = NULL; \
}
#define RtlParent(Links) ((PRTL_SPLAY_LINKS)(Links)->Parent)
#define RtlLeftChild(Links) ((PRTL_SPLAY_LINKS)(Links)->LeftChild)
#define RtlRightChild(Links) ((PRTL_SPLAY_LINKS)(Links)->RightChild)
#define RtlIsRoot(Links) ((RtlParent(Links) == (PRTL_SPLAY_LINKS)(Links)))
#define RtlIsLeftChild(Links) ((RtlLeftChild(RtlParent(Links)) == (PRTL_SPLAY_LINKS)(Links)))
#define RtlIsRightChild(Links) ((RtlRightChild(RtlParent(Links)) == (PRTL_SPLAY_LINKS)(Links)))
#define RtlInsertAsLeftChild(ParentLinks, ChildLinks) \
{ \
PRTL_SPLAY_LINKS _SplayParent; \
PRTL_SPLAY_LINKS _SplayChild; \
_SplayParent = (PRTL_SPLAY_LINKS)(ParentLinks); \
_SplayChild = (PRTL_SPLAY_LINKS)(ChildLinks); \
_SplayParent->LeftChild = _SplayChild; \
_SplayChild->Parent = _SplayParent; \
}
#define RtlInsertAsRightChild(ParentLinks, ChildLinks) \
{ \
PRTL_SPLAY_LINKS _SplayParent; \
PRTL_SPLAY_LINKS _SplayChild; \
_SplayParent = (PRTL_SPLAY_LINKS)(ParentLinks); \
_SplayChild = (PRTL_SPLAY_LINKS)(ChildLinks); \
_SplayParent->RightChild = _SplayChild; \
_SplayChild->Parent = _SplayParent; \
}
NTSYSAPI
PRTL_SPLAY_LINKS
NTAPI
RtlSplay(
_Inout_ PRTL_SPLAY_LINKS Links
);
NTSYSAPI
PRTL_SPLAY_LINKS
NTAPI
RtlDelete(
_In_ PRTL_SPLAY_LINKS Links
);
NTSYSAPI
VOID
NTAPI
RtlDeleteNoSplay(
_In_ PRTL_SPLAY_LINKS Links,
_Inout_ PRTL_SPLAY_LINKS *Root
);
_Check_return_
NTSYSAPI
PRTL_SPLAY_LINKS
NTAPI
RtlSubtreeSuccessor(
_In_ PRTL_SPLAY_LINKS Links
);
_Check_return_
NTSYSAPI
PRTL_SPLAY_LINKS
NTAPI
RtlSubtreePredecessor(
_In_ PRTL_SPLAY_LINKS Links
);
_Check_return_
NTSYSAPI
PRTL_SPLAY_LINKS
NTAPI
RtlRealSuccessor(
_In_ PRTL_SPLAY_LINKS Links
);
_Check_return_
NTSYSAPI
PRTL_SPLAY_LINKS
NTAPI
RtlRealPredecessor(
_In_ PRTL_SPLAY_LINKS Links
);
struct _RTL_GENERIC_TABLE;
typedef RTL_GENERIC_COMPARE_RESULTS (NTAPI *PRTL_GENERIC_COMPARE_ROUTINE)(
_In_ struct _RTL_GENERIC_TABLE *Table,
_In_ PVOID FirstStruct,
_In_ PVOID SecondStruct
);
typedef PVOID (NTAPI *PRTL_GENERIC_ALLOCATE_ROUTINE)(
_In_ struct _RTL_GENERIC_TABLE *Table,
_In_ CLONG ByteSize
);
typedef VOID (NTAPI *PRTL_GENERIC_FREE_ROUTINE)(
_In_ struct _RTL_GENERIC_TABLE *Table,
_In_ _Post_invalid_ PVOID Buffer
);
typedef struct _RTL_GENERIC_TABLE
{
PRTL_SPLAY_LINKS TableRoot;
LIST_ENTRY InsertOrderList;
PLIST_ENTRY OrderedPointer;
ULONG WhichOrderedElement;
ULONG NumberGenericTableElements;
PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine;
PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine;
PRTL_GENERIC_FREE_ROUTINE FreeRoutine;
PVOID TableContext;
} RTL_GENERIC_TABLE, *PRTL_GENERIC_TABLE;
NTSYSAPI
VOID
NTAPI
RtlInitializeGenericTable(
_Out_ PRTL_GENERIC_TABLE Table,
_In_ PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine,
_In_ PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine,
_In_ PRTL_GENERIC_FREE_ROUTINE FreeRoutine,
_In_opt_ PVOID TableContext
);
NTSYSAPI
PVOID
NTAPI
RtlInsertElementGenericTable(
_In_ PRTL_GENERIC_TABLE Table,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ CLONG BufferSize,
_Out_opt_ PBOOLEAN NewElement
);
NTSYSAPI
PVOID
NTAPI
RtlInsertElementGenericTableFull(
_In_ PRTL_GENERIC_TABLE Table,
_In_reads_bytes_(BufferSize) PVOID Buffer,
_In_ CLONG BufferSize,
_Out_opt_ PBOOLEAN NewElement,
_In_ PVOID NodeOrParent,
_In_ TABLE_SEARCH_RESULT SearchResult
);
NTSYSAPI
BOOLEAN
NTAPI
RtlDeleteElementGenericTable(
_In_ PRTL_GENERIC_TABLE Table,
_In_ PVOID Buffer
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlLookupElementGenericTable(
_In_ PRTL_GENERIC_TABLE Table,
_In_ PVOID Buffer
);
NTSYSAPI
PVOID
NTAPI
RtlLookupElementGenericTableFull(
_In_ PRTL_GENERIC_TABLE Table,
_In_ PVOID Buffer,
_Out_ PVOID *NodeOrParent,
_Out_ TABLE_SEARCH_RESULT *SearchResult
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlEnumerateGenericTable(
_In_ PRTL_GENERIC_TABLE Table,
_In_ BOOLEAN Restart
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlEnumerateGenericTableWithoutSplaying(
_In_ PRTL_GENERIC_TABLE Table,
_Inout_ PVOID *RestartKey
);
_Check_return_
NTSYSAPI
PVOID
NTAPI
RtlGetElementGenericTable(
_In_ PRTL_GENERIC_TABLE Table,
_In_ ULONG I
);
NTSYSAPI
ULONG
NTAPI
RtlNumberGenericTableElements(
_In_ PRTL_GENERIC_TABLE Table
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlIsGenericTableEmpty(
_In_ PRTL_GENERIC_TABLE Table
);
// RB trees
typedef struct _RTL_RB_TREE
{
PRTL_BALANCED_NODE Root;
PRTL_BALANCED_NODE Min;
} RTL_RB_TREE, *PRTL_RB_TREE;
#if (NTDDI_VERSION >= NTDDI_WIN8)
// rev
NTSYSAPI
VOID
NTAPI
RtlRbInsertNodeEx(
_In_ PRTL_RB_TREE Tree,
_In_opt_ PRTL_BALANCED_NODE Parent,
_In_ BOOLEAN Right,
_Out_ PRTL_BALANCED_NODE Node
);
// rev
NTSYSAPI
VOID
NTAPI
RtlRbRemoveNode(
_In_ PRTL_RB_TREE Tree,
_In_ PRTL_BALANCED_NODE Node
);
#endif
// Hash tables
// begin_ntddk
#define RTL_HASH_ALLOCATED_HEADER 0x00000001
#define RTL_HASH_RESERVED_SIGNATURE 0
typedef struct _RTL_DYNAMIC_HASH_TABLE_ENTRY
{
LIST_ENTRY Linkage;
ULONG_PTR Signature;
} RTL_DYNAMIC_HASH_TABLE_ENTRY, *PRTL_DYNAMIC_HASH_TABLE_ENTRY;
#define HASH_ENTRY_KEY(x) ((x)->Signature)
typedef struct _RTL_DYNAMIC_HASH_TABLE_CONTEXT
{
PLIST_ENTRY ChainHead;
PLIST_ENTRY PrevLinkage;
ULONG_PTR Signature;
} RTL_DYNAMIC_HASH_TABLE_CONTEXT, *PRTL_DYNAMIC_HASH_TABLE_CONTEXT;
typedef struct _RTL_DYNAMIC_HASH_TABLE_ENUMERATOR
{
RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry;
PLIST_ENTRY ChainHead;
ULONG BucketIndex;
} RTL_DYNAMIC_HASH_TABLE_ENUMERATOR, *PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR;
typedef struct _RTL_DYNAMIC_HASH_TABLE
{
// Entries initialized at creation.
ULONG Flags;
ULONG Shift;
// Entries used in bucket computation.
ULONG TableSize;
ULONG Pivot;
ULONG DivisorMask;
// Counters.
ULONG NumEntries;
ULONG NonEmptyBuckets;
ULONG NumEnumerators;
// The directory. This field is for internal use only.
PVOID Directory;
} RTL_DYNAMIC_HASH_TABLE, *PRTL_DYNAMIC_HASH_TABLE;
#if (NTDDI_VERSION >= NTDDI_WIN7)
FORCEINLINE
VOID
RtlInitHashTableContext(
_Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
)
{
Context->ChainHead = NULL;
Context->PrevLinkage = NULL;
}
FORCEINLINE
VOID
RtlInitHashTableContextFromEnumerator(
_Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context,
_In_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
)
{
Context->ChainHead = Enumerator->ChainHead;
Context->PrevLinkage = Enumerator->HashEntry.Linkage.Blink;
}
FORCEINLINE
VOID
RtlReleaseHashTableContext(
_Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
)
{
UNREFERENCED_PARAMETER(Context);
return;
}
FORCEINLINE
ULONG
RtlTotalBucketsHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
)
{
return HashTable->TableSize;
}
FORCEINLINE
ULONG
RtlNonEmptyBucketsHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
)
{
return HashTable->NonEmptyBuckets;
}
FORCEINLINE
ULONG
RtlEmptyBucketsHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
)
{
return HashTable->TableSize - HashTable->NonEmptyBuckets;
}
FORCEINLINE
ULONG
RtlTotalEntriesHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
)
{
return HashTable->NumEntries;
}
FORCEINLINE
ULONG
RtlActiveEnumeratorsHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
)
{
return HashTable->NumEnumerators;
}
_Must_inspect_result_
NTSYSAPI
BOOLEAN
NTAPI
RtlCreateHashTable(
_Inout_ _When_(*HashTable == NULL, __drv_allocatesMem(Mem)) PRTL_DYNAMIC_HASH_TABLE *HashTable,
_In_ ULONG Shift,
_In_ _Reserved_ ULONG Flags
);
NTSYSAPI
VOID
NTAPI
RtlDeleteHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
);
NTSYSAPI
BOOLEAN
NTAPI
RtlInsertEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_In_ PRTL_DYNAMIC_HASH_TABLE_ENTRY Entry,
_In_ ULONG_PTR Signature,
_Inout_opt_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
);
NTSYSAPI
BOOLEAN
NTAPI
RtlRemoveEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_In_ PRTL_DYNAMIC_HASH_TABLE_ENTRY Entry,
_Inout_opt_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
);
_Must_inspect_result_
NTSYSAPI
PRTL_DYNAMIC_HASH_TABLE_ENTRY
NTAPI
RtlLookupEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_In_ ULONG_PTR Signature,
_Out_opt_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
);
_Must_inspect_result_
NTSYSAPI
PRTL_DYNAMIC_HASH_TABLE_ENTRY
NTAPI
RtlGetNextEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_In_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
);
NTSYSAPI
BOOLEAN
NTAPI
RtlInitEnumerationHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Out_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
_Must_inspect_result_
NTSYSAPI
PRTL_DYNAMIC_HASH_TABLE_ENTRY
NTAPI
RtlEnumerateEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
NTSYSAPI
VOID
NTAPI
RtlEndEnumerationHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
NTSYSAPI
BOOLEAN
NTAPI
RtlInitWeakEnumerationHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Out_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
_Must_inspect_result_
NTSYSAPI
PRTL_DYNAMIC_HASH_TABLE_ENTRY
NTAPI
RtlWeaklyEnumerateEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
NTSYSAPI
VOID
NTAPI
RtlEndWeakEnumerationHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
NTSYSAPI
BOOLEAN
NTAPI
RtlExpandHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
);
NTSYSAPI
BOOLEAN
NTAPI
RtlContractHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSAPI
BOOLEAN
NTAPI
RtlInitStrongEnumerationHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Out_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
_Must_inspect_result_
NTSYSAPI
PRTL_DYNAMIC_HASH_TABLE_ENTRY
NTAPI
RtlStronglyEnumerateEntryHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
NTSYSAPI
VOID
NTAPI
RtlEndStrongEnumerationHashTable(
_In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
_Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
);
#endif
// end_ntddk
// Critical sections
NTSYSAPI
NTSTATUS
NTAPI
RtlInitializeCriticalSection(
_Out_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
NTSTATUS
NTAPI
RtlInitializeCriticalSectionAndSpinCount(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection,
_In_ ULONG SpinCount
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteCriticalSection(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
NTSTATUS
NTAPI
RtlEnterCriticalSection(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
NTSTATUS
NTAPI
RtlLeaveCriticalSection(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
LOGICAL
NTAPI
RtlTryEnterCriticalSection(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
LOGICAL
NTAPI
RtlIsCriticalSectionLocked(
_In_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
LOGICAL
NTAPI
RtlIsCriticalSectionLockedByThread(
_In_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
ULONG
NTAPI
RtlGetCriticalSectionRecursionCount(
_In_ PRTL_CRITICAL_SECTION CriticalSection
);
NTSYSAPI
ULONG
NTAPI
RtlSetCriticalSectionSpinCount(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection,
_In_ ULONG SpinCount
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
HANDLE
NTAPI
RtlQueryCriticalSectionOwner(
_In_ HANDLE EventHandle
);
#endif
NTSYSAPI
VOID
NTAPI
RtlCheckForOrphanedCriticalSections(
_In_ HANDLE ThreadHandle
);
// Resources
typedef struct _RTL_RESOURCE
{
RTL_CRITICAL_SECTION CriticalSection;
HANDLE SharedSemaphore;
volatile ULONG NumberOfWaitingShared;
HANDLE ExclusiveSemaphore;
volatile ULONG NumberOfWaitingExclusive;
volatile LONG NumberOfActive; // negative: exclusive acquire; zero: not acquired; positive: shared acquire(s)
HANDLE ExclusiveOwnerThread;
ULONG Flags; // RTL_RESOURCE_FLAG_*
PRTL_RESOURCE_DEBUG DebugInfo;
} RTL_RESOURCE, *PRTL_RESOURCE;
#define RTL_RESOURCE_FLAG_LONG_TERM ((ULONG)0x00000001)
NTSYSAPI
VOID
NTAPI
RtlInitializeResource(
_Out_ PRTL_RESOURCE Resource
);
NTSYSAPI
VOID
NTAPI
RtlDeleteResource(
_Inout_ PRTL_RESOURCE Resource
);
NTSYSAPI
BOOLEAN
NTAPI
RtlAcquireResourceShared(
_Inout_ PRTL_RESOURCE Resource,
_In_ BOOLEAN Wait
);
NTSYSAPI
BOOLEAN
NTAPI
RtlAcquireResourceExclusive(
_Inout_ PRTL_RESOURCE Resource,
_In_ BOOLEAN Wait
);
NTSYSAPI
VOID
NTAPI
RtlReleaseResource(
_Inout_ PRTL_RESOURCE Resource
);
NTSYSAPI
VOID
NTAPI
RtlConvertSharedToExclusive(
_Inout_ PRTL_RESOURCE Resource
);
NTSYSAPI
VOID
NTAPI
RtlConvertExclusiveToShared(
_Inout_ PRTL_RESOURCE Resource
);
// Slim reader-writer locks, condition variables, and barriers
#if (NTDDI_VERSION >= NTDDI_VISTA)
// winbase:InitializeSRWLock
NTSYSAPI
VOID
NTAPI
RtlInitializeSRWLock(
_Out_ PRTL_SRWLOCK SRWLock
);
// winbase:AcquireSRWLockExclusive
NTSYSAPI
VOID
NTAPI
RtlAcquireSRWLockExclusive(
_Inout_ PRTL_SRWLOCK SRWLock
);
// winbase:AcquireSRWLockShared
NTSYSAPI
VOID
NTAPI
RtlAcquireSRWLockShared(
_Inout_ PRTL_SRWLOCK SRWLock
);
// winbase:ReleaseSRWLockExclusive
NTSYSAPI
VOID
NTAPI
RtlReleaseSRWLockExclusive(
_Inout_ PRTL_SRWLOCK SRWLock
);
// winbase:ReleaseSRWLockShared
NTSYSAPI
VOID
NTAPI
RtlReleaseSRWLockShared(
_Inout_ PRTL_SRWLOCK SRWLock
);
// winbase:TryAcquireSRWLockExclusive
NTSYSAPI
BOOLEAN
NTAPI
RtlTryAcquireSRWLockExclusive(
_Inout_ PRTL_SRWLOCK SRWLock
);
// winbase:TryAcquireSRWLockShared
NTSYSAPI
BOOLEAN
NTAPI
RtlTryAcquireSRWLockShared(
_Inout_ PRTL_SRWLOCK SRWLock
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
VOID
NTAPI
RtlAcquireReleaseSRWLockExclusive(
_Inout_ PRTL_SRWLOCK SRWLock
);
#endif
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// winbase:InitializeConditionVariable
NTSYSAPI
VOID
NTAPI
RtlInitializeConditionVariable(
_Out_ PRTL_CONDITION_VARIABLE ConditionVariable
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSleepConditionVariableCS(
_Inout_ PRTL_CONDITION_VARIABLE ConditionVariable,
_Inout_ PRTL_CRITICAL_SECTION CriticalSection,
_In_opt_ PLARGE_INTEGER Timeout
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSleepConditionVariableSRW(
_Inout_ PRTL_CONDITION_VARIABLE ConditionVariable,
_Inout_ PRTL_SRWLOCK SRWLock,
_In_opt_ PLARGE_INTEGER Timeout,
_In_ ULONG Flags
);
// winbase:WakeConditionVariable
NTSYSAPI
VOID
NTAPI
RtlWakeConditionVariable(
_Inout_ PRTL_CONDITION_VARIABLE ConditionVariable
);
// winbase:WakeAllConditionVariable
NTSYSAPI
VOID
NTAPI
RtlWakeAllConditionVariable(
_Inout_ PRTL_CONDITION_VARIABLE ConditionVariable
);
#endif
// begin_rev
#define RTL_BARRIER_FLAGS_SPIN_ONLY 0x00000001 // never block on event - always spin
#define RTL_BARRIER_FLAGS_BLOCK_ONLY 0x00000002 // always block on event - never spin
#define RTL_BARRIER_FLAGS_NO_DELETE 0x00000004 // use if barrier will never be deleted
// end_rev
// begin_private
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlInitBarrier(
_Out_ PRTL_BARRIER Barrier,
_In_ ULONG TotalThreads,
_In_ ULONG SpinCount
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteBarrier(
_In_ PRTL_BARRIER Barrier
);
NTSYSAPI
BOOLEAN
NTAPI
RtlBarrier(
_Inout_ PRTL_BARRIER Barrier,
_In_ ULONG Flags
);
NTSYSAPI
BOOLEAN
NTAPI
RtlBarrierForDelete(
_Inout_ PRTL_BARRIER Barrier,
_In_ ULONG Flags
);
#endif
// end_private
// Wait on address
// begin_rev
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSAPI
NTSTATUS
NTAPI
RtlWaitOnAddress(
_In_ volatile VOID *Address,
_In_ PVOID CompareAddress,
_In_ SIZE_T AddressSize,
_In_opt_ PLARGE_INTEGER Timeout
);
NTSYSAPI
VOID
NTAPI
RtlWakeAddressAll(
_In_ PVOID Address
);
NTSYSAPI
VOID
NTAPI
RtlWakeAddressSingle(
_In_ PVOID Address
);
#endif
// end_rev
// Strings
NTSYSAPI
VOID
NTAPI
RtlInitString(
_Out_ PSTRING DestinationString,
_In_opt_ PSTR SourceString
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSAPI
NTSTATUS
NTAPI
RtlInitStringEx(
_Out_ PSTRING DestinationString,
_In_opt_z_ PCSZ SourceString
);
#endif
NTSYSAPI
VOID
NTAPI
RtlInitAnsiString(
_Out_ PANSI_STRING DestinationString,
_In_opt_ PSTR SourceString
);
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSAPI
NTSTATUS
NTAPI
RtlInitAnsiStringEx(
_Out_ PANSI_STRING DestinationString,
_In_opt_z_ PCSZ SourceString
);
#endif
NTSYSAPI
VOID
NTAPI
RtlFreeAnsiString(
_In_ PANSI_STRING AnsiString
);
NTSYSAPI
VOID
NTAPI
RtlFreeOemString(
_In_ POEM_STRING OemString
);
NTSYSAPI
VOID
NTAPI
RtlCopyString(
_In_ PSTRING DestinationString,
_In_opt_ PSTRING SourceString
);
NTSYSAPI
CHAR
NTAPI
RtlUpperChar(
_In_ CHAR Character
);
_Must_inspect_result_
NTSYSAPI
LONG
NTAPI
RtlCompareString(
_In_ PSTRING String1,
_In_ PSTRING String2,
_In_ BOOLEAN CaseInSensitive
);
_Must_inspect_result_
NTSYSAPI
BOOLEAN
NTAPI
RtlEqualString(
_In_ PSTRING String1,
_In_ PSTRING String2,
_In_ BOOLEAN CaseInSensitive
);
_Must_inspect_result_
NTSYSAPI
BOOLEAN
NTAPI
RtlPrefixString(
_In_ PSTRING String1,
_In_ PSTRING String2,
_In_ BOOLEAN CaseInSensitive
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAppendStringToString(
_In_ PSTRING Destination,
_In_ PSTRING Source
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAppendAsciizToString(
_In_ PSTRING Destination,
_In_opt_ PSTR Source
);
NTSYSAPI
VOID
NTAPI
RtlUpperString(
_In_ PSTRING DestinationString,
_In_ PSTRING SourceString
);
FORCEINLINE
BOOLEAN
RtlIsNullOrEmptyUnicodeString(
_In_opt_ PUNICODE_STRING String
)
{
return !String || String->Length == 0;
}
FORCEINLINE
VOID
NTAPI
RtlInitEmptyUnicodeString(
_Out_ PUNICODE_STRING DestinationString,
_In_opt_ PWCHAR Buffer,
_In_ USHORT MaximumLength
)
{
DestinationString->Buffer = Buffer;
DestinationString->MaximumLength = MaximumLength;
DestinationString->Length = 0;
}
NTSYSAPI
VOID
NTAPI
RtlInitUnicodeString(
_Out_ PUNICODE_STRING DestinationString,
_In_opt_ PWSTR SourceString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlInitUnicodeStringEx(
_Out_ PUNICODE_STRING DestinationString,
_In_opt_ PWSTR SourceString
);
NTSYSAPI
BOOLEAN
NTAPI
RtlCreateUnicodeString(
_Out_ PUNICODE_STRING DestinationString,
_In_ PWSTR SourceString
);
NTSYSAPI
BOOLEAN
NTAPI
RtlCreateUnicodeStringFromAsciiz(
_Out_ PUNICODE_STRING DestinationString,
_In_ PSTR SourceString
);
NTSYSAPI
VOID
NTAPI
RtlFreeUnicodeString(
_In_ PUNICODE_STRING UnicodeString
);
#define RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE (0x00000001)
#define RTL_DUPLICATE_UNICODE_STRING_ALLOCATE_NULL_STRING (0x00000002)
NTSYSAPI
NTSTATUS
NTAPI
RtlDuplicateUnicodeString(
_In_ ULONG Flags,
_In_ PUNICODE_STRING StringIn,
_Out_ PUNICODE_STRING StringOut
);
NTSYSAPI
VOID
NTAPI
RtlCopyUnicodeString(
_In_ PUNICODE_STRING DestinationString,
_In_ PUNICODE_STRING SourceString
);
NTSYSAPI
WCHAR
NTAPI
RtlUpcaseUnicodeChar(
_In_ WCHAR SourceCharacter
);
NTSYSAPI
WCHAR
NTAPI
RtlDowncaseUnicodeChar(
_In_ WCHAR SourceCharacter
);
_Must_inspect_result_
NTSYSAPI
LONG
NTAPI
RtlCompareUnicodeString(
_In_ PUNICODE_STRING String1,
_In_ PUNICODE_STRING String2,
_In_ BOOLEAN CaseInSensitive
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
_Must_inspect_result_
NTSYSAPI
LONG
NTAPI
RtlCompareUnicodeStrings(
_In_reads_(String1Length) PWCH String1,
_In_ SIZE_T String1Length,
_In_reads_(String2Length) PWCH String2,
_In_ SIZE_T String2Length,
_In_ BOOLEAN CaseInSensitive
);
#endif
_Must_inspect_result_
NTSYSAPI
BOOLEAN
NTAPI
RtlEqualUnicodeString(
_In_ PUNICODE_STRING String1,
_In_ PUNICODE_STRING String2,
_In_ BOOLEAN CaseInSensitive
);
#define HASH_STRING_ALGORITHM_DEFAULT 0
#define HASH_STRING_ALGORITHM_X65599 1
#define HASH_STRING_ALGORITHM_INVALID 0xffffffff
NTSYSAPI
NTSTATUS
NTAPI
RtlHashUnicodeString(
_In_ PUNICODE_STRING String,
_In_ BOOLEAN CaseInSensitive,
_In_ ULONG HashAlgorithm,
_Out_ PULONG HashValue
);
NTSYSAPI
NTSTATUS
NTAPI
RtlValidateUnicodeString(
_In_ ULONG Flags,
_In_ PUNICODE_STRING String
);
_Must_inspect_result_
NTSYSAPI
BOOLEAN
NTAPI
RtlPrefixUnicodeString(
_In_ PUNICODE_STRING String1,
_In_ PUNICODE_STRING String2,
_In_ BOOLEAN CaseInSensitive
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
_Must_inspect_result_
NTSYSAPI
BOOLEAN
NTAPI
RtlSuffixUnicodeString(
_In_ PUNICODE_STRING String1,
_In_ PUNICODE_STRING String2,
_In_ BOOLEAN CaseInSensitive
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10)
_Must_inspect_result_
NTSYSAPI
PWCHAR
NTAPI
RtlFindUnicodeSubstring(
_In_ PUNICODE_STRING FullString,
_In_ PUNICODE_STRING SearchString,
_In_ BOOLEAN CaseInSensitive
);
#endif
#define RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END 0x00000001
#define RTL_FIND_CHAR_IN_UNICODE_STRING_COMPLEMENT_CHAR_SET 0x00000002
#define RTL_FIND_CHAR_IN_UNICODE_STRING_CASE_INSENSITIVE 0x00000004
NTSYSAPI
NTSTATUS
NTAPI
RtlFindCharInUnicodeString(
_In_ ULONG Flags,
_In_ PUNICODE_STRING StringToSearch,
_In_ PUNICODE_STRING CharSet,
_Out_ PUSHORT NonInclusivePrefixLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAppendUnicodeStringToString(
_In_ PUNICODE_STRING Destination,
_In_ PUNICODE_STRING Source
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAppendUnicodeToString(
_In_ PUNICODE_STRING Destination,
_In_opt_ PWSTR Source
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeString(
_Inout_ PUNICODE_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDowncaseUnicodeString(
_Inout_ PUNICODE_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
VOID
NTAPI
RtlEraseUnicodeString(
_Inout_ PUNICODE_STRING String
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAnsiStringToUnicodeString(
_Inout_ PUNICODE_STRING DestinationString,
_In_ PANSI_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeStringToAnsiString(
_Inout_ PANSI_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
WCHAR
NTAPI
RtlAnsiCharToUnicodeChar(
_Inout_ PUCHAR *SourceCharacter
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeStringToAnsiString(
_Inout_ PANSI_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlOemStringToUnicodeString(
_Inout_ PUNICODE_STRING DestinationString,
_In_ POEM_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeStringToOemString(
_Inout_ POEM_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeStringToOemString(
_Inout_ POEM_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeStringToCountedOemString(
_Inout_ POEM_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeStringToCountedOemString(
_Inout_ POEM_STRING DestinationString,
_In_ PUNICODE_STRING SourceString,
_In_ BOOLEAN AllocateDestinationString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlMultiByteToUnicodeN(
_Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG MaxBytesInUnicodeString,
_Out_opt_ PULONG BytesInUnicodeString,
_In_reads_bytes_(BytesInMultiByteString) PSTR MultiByteString,
_In_ ULONG BytesInMultiByteString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlMultiByteToUnicodeSize(
_Out_ PULONG BytesInUnicodeString,
_In_reads_bytes_(BytesInMultiByteString) PSTR MultiByteString,
_In_ ULONG BytesInMultiByteString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeToMultiByteN(
_Out_writes_bytes_to_(MaxBytesInMultiByteString, *BytesInMultiByteString) PCHAR MultiByteString,
_In_ ULONG MaxBytesInMultiByteString,
_Out_opt_ PULONG BytesInMultiByteString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeToMultiByteSize(
_Out_ PULONG BytesInMultiByteString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeToMultiByteN(
_Out_writes_bytes_to_(MaxBytesInMultiByteString, *BytesInMultiByteString) PCHAR MultiByteString,
_In_ ULONG MaxBytesInMultiByteString,
_Out_opt_ PULONG BytesInMultiByteString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlOemToUnicodeN(
_Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWSTR UnicodeString,
_In_ ULONG MaxBytesInUnicodeString,
_Out_opt_ PULONG BytesInUnicodeString,
_In_reads_bytes_(BytesInOemString) PCH OemString,
_In_ ULONG BytesInOemString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeToOemN(
_Out_writes_bytes_to_(MaxBytesInOemString, *BytesInOemString) PCHAR OemString,
_In_ ULONG MaxBytesInOemString,
_Out_opt_ PULONG BytesInOemString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeToOemN(
_Out_writes_bytes_to_(MaxBytesInOemString, *BytesInOemString) PCHAR OemString,
_In_ ULONG MaxBytesInOemString,
_Out_opt_ PULONG BytesInOemString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlConsoleMultiByteToUnicodeN(
_Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG MaxBytesInUnicodeString,
_Out_opt_ PULONG BytesInUnicodeString,
_In_reads_bytes_(BytesInMultiByteString) PCH MultiByteString,
_In_ ULONG BytesInMultiByteString,
_Out_ PULONG pdwSpecialChar
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSAPI
NTSTATUS
NTAPI
RtlUTF8ToUnicodeN(
_Out_writes_bytes_to_(UnicodeStringMaxByteCount, *UnicodeStringActualByteCount) PWSTR UnicodeStringDestination,
_In_ ULONG UnicodeStringMaxByteCount,
_Out_ PULONG UnicodeStringActualByteCount,
_In_reads_bytes_(UTF8StringByteCount) PCH UTF8StringSource,
_In_ ULONG UTF8StringByteCount
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeToUTF8N(
_Out_writes_bytes_to_(UTF8StringMaxByteCount, *UTF8StringActualByteCount) PCHAR UTF8StringDestination,
_In_ ULONG UTF8StringMaxByteCount,
_Out_ PULONG UTF8StringActualByteCount,
_In_reads_bytes_(UnicodeStringByteCount) PWCH UnicodeStringSource,
_In_ ULONG UnicodeStringByteCount
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlCustomCPToUnicodeN(
_In_ PCPTABLEINFO CustomCP,
_Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG MaxBytesInUnicodeString,
_Out_opt_ PULONG BytesInUnicodeString,
_In_reads_bytes_(BytesInCustomCPString) PCH CustomCPString,
_In_ ULONG BytesInCustomCPString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeToCustomCPN(
_In_ PCPTABLEINFO CustomCP,
_Out_writes_bytes_to_(MaxBytesInCustomCPString, *BytesInCustomCPString) PCH CustomCPString,
_In_ ULONG MaxBytesInCustomCPString,
_Out_opt_ PULONG BytesInCustomCPString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpcaseUnicodeToCustomCPN(
_In_ PCPTABLEINFO CustomCP,
_Out_writes_bytes_to_(MaxBytesInCustomCPString, *BytesInCustomCPString) PCH CustomCPString,
_In_ ULONG MaxBytesInCustomCPString,
_Out_opt_ PULONG BytesInCustomCPString,
_In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
_In_ ULONG BytesInUnicodeString
);
NTSYSAPI
VOID
NTAPI
RtlInitCodePageTable(
_In_ PUSHORT TableBase,
_Out_ PCPTABLEINFO CodePageTable
);
NTSYSAPI
VOID
NTAPI
RtlInitNlsTables(
_In_ PUSHORT AnsiNlsBase,
_In_ PUSHORT OemNlsBase,
_In_ PUSHORT LanguageNlsBase,
_Out_ PNLSTABLEINFO TableInfo // PCPTABLEINFO?
);
NTSYSAPI
VOID
NTAPI
RtlResetRtlTranslations(
_In_ PNLSTABLEINFO TableInfo
);
NTSYSAPI
BOOLEAN
NTAPI
RtlIsTextUnicode(
_In_ PVOID Buffer,
_In_ ULONG Size,
_Inout_opt_ PULONG Result
);
typedef enum _RTL_NORM_FORM
{
NormOther = 0x0,
NormC = 0x1,
NormD = 0x2,
NormKC = 0x5,
NormKD = 0x6,
NormIdna = 0xd,
DisallowUnassigned = 0x100,
NormCDisallowUnassigned = 0x101,
NormDDisallowUnassigned = 0x102,
NormKCDisallowUnassigned = 0x105,
NormKDDisallowUnassigned = 0x106,
NormIdnaDisallowUnassigned = 0x10d
} RTL_NORM_FORM;
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlNormalizeString(
_In_ ULONG NormForm, // RTL_NORM_FORM
_In_ PCWSTR SourceString,
_In_ LONG SourceStringLength,
_Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
_Inout_ PLONG DestinationStringLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlIsNormalizedString(
_In_ ULONG NormForm, // RTL_NORM_FORM
_In_ PCWSTR SourceString,
_In_ LONG SourceStringLength,
_Out_ PBOOLEAN Normalized
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// ntifs:FsRtlIsNameInExpression
NTSYSAPI
BOOLEAN
NTAPI
RtlIsNameInExpression(
_In_ PUNICODE_STRING Expression,
_In_ PUNICODE_STRING Name,
_In_ BOOLEAN IgnoreCase,
_In_opt_ PWCH UpcaseTable
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS4)
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsNameInUnUpcasedExpression(
_In_ PUNICODE_STRING Expression,
_In_ PUNICODE_STRING Name,
_In_ BOOLEAN IgnoreCase,
_In_opt_ PWCH UpcaseTable
);
#endif
NTSYSAPI
BOOLEAN
NTAPI
RtlEqualDomainName(
_In_ PUNICODE_STRING String1,
_In_ PUNICODE_STRING String2
);
NTSYSAPI
BOOLEAN
NTAPI
RtlEqualComputerName(
_In_ PUNICODE_STRING String1,
_In_ PUNICODE_STRING String2
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDnsHostNameToComputerName(
_Out_ PUNICODE_STRING ComputerNameString,
_In_ PUNICODE_STRING DnsHostNameString,
_In_ BOOLEAN AllocateComputerNameString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlStringFromGUID(
_In_ PGUID Guid,
_Out_ PUNICODE_STRING GuidString
);
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlStringFromGUIDEx(
_In_ PGUID Guid,
_Inout_ PUNICODE_STRING GuidString,
_In_ BOOLEAN AllocateGuidString
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlGUIDFromString(
_In_ PUNICODE_STRING GuidString,
_Out_ PGUID Guid
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
LONG
NTAPI
RtlCompareAltitudes(
_In_ PUNICODE_STRING Altitude1,
_In_ PUNICODE_STRING Altitude2
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIdnToAscii(
_In_ ULONG Flags,
_In_ PWSTR SourceString,
_In_ LONG SourceStringLength,
_Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
_Inout_ PLONG DestinationStringLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIdnToUnicode(
_In_ ULONG Flags,
_In_ PWSTR SourceString,
_In_ LONG SourceStringLength,
_Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
_Inout_ PLONG DestinationStringLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIdnToNameprepUnicode(
_In_ ULONG Flags,
_In_ PWSTR SourceString,
_In_ LONG SourceStringLength,
_Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
_Inout_ PLONG DestinationStringLength
);
#endif
// Prefix
typedef struct _PREFIX_TABLE_ENTRY
{
CSHORT NodeTypeCode;
CSHORT NameLength;
struct _PREFIX_TABLE_ENTRY *NextPrefixTree;
RTL_SPLAY_LINKS Links;
PSTRING Prefix;
} PREFIX_TABLE_ENTRY, *PPREFIX_TABLE_ENTRY;
typedef struct _PREFIX_TABLE
{
CSHORT NodeTypeCode;
CSHORT NameLength;
PPREFIX_TABLE_ENTRY NextPrefixTree;
} PREFIX_TABLE, *PPREFIX_TABLE;
NTSYSAPI
VOID
NTAPI
PfxInitialize(
_Out_ PPREFIX_TABLE PrefixTable
);
NTSYSAPI
BOOLEAN
NTAPI
PfxInsertPrefix(
_In_ PPREFIX_TABLE PrefixTable,
_In_ PSTRING Prefix,
_Out_ PPREFIX_TABLE_ENTRY PrefixTableEntry
);
NTSYSAPI
VOID
NTAPI
PfxRemovePrefix(
_In_ PPREFIX_TABLE PrefixTable,
_In_ PPREFIX_TABLE_ENTRY PrefixTableEntry
);
NTSYSAPI
PPREFIX_TABLE_ENTRY
NTAPI
PfxFindPrefix(
_In_ PPREFIX_TABLE PrefixTable,
_In_ PSTRING FullName
);
typedef struct _UNICODE_PREFIX_TABLE_ENTRY
{
CSHORT NodeTypeCode;
CSHORT NameLength;
struct _UNICODE_PREFIX_TABLE_ENTRY *NextPrefixTree;
struct _UNICODE_PREFIX_TABLE_ENTRY *CaseMatch;
RTL_SPLAY_LINKS Links;
PUNICODE_STRING Prefix;
} UNICODE_PREFIX_TABLE_ENTRY, *PUNICODE_PREFIX_TABLE_ENTRY;
typedef struct _UNICODE_PREFIX_TABLE
{
CSHORT NodeTypeCode;
CSHORT NameLength;
PUNICODE_PREFIX_TABLE_ENTRY NextPrefixTree;
PUNICODE_PREFIX_TABLE_ENTRY LastNextEntry;
} UNICODE_PREFIX_TABLE, *PUNICODE_PREFIX_TABLE;
NTSYSAPI
VOID
NTAPI
RtlInitializeUnicodePrefix(
_Out_ PUNICODE_PREFIX_TABLE PrefixTable
);
NTSYSAPI
BOOLEAN
NTAPI
RtlInsertUnicodePrefix(
_In_ PUNICODE_PREFIX_TABLE PrefixTable,
_In_ PUNICODE_STRING Prefix,
_Out_ PUNICODE_PREFIX_TABLE_ENTRY PrefixTableEntry
);
NTSYSAPI
VOID
NTAPI
RtlRemoveUnicodePrefix(
_In_ PUNICODE_PREFIX_TABLE PrefixTable,
_In_ PUNICODE_PREFIX_TABLE_ENTRY PrefixTableEntry
);
NTSYSAPI
PUNICODE_PREFIX_TABLE_ENTRY
NTAPI
RtlFindUnicodePrefix(
_In_ PUNICODE_PREFIX_TABLE PrefixTable,
_In_ PUNICODE_STRING FullName,
_In_ ULONG CaseInsensitiveIndex
);
NTSYSAPI
PUNICODE_PREFIX_TABLE_ENTRY
NTAPI
RtlNextUnicodePrefix(
_In_ PUNICODE_PREFIX_TABLE PrefixTable,
_In_ BOOLEAN Restart
);
// Compression
typedef struct _COMPRESSED_DATA_INFO
{
USHORT CompressionFormatAndEngine; // COMPRESSION_FORMAT_* and COMPRESSION_ENGINE_*
UCHAR CompressionUnitShift;
UCHAR ChunkShift;
UCHAR ClusterShift;
UCHAR Reserved;
USHORT NumberOfChunks;
ULONG CompressedChunkSizes[1];
} COMPRESSED_DATA_INFO, *PCOMPRESSED_DATA_INFO;
NTSYSAPI
NTSTATUS
NTAPI
RtlGetCompressionWorkSpaceSize(
_In_ USHORT CompressionFormatAndEngine,
_Out_ PULONG CompressBufferWorkSpaceSize,
_Out_ PULONG CompressFragmentWorkSpaceSize
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCompressBuffer(
_In_ USHORT CompressionFormatAndEngine,
_In_reads_bytes_(UncompressedBufferSize) PUCHAR UncompressedBuffer,
_In_ ULONG UncompressedBufferSize,
_Out_writes_bytes_to_(CompressedBufferSize, *FinalCompressedSize) PUCHAR CompressedBuffer,
_In_ ULONG CompressedBufferSize,
_In_ ULONG UncompressedChunkSize,
_Out_ PULONG FinalCompressedSize,
_In_ PVOID WorkSpace
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDecompressBuffer(
_In_ USHORT CompressionFormat,
_Out_writes_bytes_to_(UncompressedBufferSize, *FinalUncompressedSize) PUCHAR UncompressedBuffer,
_In_ ULONG UncompressedBufferSize,
_In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
_In_ ULONG CompressedBufferSize,
_Out_ PULONG FinalUncompressedSize
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSAPI
NTSTATUS
NTAPI
RtlDecompressBufferEx(
_In_ USHORT CompressionFormat,
_Out_writes_bytes_to_(UncompressedBufferSize, *FinalUncompressedSize) PUCHAR UncompressedBuffer,
_In_ ULONG UncompressedBufferSize,
_In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
_In_ ULONG CompressedBufferSize,
_Out_ PULONG FinalUncompressedSize,
_In_ PVOID WorkSpace
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlDecompressFragment(
_In_ USHORT CompressionFormat,
_Out_writes_bytes_to_(UncompressedFragmentSize, *FinalUncompressedSize) PUCHAR UncompressedFragment,
_In_ ULONG UncompressedFragmentSize,
_In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
_In_ ULONG CompressedBufferSize,
_In_range_(<, CompressedBufferSize) ULONG FragmentOffset,
_Out_ PULONG FinalUncompressedSize,
_In_ PVOID WorkSpace
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDescribeChunk(
_In_ USHORT CompressionFormat,
_Inout_ PUCHAR *CompressedBuffer,
_In_ PUCHAR EndOfCompressedBufferPlus1,
_Out_ PUCHAR *ChunkBuffer,
_Out_ PULONG ChunkSize
);
NTSYSAPI
NTSTATUS
NTAPI
RtlReserveChunk(
_In_ USHORT CompressionFormat,
_Inout_ PUCHAR *CompressedBuffer,
_In_ PUCHAR EndOfCompressedBufferPlus1,
_Out_ PUCHAR *ChunkBuffer,
_In_ ULONG ChunkSize
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDecompressChunks(
_Out_writes_bytes_(UncompressedBufferSize) PUCHAR UncompressedBuffer,
_In_ ULONG UncompressedBufferSize,
_In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
_In_ ULONG CompressedBufferSize,
_In_reads_bytes_(CompressedTailSize) PUCHAR CompressedTail,
_In_ ULONG CompressedTailSize,
_In_ PCOMPRESSED_DATA_INFO CompressedDataInfo
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCompressChunks(
_In_reads_bytes_(UncompressedBufferSize) PUCHAR UncompressedBuffer,
_In_ ULONG UncompressedBufferSize,
_Out_writes_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
_In_range_(>=, (UncompressedBufferSize - (UncompressedBufferSize / 16))) ULONG CompressedBufferSize,
_Inout_updates_bytes_(CompressedDataInfoLength) PCOMPRESSED_DATA_INFO CompressedDataInfo,
_In_range_(>, sizeof(COMPRESSED_DATA_INFO)) ULONG CompressedDataInfoLength,
_In_ PVOID WorkSpace
);
// Locale
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlConvertLCIDToString(
_In_ LCID LcidValue,
_In_ ULONG Base,
_In_ ULONG Padding, // string is padded to this width
_Out_writes_(Size) PWSTR pResultBuf,
_In_ ULONG Size
);
// private
NTSYSAPI
BOOLEAN
NTAPI
RtlIsValidLocaleName(
_In_ PWSTR LocaleName,
_In_ ULONG Flags
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlGetParentLocaleName(
_In_ PWSTR LocaleName,
_Inout_ PUNICODE_STRING ParentLocaleName,
_In_ ULONG Flags,
_In_ BOOLEAN AllocateDestinationString
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlLcidToLocaleName(
_In_ LCID lcid, // sic
_Inout_ PUNICODE_STRING LocaleName,
_In_ ULONG Flags,
_In_ BOOLEAN AllocateDestinationString
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlLocaleNameToLcid(
_In_ PWSTR LocaleName,
_Out_ PLCID lcid,
_In_ ULONG Flags
);
// private
NTSYSAPI
BOOLEAN
NTAPI
RtlLCIDToCultureName(
_In_ LCID Lcid,
_Inout_ PUNICODE_STRING String
);
// private
NTSYSAPI
BOOLEAN
NTAPI
RtlCultureNameToLCID(
_In_ PUNICODE_STRING String,
_Out_ PLCID Lcid
);
// private
NTSYSAPI
VOID
NTAPI
RtlCleanUpTEBLangLists(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGetLocaleFileMappingAddress(
_Out_ PVOID *BaseAddress,
_Out_ PLCID DefaultLocaleId,
_Out_ PLARGE_INTEGER DefaultCasingTableSize
);
#endif
// PEB
NTSYSAPI
PPEB
NTAPI
RtlGetCurrentPeb(
VOID
);
NTSYSAPI
VOID
NTAPI
RtlAcquirePebLock(
VOID
);
NTSYSAPI
VOID
NTAPI
RtlReleasePebLock(
VOID
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
LOGICAL
NTAPI
RtlTryAcquirePebLock(
VOID
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlAllocateFromPeb(
_In_ ULONG Size,
_Out_ PVOID *Block
);
NTSYSAPI
NTSTATUS
NTAPI
RtlFreeToPeb(
_In_ PVOID Block,
_In_ ULONG Size
);
// Processes
#define DOS_MAX_COMPONENT_LENGTH 255
#define DOS_MAX_PATH_LENGTH (DOS_MAX_COMPONENT_LENGTH + 5)
typedef struct _CURDIR
{
UNICODE_STRING DosPath;
HANDLE Handle;
} CURDIR, *PCURDIR;
#define RTL_USER_PROC_CURDIR_CLOSE 0x00000002
#define RTL_USER_PROC_CURDIR_INHERIT 0x00000003
typedef struct _RTL_DRIVE_LETTER_CURDIR
{
USHORT Flags;
USHORT Length;
ULONG TimeStamp;
STRING DosPath;
} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
#define RTL_MAX_DRIVE_LETTERS 32
#define RTL_DRIVE_LETTER_VALID (USHORT)0x0001
typedef struct _RTL_USER_PROCESS_PARAMETERS
{
ULONG MaximumLength;
ULONG Length;
ULONG Flags;
ULONG DebugFlags;
HANDLE ConsoleHandle;
ULONG ConsoleFlags;
HANDLE StandardInput;
HANDLE StandardOutput;
HANDLE StandardError;
CURDIR CurrentDirectory;
UNICODE_STRING DllPath;
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
PVOID Environment;
ULONG StartingX;
ULONG StartingY;
ULONG CountX;
ULONG CountY;
ULONG CountCharsX;
ULONG CountCharsY;
ULONG FillAttribute;
ULONG WindowFlags;
ULONG ShowWindowFlags;
UNICODE_STRING WindowTitle;
UNICODE_STRING DesktopInfo;
UNICODE_STRING ShellInfo;
UNICODE_STRING RuntimeData;
RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];
ULONG_PTR EnvironmentSize;
ULONG_PTR EnvironmentVersion;
PVOID PackageDependencyData;
ULONG ProcessGroupId;
ULONG LoaderThreads;
UNICODE_STRING RedirectionDllName; // REDSTONE4
UNICODE_STRING HeapPartitionName; // 19H1
ULONG_PTR DefaultThreadpoolCpuSetMasks;
ULONG DefaultThreadpoolCpuSetMaskCount;
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
#define RTL_USER_PROC_PARAMS_NORMALIZED 0x00000001
#define RTL_USER_PROC_PROFILE_USER 0x00000002
#define RTL_USER_PROC_PROFILE_KERNEL 0x00000004
#define RTL_USER_PROC_PROFILE_SERVER 0x00000008
#define RTL_USER_PROC_RESERVE_1MB 0x00000020
#define RTL_USER_PROC_RESERVE_16MB 0x00000040
#define RTL_USER_PROC_CASE_SENSITIVE 0x00000080
#define RTL_USER_PROC_DISABLE_HEAP_DECOMMIT 0x00000100
#define RTL_USER_PROC_DLL_REDIRECTION_LOCAL 0x00001000
#define RTL_USER_PROC_APP_MANIFEST_PRESENT 0x00002000
#define RTL_USER_PROC_IMAGE_KEY_MISSING 0x00004000
#define RTL_USER_PROC_OPTIN_PROCESS 0x00020000
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateProcessParameters(
_Out_ PRTL_USER_PROCESS_PARAMETERS *pProcessParameters,
_In_ PUNICODE_STRING ImagePathName,
_In_opt_ PUNICODE_STRING DllPath,
_In_opt_ PUNICODE_STRING CurrentDirectory,
_In_opt_ PUNICODE_STRING CommandLine,
_In_opt_ PVOID Environment,
_In_opt_ PUNICODE_STRING WindowTitle,
_In_opt_ PUNICODE_STRING DesktopInfo,
_In_opt_ PUNICODE_STRING ShellInfo,
_In_opt_ PUNICODE_STRING RuntimeData
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateProcessParametersEx(
_Out_ PRTL_USER_PROCESS_PARAMETERS *pProcessParameters,
_In_ PUNICODE_STRING ImagePathName,
_In_opt_ PUNICODE_STRING DllPath,
_In_opt_ PUNICODE_STRING CurrentDirectory,
_In_opt_ PUNICODE_STRING CommandLine,
_In_opt_ PVOID Environment,
_In_opt_ PUNICODE_STRING WindowTitle,
_In_opt_ PUNICODE_STRING DesktopInfo,
_In_opt_ PUNICODE_STRING ShellInfo,
_In_opt_ PUNICODE_STRING RuntimeData,
_In_ ULONG Flags // pass RTL_USER_PROC_PARAMS_NORMALIZED to keep parameters normalized
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyProcessParameters(
_In_ _Post_invalid_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
);
NTSYSAPI
PRTL_USER_PROCESS_PARAMETERS
NTAPI
RtlNormalizeProcessParams(
_Inout_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
);
NTSYSAPI
PRTL_USER_PROCESS_PARAMETERS
NTAPI
RtlDeNormalizeProcessParams(
_Inout_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
);
typedef struct _RTL_USER_PROCESS_INFORMATION
{
ULONG Length;
HANDLE Process;
HANDLE Thread;
CLIENT_ID ClientId;
SECTION_IMAGE_INFORMATION ImageInformation;
} RTL_USER_PROCESS_INFORMATION, *PRTL_USER_PROCESS_INFORMATION;
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateUserProcess(
_In_ PUNICODE_STRING NtImagePathName,
_In_ ULONG AttributesDeprecated,
_In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters,
_In_opt_ PSECURITY_DESCRIPTOR ProcessSecurityDescriptor,
_In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
_In_opt_ HANDLE ParentProcess,
_In_ BOOLEAN InheritHandles,
_In_opt_ HANDLE DebugPort,
_In_opt_ HANDLE TokenHandle, // used to be ExceptionPort
_Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateUserProcessEx(
_In_ PUNICODE_STRING NtImagePathName,
_In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters,
_In_ BOOLEAN InheritHandles,
_Reserved_ ULONG Flags,
_Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
DECLSPEC_NORETURN
NTSYSAPI
VOID
NTAPI
RtlExitUserProcess(
_In_ NTSTATUS ExitStatus
);
#else
#define RtlExitUserProcess RtlExitUserProcess_R
DECLSPEC_NORETURN
FORCEINLINE VOID RtlExitUserProcess_R(
_In_ NTSTATUS ExitStatus
)
{
ExitProcess(ExitStatus);
}
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// begin_rev
#define RTL_CLONE_PROCESS_FLAGS_CREATE_SUSPENDED 0x00000001
#define RTL_CLONE_PROCESS_FLAGS_INHERIT_HANDLES 0x00000002
#define RTL_CLONE_PROCESS_FLAGS_NO_SYNCHRONIZE 0x00000004 // don't update synchronization objects
// end_rev
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlCloneUserProcess(
_In_ ULONG ProcessFlags,
_In_opt_ PSECURITY_DESCRIPTOR ProcessSecurityDescriptor,
_In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
_In_opt_ HANDLE DebugPort,
_Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation
);
// private
NTSYSAPI
VOID
NTAPI
RtlUpdateClonedCriticalSection(
_Inout_ PRTL_CRITICAL_SECTION CriticalSection
);
// private
NTSYSAPI
VOID
NTAPI
RtlUpdateClonedSRWLock(
_Inout_ PRTL_SRWLOCK SRWLock,
_In_ LOGICAL Shared // TRUE to set to shared acquire
);
// private
typedef struct _RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION
{
HANDLE ReflectionProcessHandle;
HANDLE ReflectionThreadHandle;
CLIENT_ID ReflectionClientId;
} RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION, *PRTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION;
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateProcessReflection(
_In_ HANDLE ProcessHandle,
_In_ ULONG Flags,
_In_opt_ PVOID StartRoutine,
_In_opt_ PVOID StartContext,
_In_opt_ HANDLE EventHandle,
_Out_opt_ PRTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION ReflectionInformation
);
#endif
#endif
NTSYSAPI
NTSTATUS
STDAPIVCALLTYPE
RtlSetProcessIsCritical(
_In_ BOOLEAN NewValue,
_Out_opt_ PBOOLEAN OldValue,
_In_ BOOLEAN CheckFlag
);
NTSYSAPI
NTSTATUS
STDAPIVCALLTYPE
RtlSetThreadIsCritical(
_In_ BOOLEAN NewValue,
_Out_opt_ PBOOLEAN OldValue,
_In_ BOOLEAN CheckFlag
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlValidProcessProtection(
_In_ PS_PROTECTION ProcessProtection
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlTestProtectedAccess(
_In_ PS_PROTECTION Source,
_In_ PS_PROTECTION Target
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS3)
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsCurrentProcess( // NtCompareObjects(NtCurrentProcess(), ProcessHandle)
_In_ HANDLE ProcessHandle
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsCurrentThread( // NtCompareObjects(NtCurrentThread(), ThreadHandle)
_In_ HANDLE ThreadHandle
);
#endif
// Threads
typedef NTSTATUS (NTAPI *PUSER_THREAD_START_ROUTINE)(
_In_ PVOID ThreadParameter
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateUserThread(
_In_ HANDLE Process,
_In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
_In_ BOOLEAN CreateSuspended,
_In_opt_ ULONG ZeroBits,
_In_opt_ SIZE_T MaximumStackSize,
_In_opt_ SIZE_T CommittedStackSize,
_In_ PUSER_THREAD_START_ROUTINE StartAddress,
_In_opt_ PVOID Parameter,
_Out_opt_ PHANDLE Thread,
_Out_opt_ PCLIENT_ID ClientId
);
#if (NTDDI_VERSION >= NTDDI_VISTA) // should be NTDDI_WINXP, but is NTDDI_VISTA for consistency with RtlExitUserProcess
DECLSPEC_NORETURN
NTSYSAPI
VOID
NTAPI
RtlExitUserThread(
_In_ NTSTATUS ExitStatus
);
#else
#define RtlExitUserThread RtlExitUserThread_R
DECLSPEC_NORETURN
FORCEINLINE VOID RtlExitUserThread_R(
_In_ NTSTATUS ExitStatus
)
{
ExitThread(ExitStatus);
}
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsCurrentThreadAttachExempt(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateUserStack(
_In_opt_ SIZE_T CommittedStackSize,
_In_opt_ SIZE_T MaximumStackSize,
_In_opt_ ULONG_PTR ZeroBits,
_In_ SIZE_T PageSize,
_In_ ULONG_PTR ReserveAlignment,
_Out_ PINITIAL_TEB InitialTeb
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlFreeUserStack(
_In_ PVOID AllocationBase
);
#endif
// Extended thread context
typedef struct _CONTEXT_CHUNK
{
LONG Offset; // Offset may be negative.
ULONG Length;
} CONTEXT_CHUNK, *PCONTEXT_CHUNK;
typedef struct _CONTEXT_EX
{
CONTEXT_CHUNK All;
CONTEXT_CHUNK Legacy;
CONTEXT_CHUNK XState;
} CONTEXT_EX, *PCONTEXT_EX;
#define CONTEXT_EX_LENGTH ALIGN_UP_BY(sizeof(CONTEXT_EX), PAGE_SIZE)
#define RTL_CONTEXT_EX_OFFSET(ContextEx, Chunk) ((ContextEx)->Chunk.Offset)
#define RTL_CONTEXT_EX_LENGTH(ContextEx, Chunk) ((ContextEx)->Chunk.Length)
#define RTL_CONTEXT_EX_CHUNK(Base, Layout, Chunk) ((PVOID)((PCHAR)(Base) + RTL_CONTEXT_EX_OFFSET(Layout, Chunk)))
#define RTL_CONTEXT_OFFSET(Context, Chunk) RTL_CONTEXT_EX_OFFSET((PCONTEXT_EX)(Context + 1), Chunk)
#define RTL_CONTEXT_LENGTH(Context, Chunk) RTL_CONTEXT_EX_LENGTH((PCONTEXT_EX)(Context + 1), Chunk)
#define RTL_CONTEXT_CHUNK(Context, Chunk) RTL_CONTEXT_EX_CHUNK((PCONTEXT_EX)(Context + 1), (PCONTEXT_EX)(Context + 1), Chunk)
NTSYSAPI
VOID
NTAPI
RtlInitializeContext(
_In_ HANDLE Process,
_Out_ PCONTEXT Context,
_In_opt_ PVOID Parameter,
_In_opt_ PVOID InitialPc,
_In_opt_ PVOID InitialSp
);
NTSYSAPI
ULONG
NTAPI
RtlInitializeExtendedContext(
_Out_ PCONTEXT Context,
_In_ ULONG ContextFlags,
_Out_ PCONTEXT_EX* ContextEx
);
NTSYSAPI
ULONG
NTAPI
RtlCopyExtendedContext(
_Out_ PCONTEXT_EX Destination,
_In_ ULONG ContextFlags,
_In_ PCONTEXT_EX Source
);
NTSYSAPI
ULONG
NTAPI
RtlGetExtendedContextLength(
_In_ ULONG ContextFlags,
_Out_ PULONG ContextLength
);
NTSYSAPI
ULONG64
NTAPI
RtlGetExtendedFeaturesMask(
_In_ PCONTEXT_EX ContextEx
);
NTSYSAPI
PVOID
NTAPI
RtlLocateExtendedFeature(
_In_ PCONTEXT_EX ContextEx,
_In_ ULONG FeatureId,
_Out_opt_ PULONG Length
);
NTSYSAPI
PCONTEXT
NTAPI
RtlLocateLegacyContext(
_In_ PCONTEXT_EX ContextEx,
_Out_opt_ PULONG Length
);
NTSYSAPI
VOID
NTAPI
RtlSetExtendedFeaturesMask(
__out PCONTEXT_EX ContextEx,
_Out_ ULONG64 FeatureMask
);
#ifdef _WIN64
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlWow64GetThreadContext(
_In_ HANDLE ThreadHandle,
_Inout_ PWOW64_CONTEXT ThreadContext
);
#endif
#ifdef _WIN64
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlWow64SetThreadContext(
_In_ HANDLE ThreadHandle,
_In_ PWOW64_CONTEXT ThreadContext
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlRemoteCall(
_In_ HANDLE Process,
_In_ HANDLE Thread,
_In_ PVOID CallSite,
_In_ ULONG ArgumentCount,
_In_opt_ PULONG_PTR Arguments,
_In_ BOOLEAN PassContext,
_In_ BOOLEAN AlreadySuspended
);
// Vectored exception handlers
NTSYSAPI
PVOID
NTAPI
RtlAddVectoredExceptionHandler(
_In_ ULONG First,
_In_ PVECTORED_EXCEPTION_HANDLER Handler
);
NTSYSAPI
ULONG
NTAPI
RtlRemoveVectoredExceptionHandler(
_In_ PVOID Handle
);
NTSYSAPI
PVOID
NTAPI
RtlAddVectoredContinueHandler(
_In_ ULONG First,
_In_ PVECTORED_EXCEPTION_HANDLER Handler
);
NTSYSAPI
ULONG
NTAPI
RtlRemoveVectoredContinueHandler(
_In_ PVOID Handle
);
// Runtime exception handling
typedef ULONG (NTAPI *PRTLP_UNHANDLED_EXCEPTION_FILTER)(
_In_ PEXCEPTION_POINTERS ExceptionInfo
);
NTSYSAPI
VOID
NTAPI
RtlSetUnhandledExceptionFilter(
_In_ PRTLP_UNHANDLED_EXCEPTION_FILTER UnhandledExceptionFilter
);
// rev
NTSYSAPI
LONG
NTAPI
RtlUnhandledExceptionFilter(
_In_ PEXCEPTION_POINTERS ExceptionPointers
);
// rev
NTSYSAPI
LONG
NTAPI
RtlUnhandledExceptionFilter2(
_In_ PEXCEPTION_POINTERS ExceptionPointers,
_In_ ULONG Flags
);
// rev
NTSYSAPI
LONG
NTAPI
RtlKnownExceptionFilter(
_In_ PEXCEPTION_POINTERS ExceptionPointers
);
#ifdef _WIN64
// private
typedef enum _FUNCTION_TABLE_TYPE
{
RF_SORTED,
RF_UNSORTED,
RF_CALLBACK,
RF_KERNEL_DYNAMIC
} FUNCTION_TABLE_TYPE;
// private
typedef struct _DYNAMIC_FUNCTION_TABLE
{
LIST_ENTRY ListEntry;
PRUNTIME_FUNCTION FunctionTable;
LARGE_INTEGER TimeStamp;
ULONG64 MinimumAddress;
ULONG64 MaximumAddress;
ULONG64 BaseAddress;
PGET_RUNTIME_FUNCTION_CALLBACK Callback;
PVOID Context;
PWSTR OutOfProcessCallbackDll;
FUNCTION_TABLE_TYPE Type;
ULONG EntryCount;
RTL_BALANCED_NODE TreeNode;
} DYNAMIC_FUNCTION_TABLE, *PDYNAMIC_FUNCTION_TABLE;
// rev
NTSYSAPI
PLIST_ENTRY
NTAPI
RtlGetFunctionTableListHead(
VOID
);
#endif
// Images
NTSYSAPI
PIMAGE_NT_HEADERS
NTAPI
RtlImageNtHeader(
_In_ PVOID BaseOfImage
);
#define RTL_IMAGE_NT_HEADER_EX_FLAG_NO_RANGE_CHECK 0x00000001
NTSYSAPI
NTSTATUS
NTAPI
RtlImageNtHeaderEx(
_In_ ULONG Flags,
_In_ PVOID BaseOfImage,
_In_ ULONG64 Size,
_Out_ PIMAGE_NT_HEADERS *OutHeaders
);
NTSYSAPI
PVOID
NTAPI
RtlAddressInSectionTable(
_In_ PIMAGE_NT_HEADERS NtHeaders,
_In_ PVOID BaseOfImage,
_In_ ULONG VirtualAddress
);
NTSYSAPI
PIMAGE_SECTION_HEADER
NTAPI
RtlSectionTableFromVirtualAddress(
_In_ PIMAGE_NT_HEADERS NtHeaders,
_In_ PVOID BaseOfImage,
_In_ ULONG VirtualAddress
);
NTSYSAPI
PVOID
NTAPI
RtlImageDirectoryEntryToData(
_In_ PVOID BaseOfImage,
_In_ BOOLEAN MappedAsImage,
_In_ USHORT DirectoryEntry,
_Out_ PULONG Size
);
NTSYSAPI
PIMAGE_SECTION_HEADER
NTAPI
RtlImageRvaToSection(
_In_ PIMAGE_NT_HEADERS NtHeaders,
_In_ PVOID BaseOfImage,
_In_ ULONG Rva
);
NTSYSAPI
PVOID
NTAPI
RtlImageRvaToVa(
_In_ PIMAGE_NT_HEADERS NtHeaders,
_In_ PVOID BaseOfImage,
_In_ ULONG Rva,
_Inout_opt_ PIMAGE_SECTION_HEADER *LastRvaSection
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
// rev
NTSYSAPI
PVOID
NTAPI
RtlFindExportedRoutineByName(
_In_ PVOID BaseOfImage,
_In_ PSTR RoutineName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGuardCheckLongJumpTarget(
_In_ PVOID PcValue,
_In_ BOOL IsFastFail,
_Out_ PBOOL IsLongJumpTarget
);
#endif
// Memory
NTSYSAPI
SIZE_T
NTAPI
RtlCompareMemoryUlong(
_In_ PVOID Source,
_In_ SIZE_T Length,
_In_ ULONG Pattern
);
NTSYSAPI
VOID
NTAPI
RtlFillMemoryUlong(
_Out_ PVOID Destination,
_In_ SIZE_T Length,
_In_ ULONG Pattern
);
NTSYSAPI
VOID
NTAPI
RtlFillMemoryUlonglong(
_Out_ PVOID Destination,
_In_ SIZE_T Length,
_In_ ULONGLONG Pattern
);
// Environment
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateEnvironment(
_In_ BOOLEAN CloneCurrentEnvironment,
_Out_ PVOID *Environment
);
// begin_rev
#define RTL_CREATE_ENVIRONMENT_TRANSLATE 0x1 // translate from multi-byte to Unicode
#define RTL_CREATE_ENVIRONMENT_TRANSLATE_FROM_OEM 0x2 // translate from OEM to Unicode (Translate flag must also be set)
#define RTL_CREATE_ENVIRONMENT_EMPTY 0x4 // create empty environment block
// end_rev
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateEnvironmentEx(
_In_ PVOID SourceEnv,
_Out_ PVOID *Environment,
_In_ ULONG Flags
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyEnvironment(
_In_ PVOID Environment
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetCurrentEnvironment(
_In_ PVOID Environment,
_Out_opt_ PVOID *PreviousEnvironment
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSetEnvironmentVar(
_In_opt_ PWSTR *Environment,
_In_reads_(NameLength) PWSTR Name,
_In_ SIZE_T NameLength,
_In_reads_(ValueLength) PWSTR Value,
_In_ SIZE_T ValueLength
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlSetEnvironmentVariable(
_In_opt_ PVOID *Environment,
_In_ PUNICODE_STRING Name,
_In_opt_ PUNICODE_STRING Value
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryEnvironmentVariable(
_In_opt_ PVOID Environment,
_In_reads_(NameLength) PWSTR Name,
_In_ SIZE_T NameLength,
_Out_writes_(ValueLength) PWSTR Value,
_In_ SIZE_T ValueLength,
_Out_ PSIZE_T ReturnLength
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryEnvironmentVariable_U(
_In_opt_ PVOID Environment,
_In_ PUNICODE_STRING Name,
_Out_ PUNICODE_STRING Value
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlExpandEnvironmentStrings(
_In_opt_ PVOID Environment,
_In_reads_(SrcLength) PWSTR Src,
_In_ SIZE_T SrcLength,
_Out_writes_(DstLength) PWSTR Dst,
_In_ SIZE_T DstLength,
_Out_opt_ PSIZE_T ReturnLength
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlExpandEnvironmentStrings_U(
_In_opt_ PVOID Environment,
_In_ PUNICODE_STRING Source,
_Out_ PUNICODE_STRING Destination,
_Out_opt_ PULONG ReturnedLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetEnvironmentStrings(
_In_ PWCHAR NewEnvironment,
_In_ SIZE_T NewEnvironmentSize
);
// Directory and path support
typedef struct _RTLP_CURDIR_REF
{
LONG ReferenceCount;
HANDLE DirectoryHandle;
} RTLP_CURDIR_REF, *PRTLP_CURDIR_REF;
typedef struct _RTL_RELATIVE_NAME_U
{
UNICODE_STRING RelativeName;
HANDLE ContainingDirectory;
PRTLP_CURDIR_REF CurDirRef;
} RTL_RELATIVE_NAME_U, *PRTL_RELATIVE_NAME_U;
typedef enum _RTL_PATH_TYPE
{
RtlPathTypeUnknown,
RtlPathTypeUncAbsolute,
RtlPathTypeDriveAbsolute,
RtlPathTypeDriveRelative,
RtlPathTypeRooted,
RtlPathTypeRelative,
RtlPathTypeLocalDevice,
RtlPathTypeRootLocalDevice
} RTL_PATH_TYPE;
// Data exports (ntdll.lib/ntdllp.lib)
NTSYSAPI PWSTR RtlNtdllName;
NTSYSAPI UNICODE_STRING RtlDosPathSeperatorsString;
NTSYSAPI UNICODE_STRING RtlAlternateDosPathSeperatorString;
NTSYSAPI UNICODE_STRING RtlNtPathSeperatorString;
// Path functions
NTSYSAPI
RTL_PATH_TYPE
NTAPI
RtlDetermineDosPathNameType_U(
_In_ PWSTR DosFileName
);
NTSYSAPI
RTL_PATH_TYPE
NTAPI
RtlDetermineDosPathNameType_Ustr(
_In_ PCUNICODE_STRING DosFileName
);
NTSYSAPI
ULONG
NTAPI
RtlIsDosDeviceName_U(
_In_ PWSTR DosFileName
);
NTSYSAPI
ULONG
NTAPI
RtlIsDosDeviceName_Ustr(
_In_ PUNICODE_STRING DosFileName
);
NTSYSAPI
ULONG
NTAPI
RtlGetFullPathName_U(
_In_ PWSTR FileName,
_In_ ULONG BufferLength,
_Out_writes_bytes_(BufferLength) PWSTR Buffer,
_Out_opt_ PWSTR *FilePart
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGetFullPathName_UEx(
_In_ PWSTR FileName,
_In_ ULONG BufferLength,
_Out_writes_bytes_(BufferLength) PWSTR Buffer,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ ULONG *BytesRequired
);
#endif
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSAPI
NTSTATUS
NTAPI
RtlGetFullPathName_UstrEx(
_In_ PUNICODE_STRING FileName,
_Inout_ PUNICODE_STRING StaticString,
_Out_opt_ PUNICODE_STRING DynamicString,
_Out_opt_ PUNICODE_STRING *StringUsed,
_Out_opt_ SIZE_T *FilePartPrefixCch,
_Out_opt_ PBOOLEAN NameInvalid,
_Out_ RTL_PATH_TYPE *InputPathType,
_Out_opt_ SIZE_T *BytesRequired
);
#endif
NTSYSAPI
ULONG
NTAPI
RtlGetCurrentDirectory_U(
_In_ ULONG BufferLength,
_Out_writes_bytes_(BufferLength) PWSTR Buffer
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetCurrentDirectory_U(
_In_ PUNICODE_STRING PathName
);
NTSYSAPI
ULONG
NTAPI
RtlGetLongestNtPathLength(
VOID
);
NTSYSAPI
BOOLEAN
NTAPI
RtlDosPathNameToNtPathName_U(
_In_ PWSTR DosFileName,
_Out_ PUNICODE_STRING NtFileName,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
);
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSAPI
NTSTATUS
NTAPI
RtlDosPathNameToNtPathName_U_WithStatus(
_In_ PWSTR DosFileName,
_Out_ PUNICODE_STRING NtFileName,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS3)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlDosLongPathNameToNtPathName_U_WithStatus(
_In_ PWSTR DosFileName,
_Out_ PUNICODE_STRING NtFileName,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSAPI
BOOLEAN
NTAPI
RtlDosPathNameToRelativeNtPathName_U(
_In_ PWSTR DosFileName,
_Out_ PUNICODE_STRING NtFileName,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSAPI
NTSTATUS
NTAPI
RtlDosPathNameToRelativeNtPathName_U_WithStatus(
_In_ PWSTR DosFileName,
_Out_ PUNICODE_STRING NtFileName,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS3)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlDosLongPathNameToRelativeNtPathName_U_WithStatus(
_In_ PWSTR DosFileName,
_Out_ PUNICODE_STRING NtFileName,
_Out_opt_ PWSTR *FilePart,
_Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
);
#endif
#if (NTDDI_VERSION >= NTDDI_WS03)
NTSYSAPI
VOID
NTAPI
RtlReleaseRelativeName(
_Inout_ PRTL_RELATIVE_NAME_U RelativeName
);
#endif
NTSYSAPI
ULONG
NTAPI
RtlDosSearchPath_U(
_In_ PWSTR Path,
_In_ PWSTR FileName,
_In_opt_ PWSTR Extension,
_In_ ULONG BufferLength,
_Out_writes_bytes_(BufferLength) PWSTR Buffer,
_Out_opt_ PWSTR *FilePart
);
#define RTL_DOS_SEARCH_PATH_FLAG_APPLY_ISOLATION_REDIRECTION 0x00000001
#define RTL_DOS_SEARCH_PATH_FLAG_DISALLOW_DOT_RELATIVE_PATH_SEARCH 0x00000002
#define RTL_DOS_SEARCH_PATH_FLAG_APPLY_DEFAULT_EXTENSION_WHEN_NOT_RELATIVE_PATH_EVEN_IF_FILE_HAS_EXTENSION 0x00000004
NTSYSAPI
NTSTATUS
NTAPI
RtlDosSearchPath_Ustr(
_In_ ULONG Flags,
_In_ PUNICODE_STRING Path,
_In_ PUNICODE_STRING FileName,
_In_opt_ PUNICODE_STRING DefaultExtension,
_Out_opt_ PUNICODE_STRING StaticString,
_Out_opt_ PUNICODE_STRING DynamicString,
_Out_opt_ PCUNICODE_STRING *FullFileNameOut,
_Out_opt_ SIZE_T *FilePartPrefixCch,
_Out_opt_ SIZE_T *BytesRequired
);
NTSYSAPI
BOOLEAN
NTAPI
RtlDoesFileExists_U(
_In_ PWSTR FileName
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetLengthWithoutLastFullDosOrNtPathElement(
_Reserved_ ULONG Flags,
_In_ PUNICODE_STRING PathString,
_Out_ PULONG Length
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetLengthWithoutTrailingPathSeperators(
_Reserved_ ULONG Flags,
_In_ PUNICODE_STRING PathString,
_Out_ PULONG Length
);
typedef struct _GENERATE_NAME_CONTEXT
{
USHORT Checksum;
BOOLEAN CheckSumInserted;
UCHAR NameLength;
WCHAR NameBuffer[8];
ULONG ExtensionLength;
WCHAR ExtensionBuffer[4];
ULONG LastIndexValue;
} GENERATE_NAME_CONTEXT, *PGENERATE_NAME_CONTEXT;
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlGenerate8dot3Name(
_In_ PUNICODE_STRING Name,
_In_ BOOLEAN AllowExtendedCharacters,
_In_ PGENERATE_NAME_CONTEXT Context,
_Out_ PUNICODE_STRING Name8dot3
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlComputePrivatizedDllName_U(
_In_ PUNICODE_STRING DllName,
_Out_ PUNICODE_STRING RealName,
_Out_ PUNICODE_STRING LocalName
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlGetSearchPath(
_Out_ PWSTR *SearchPath
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlSetSearchPathMode(
_In_ ULONG Flags
);
// rev
NTSYSAPI
PWSTR
NTAPI
RtlGetExePath(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS2)
// private
NTSYSAPI
PWSTR
NTAPI
RtlGetNtSystemRoot(
VOID
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlAreLongPathsEnabled(
VOID
);
#endif
NTSYSAPI
BOOLEAN
NTAPI
RtlIsThreadWithinLoaderCallout(
VOID
);
NTSYSAPI
BOOLEAN
NTAPI
RtlDllShutdownInProgress(
VOID
);
// Heaps
typedef struct _RTL_HEAP_ENTRY
{
SIZE_T Size;
USHORT Flags;
USHORT AllocatorBackTraceIndex;
union
{
struct
{
SIZE_T Settable;
ULONG Tag;
} s1;
struct
{
SIZE_T CommittedSize;
PVOID FirstBlock;
} s2;
} u;
} RTL_HEAP_ENTRY, *PRTL_HEAP_ENTRY;
#define RTL_HEAP_BUSY (USHORT)0x0001
#define RTL_HEAP_SEGMENT (USHORT)0x0002
#define RTL_HEAP_SETTABLE_VALUE (USHORT)0x0010
#define RTL_HEAP_SETTABLE_FLAG1 (USHORT)0x0020
#define RTL_HEAP_SETTABLE_FLAG2 (USHORT)0x0040
#define RTL_HEAP_SETTABLE_FLAG3 (USHORT)0x0080
#define RTL_HEAP_SETTABLE_FLAGS (USHORT)0x00e0
#define RTL_HEAP_UNCOMMITTED_RANGE (USHORT)0x0100
#define RTL_HEAP_PROTECTED_ENTRY (USHORT)0x0200
typedef struct _RTL_HEAP_TAG
{
ULONG NumberOfAllocations;
ULONG NumberOfFrees;
SIZE_T BytesAllocated;
USHORT TagIndex;
USHORT CreatorBackTraceIndex;
WCHAR TagName[24];
} RTL_HEAP_TAG, *PRTL_HEAP_TAG;
typedef struct _RTL_HEAP_INFORMATION
{
PVOID BaseAddress;
ULONG Flags;
USHORT EntryOverhead;
USHORT CreatorBackTraceIndex;
SIZE_T BytesAllocated;
SIZE_T BytesCommitted;
ULONG NumberOfTags;
ULONG NumberOfEntries;
ULONG NumberOfPseudoTags;
ULONG PseudoTagGranularity;
ULONG Reserved[5];
PRTL_HEAP_TAG Tags;
PRTL_HEAP_ENTRY Entries;
} RTL_HEAP_INFORMATION, *PRTL_HEAP_INFORMATION;
typedef struct _RTL_PROCESS_HEAPS
{
ULONG NumberOfHeaps;
RTL_HEAP_INFORMATION Heaps[1];
} RTL_PROCESS_HEAPS, *PRTL_PROCESS_HEAPS;
typedef NTSTATUS (NTAPI *PRTL_HEAP_COMMIT_ROUTINE)(
_In_ PVOID Base,
_Inout_ PVOID *CommitAddress,
_Inout_ PSIZE_T CommitSize
);
typedef struct _RTL_HEAP_PARAMETERS
{
ULONG Length;
SIZE_T SegmentReserve;
SIZE_T SegmentCommit;
SIZE_T DeCommitFreeBlockThreshold;
SIZE_T DeCommitTotalFreeThreshold;
SIZE_T MaximumAllocationSize;
SIZE_T VirtualMemoryThreshold;
SIZE_T InitialCommit;
SIZE_T InitialReserve;
PRTL_HEAP_COMMIT_ROUTINE CommitRoutine;
SIZE_T Reserved[2];
} RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS;
#define HEAP_SETTABLE_USER_VALUE 0x00000100
#define HEAP_SETTABLE_USER_FLAG1 0x00000200
#define HEAP_SETTABLE_USER_FLAG2 0x00000400
#define HEAP_SETTABLE_USER_FLAG3 0x00000800
#define HEAP_SETTABLE_USER_FLAGS 0x00000e00
#define HEAP_CLASS_0 0x00000000 // Process heap
#define HEAP_CLASS_1 0x00001000 // Private heap
#define HEAP_CLASS_2 0x00002000 // Kernel heap
#define HEAP_CLASS_3 0x00003000 // GDI heap
#define HEAP_CLASS_4 0x00004000 // User heap
#define HEAP_CLASS_5 0x00005000 // Console heap
#define HEAP_CLASS_6 0x00006000 // User desktop heap
#define HEAP_CLASS_7 0x00007000 // CSR shared heap
#define HEAP_CLASS_8 0x00008000 // CSR port heap
#define HEAP_CLASS_MASK 0x0000f000
NTSYSAPI
PVOID
NTAPI
RtlCreateHeap(
_In_ ULONG Flags,
_In_opt_ PVOID HeapBase,
_In_opt_ SIZE_T ReserveSize,
_In_opt_ SIZE_T CommitSize,
_In_opt_ PVOID Lock,
_In_opt_ PRTL_HEAP_PARAMETERS Parameters
);
NTSYSAPI
PVOID
NTAPI
RtlDestroyHeap(
_Frees_ptr_ PVOID HeapHandle
);
NTSYSAPI
PVOID
NTAPI
RtlAllocateHeap(
_In_ PVOID HeapHandle,
_In_opt_ ULONG Flags,
_In_ SIZE_T Size
);
NTSYSAPI
BOOLEAN
NTAPI
RtlFreeHeap(
_In_ PVOID HeapHandle,
_In_opt_ ULONG Flags,
_Frees_ptr_opt_ PVOID BaseAddress
);
NTSYSAPI
SIZE_T
NTAPI
RtlSizeHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress
);
NTSYSAPI
NTSTATUS
NTAPI
RtlZeroHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags
);
NTSYSAPI
VOID
NTAPI
RtlProtectHeap(
_In_ PVOID HeapHandle,
_In_ BOOLEAN MakeReadOnly
);
#define RtlProcessHeap() (NtCurrentPeb()->ProcessHeap)
NTSYSAPI
BOOLEAN
NTAPI
RtlLockHeap(
_In_ PVOID HeapHandle
);
NTSYSAPI
BOOLEAN
NTAPI
RtlUnlockHeap(
_In_ PVOID HeapHandle
);
NTSYSAPI
PVOID
NTAPI
RtlReAllocateHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_Frees_ptr_opt_ PVOID BaseAddress,
_In_ SIZE_T Size
);
NTSYSAPI
BOOLEAN
NTAPI
RtlGetUserInfoHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress,
_Out_opt_ PVOID *UserValue,
_Out_opt_ PULONG UserFlags
);
NTSYSAPI
BOOLEAN
NTAPI
RtlSetUserValueHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress,
_In_ PVOID UserValue
);
NTSYSAPI
BOOLEAN
NTAPI
RtlSetUserFlagsHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress,
_In_ ULONG UserFlagsReset,
_In_ ULONG UserFlagsSet
);
typedef struct _RTL_HEAP_TAG_INFO
{
ULONG NumberOfAllocations;
ULONG NumberOfFrees;
SIZE_T BytesAllocated;
} RTL_HEAP_TAG_INFO, *PRTL_HEAP_TAG_INFO;
#define RTL_HEAP_MAKE_TAG HEAP_MAKE_TAG_FLAGS
NTSYSAPI
ULONG
NTAPI
RtlCreateTagHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_opt_ PWSTR TagPrefix,
_In_ PWSTR TagNames
);
NTSYSAPI
PWSTR
NTAPI
RtlQueryTagHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ USHORT TagIndex,
_In_ BOOLEAN ResetCounters,
_Out_opt_ PRTL_HEAP_TAG_INFO TagInfo
);
NTSYSAPI
NTSTATUS
NTAPI
RtlExtendHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ PVOID Base,
_In_ SIZE_T Size
);
NTSYSAPI
SIZE_T
NTAPI
RtlCompactHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags
);
NTSYSAPI
BOOLEAN
NTAPI
RtlValidateHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ PVOID BaseAddress
);
NTSYSAPI
BOOLEAN
NTAPI
RtlValidateProcessHeaps(
VOID
);
NTSYSAPI
ULONG
NTAPI
RtlGetProcessHeaps(
_In_ ULONG NumberOfHeaps,
_Out_ PVOID *ProcessHeaps
);
typedef NTSTATUS (NTAPI *PRTL_ENUM_HEAPS_ROUTINE)(
_In_ PVOID HeapHandle,
_In_ PVOID Parameter
);
NTSYSAPI
NTSTATUS
NTAPI
RtlEnumProcessHeaps(
_In_ PRTL_ENUM_HEAPS_ROUTINE EnumRoutine,
_In_ PVOID Parameter
);
typedef struct _RTL_HEAP_USAGE_ENTRY
{
struct _RTL_HEAP_USAGE_ENTRY *Next;
PVOID Address;
SIZE_T Size;
USHORT AllocatorBackTraceIndex;
USHORT TagIndex;
} RTL_HEAP_USAGE_ENTRY, *PRTL_HEAP_USAGE_ENTRY;
typedef struct _RTL_HEAP_USAGE
{
ULONG Length;
SIZE_T BytesAllocated;
SIZE_T BytesCommitted;
SIZE_T BytesReserved;
SIZE_T BytesReservedMaximum;
PRTL_HEAP_USAGE_ENTRY Entries;
PRTL_HEAP_USAGE_ENTRY AddedEntries;
PRTL_HEAP_USAGE_ENTRY RemovedEntries;
ULONG_PTR Reserved[8];
} RTL_HEAP_USAGE, *PRTL_HEAP_USAGE;
#define HEAP_USAGE_ALLOCATED_BLOCKS HEAP_REALLOC_IN_PLACE_ONLY
#define HEAP_USAGE_FREE_BUFFER HEAP_ZERO_MEMORY
NTSYSAPI
NTSTATUS
NTAPI
RtlUsageHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_Inout_ PRTL_HEAP_USAGE Usage
);
typedef struct _RTL_HEAP_WALK_ENTRY
{
PVOID DataAddress;
SIZE_T DataSize;
UCHAR OverheadBytes;
UCHAR SegmentIndex;
USHORT Flags;
union
{
struct
{
SIZE_T Settable;
USHORT TagIndex;
USHORT AllocatorBackTraceIndex;
ULONG Reserved[2];
} Block;
struct
{
ULONG CommittedSize;
ULONG UnCommittedSize;
PVOID FirstEntry;
PVOID LastEntry;
} Segment;
};
} RTL_HEAP_WALK_ENTRY, *PRTL_HEAP_WALK_ENTRY;
NTSYSAPI
NTSTATUS
NTAPI
RtlWalkHeap(
_In_ PVOID HeapHandle,
_Inout_ PRTL_HEAP_WALK_ENTRY Entry
);
// HEAP_INFORMATION_CLASS
#define HeapCompatibilityInformation 0x0 // q; s: ULONG
#define HeapEnableTerminationOnCorruption 0x1 // q; s: NULL
#define HeapExtendedInformation 0x2 // q; s: HEAP_EXTENDED_INFORMATION
#define HeapOptimizeResources 0x3 // q; s: HEAP_OPTIMIZE_RESOURCES_INFORMATION
#define HeapTaggingInformation 0x4
#define HeapStackDatabase 0x5
#define HeapDetailedFailureInformation 0x80000001
#define HeapSetDebuggingInformation 0x80000002 // q; s: HEAP_DEBUGGING_INFORMATION
typedef enum _HEAP_COMPATIBILITY_MODE
{
HEAP_COMPATIBILITY_STANDARD = 0UL,
HEAP_COMPATIBILITY_LAL = 1UL,
HEAP_COMPATIBILITY_LFH = 2UL,
} HEAP_COMPATIBILITY_MODE;
typedef struct _PROCESS_HEAP_INFORMATION
{
ULONG_PTR ReserveSize;
ULONG_PTR CommitSize;
ULONG NumberOfHeaps;
ULONG_PTR FirstHeapInformationOffset;
} PROCESS_HEAP_INFORMATION, *PPROCESS_HEAP_INFORMATION;
typedef struct _HEAP_INFORMATION
{
ULONG_PTR Address;
ULONG Mode;
ULONG_PTR ReserveSize;
ULONG_PTR CommitSize;
ULONG_PTR FirstRegionInformationOffset;
ULONG_PTR NextHeapInformationOffset;
} HEAP_INFORMATION, *PHEAP_INFORMATION;
typedef struct _HEAP_EXTENDED_INFORMATION
{
HANDLE Process;
ULONG_PTR Heap;
ULONG Level;
PVOID CallbackRoutine;
PVOID CallbackContext;
union
{
PROCESS_HEAP_INFORMATION ProcessHeapInformation;
HEAP_INFORMATION HeapInformation;
};
} HEAP_EXTENDED_INFORMATION, *PHEAP_EXTENDED_INFORMATION;
// rev
typedef NTSTATUS (NTAPI *PRTL_HEAP_LEAK_ENUMERATION_ROUTINE)(
_In_ LONG Reserved,
_In_ PVOID HeapHandle,
_In_ PVOID BaseAddress,
_In_ SIZE_T BlockSize,
_In_ ULONG StackTraceDepth,
_In_ PVOID *StackTrace
);
// symbols
typedef struct _HEAP_DEBUGGING_INFORMATION
{
PVOID InterceptorFunction;
USHORT InterceptorValue;
ULONG ExtendedOptions;
ULONG StackTraceDepth;
SIZE_T MinTotalBlockSize;
SIZE_T MaxTotalBlockSize;
PRTL_HEAP_LEAK_ENUMERATION_ROUTINE HeapLeakEnumerationRoutine;
} HEAP_DEBUGGING_INFORMATION, *PHEAP_DEBUGGING_INFORMATION;
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryHeapInformation(
_In_ PVOID HeapHandle,
_In_ HEAP_INFORMATION_CLASS HeapInformationClass,
_Out_opt_ PVOID HeapInformation,
_In_opt_ SIZE_T HeapInformationLength,
_Out_opt_ PSIZE_T ReturnLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetHeapInformation(
_In_ PVOID HeapHandle,
_In_ HEAP_INFORMATION_CLASS HeapInformationClass,
_In_opt_ PVOID HeapInformation,
_In_opt_ SIZE_T HeapInformationLength
);
NTSYSAPI
ULONG
NTAPI
RtlMultipleAllocateHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ SIZE_T Size,
_In_ ULONG Count,
_Out_ PVOID *Array
);
NTSYSAPI
ULONG
NTAPI
RtlMultipleFreeHeap(
_In_ PVOID HeapHandle,
_In_ ULONG Flags,
_In_ ULONG Count,
_In_ PVOID *Array
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSAPI
VOID
NTAPI
RtlDetectHeapLeaks(
VOID
);
#endif
NTSYSAPI
VOID
NTAPI
RtlFlushHeaps(
VOID
);
// Memory zones
// begin_private
typedef struct _RTL_MEMORY_ZONE_SEGMENT
{
struct _RTL_MEMORY_ZONE_SEGMENT *NextSegment;
SIZE_T Size;
PVOID Next;
PVOID Limit;
} RTL_MEMORY_ZONE_SEGMENT, *PRTL_MEMORY_ZONE_SEGMENT;
typedef struct _RTL_MEMORY_ZONE
{
RTL_MEMORY_ZONE_SEGMENT Segment;
RTL_SRWLOCK Lock;
ULONG LockCount;
PRTL_MEMORY_ZONE_SEGMENT FirstSegment;
} RTL_MEMORY_ZONE, *PRTL_MEMORY_ZONE;
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateMemoryZone(
_Out_ PVOID *MemoryZone,
_In_ SIZE_T InitialSize,
_Reserved_ ULONG Flags
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyMemoryZone(
_In_ _Post_invalid_ PVOID MemoryZone
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAllocateMemoryZone(
_In_ PVOID MemoryZone,
_In_ SIZE_T BlockSize,
_Out_ PVOID *Block
);
NTSYSAPI
NTSTATUS
NTAPI
RtlResetMemoryZone(
_In_ PVOID MemoryZone
);
NTSYSAPI
NTSTATUS
NTAPI
RtlLockMemoryZone(
_In_ PVOID MemoryZone
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnlockMemoryZone(
_In_ PVOID MemoryZone
);
#endif
// end_private
// Memory block lookaside lists
// begin_private
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateMemoryBlockLookaside(
_Out_ PVOID *MemoryBlockLookaside,
_Reserved_ ULONG Flags,
_In_ ULONG InitialSize,
_In_ ULONG MinimumBlockSize,
_In_ ULONG MaximumBlockSize
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAllocateMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside,
_In_ ULONG BlockSize,
_Out_ PVOID *Block
);
NTSYSAPI
NTSTATUS
NTAPI
RtlFreeMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside,
_In_ PVOID Block
);
NTSYSAPI
NTSTATUS
NTAPI
RtlExtendMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside,
_In_ ULONG Increment
);
NTSYSAPI
NTSTATUS
NTAPI
RtlResetMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside
);
NTSYSAPI
NTSTATUS
NTAPI
RtlLockMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUnlockMemoryBlockLookaside(
_In_ PVOID MemoryBlockLookaside
);
#endif
// end_private
// Transactions
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
HANDLE
NTAPI
RtlGetCurrentTransaction(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
LOGICAL
NTAPI
RtlSetCurrentTransaction(
_In_ HANDLE TransactionHandle
);
#endif
// LUIDs
FORCEINLINE BOOLEAN RtlIsEqualLuid( // RtlEqualLuid
_In_ PLUID L1,
_In_ PLUID L2
)
{
return L1->LowPart == L2->LowPart &&
L1->HighPart == L2->HighPart;
}
FORCEINLINE BOOLEAN RtlIsZeroLuid(
_In_ PLUID L1
)
{
return (L1->LowPart | L1->HighPart) == 0;
}
FORCEINLINE LUID RtlConvertLongToLuid(
_In_ LONG Long
)
{
LUID tempLuid;
LARGE_INTEGER tempLi;
tempLi.QuadPart = Long;
tempLuid.LowPart = tempLi.LowPart;
tempLuid.HighPart = tempLi.HighPart;
return tempLuid;
}
FORCEINLINE LUID RtlConvertUlongToLuid(
_In_ ULONG Ulong
)
{
LUID tempLuid;
tempLuid.LowPart = Ulong;
tempLuid.HighPart = 0;
return tempLuid;
}
NTSYSAPI
VOID
NTAPI
RtlCopyLuid(
_Out_ PLUID DestinationLuid,
_In_ PLUID SourceLuid
);
// ros
NTSYSAPI
VOID
NTAPI
RtlCopyLuidAndAttributesArray(
_In_ ULONG Count,
_In_ PLUID_AND_ATTRIBUTES Src,
_In_ PLUID_AND_ATTRIBUTES Dest
);
// Byte swap routines.
NTSYSAPI
USHORT
FASTCALL
RtlUshortByteSwap(
_In_ USHORT Source
);
NTSYSAPI
ULONG
FASTCALL
RtlUlongByteSwap(
_In_ ULONG Source
);
NTSYSAPI
ULONGLONG
FASTCALL
RtlUlonglongByteSwap(
_In_ ULONGLONG Source
);
// Debugging
// private
typedef struct _RTL_PROCESS_VERIFIER_OPTIONS
{
ULONG SizeStruct;
ULONG Option;
UCHAR OptionData[1];
} RTL_PROCESS_VERIFIER_OPTIONS, *PRTL_PROCESS_VERIFIER_OPTIONS;
// private
typedef struct _RTL_DEBUG_INFORMATION
{
HANDLE SectionHandleClient;
PVOID ViewBaseClient;
PVOID ViewBaseTarget;
ULONG_PTR ViewBaseDelta;
HANDLE EventPairClient;
HANDLE EventPairTarget;
HANDLE TargetProcessId;
HANDLE TargetThreadHandle;
ULONG Flags;
SIZE_T OffsetFree;
SIZE_T CommitSize;
SIZE_T ViewSize;
union
{
struct _RTL_PROCESS_MODULES *Modules;
struct _RTL_PROCESS_MODULE_INFORMATION_EX *ModulesEx;
};
struct _RTL_PROCESS_BACKTRACES *BackTraces;
struct _RTL_PROCESS_HEAPS *Heaps;
struct _RTL_PROCESS_LOCKS *Locks;
PVOID SpecificHeap;
HANDLE TargetProcessHandle;
PRTL_PROCESS_VERIFIER_OPTIONS VerifierOptions;
PVOID ProcessHeap;
HANDLE CriticalSectionHandle;
HANDLE CriticalSectionOwnerThread;
PVOID Reserved[4];
} RTL_DEBUG_INFORMATION, *PRTL_DEBUG_INFORMATION;
NTSYSAPI
PRTL_DEBUG_INFORMATION
NTAPI
RtlCreateQueryDebugBuffer(
_In_opt_ ULONG MaximumCommit,
_In_ BOOLEAN UseEventPair
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyQueryDebugBuffer(
_In_ PRTL_DEBUG_INFORMATION Buffer
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
PVOID
NTAPI
RtlCommitDebugInfo(
_Inout_ PRTL_DEBUG_INFORMATION Buffer,
_In_ SIZE_T Size
);
// private
NTSYSAPI
VOID
NTAPI
RtlDeCommitDebugInfo(
_Inout_ PRTL_DEBUG_INFORMATION Buffer,
_In_ PVOID p,
_In_ SIZE_T Size
);
#endif
#define RTL_QUERY_PROCESS_MODULES 0x00000001
#define RTL_QUERY_PROCESS_BACKTRACES 0x00000002
#define RTL_QUERY_PROCESS_HEAP_SUMMARY 0x00000004
#define RTL_QUERY_PROCESS_HEAP_TAGS 0x00000008
#define RTL_QUERY_PROCESS_HEAP_ENTRIES 0x00000010
#define RTL_QUERY_PROCESS_LOCKS 0x00000020
#define RTL_QUERY_PROCESS_MODULES32 0x00000040
#define RTL_QUERY_PROCESS_VERIFIER_OPTIONS 0x00000080 // rev
#define RTL_QUERY_PROCESS_MODULESEX 0x00000100 // rev
#define RTL_QUERY_PROCESS_HEAP_ENTRIES_EX 0x00000200 // ?
#define RTL_QUERY_PROCESS_CS_OWNER 0x00000400 // rev
#define RTL_QUERY_PROCESS_NONINVASIVE 0x80000000
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryProcessDebugInformation(
_In_ HANDLE UniqueProcessId,
_In_ ULONG Flags,
_Inout_ PRTL_DEBUG_INFORMATION Buffer
);
// Messages
NTSYSAPI
NTSTATUS
NTAPI
RtlFindMessage(
_In_ PVOID DllHandle,
_In_ ULONG MessageTableId,
_In_ ULONG MessageLanguageId,
_In_ ULONG MessageId,
_Out_ PMESSAGE_RESOURCE_ENTRY *MessageEntry
);
NTSYSAPI
NTSTATUS
NTAPI
RtlFormatMessage(
_In_ PWSTR MessageFormat,
_In_ ULONG MaximumWidth,
_In_ BOOLEAN IgnoreInserts,
_In_ BOOLEAN ArgumentsAreAnsi,
_In_ BOOLEAN ArgumentsAreAnArray,
_In_ va_list *Arguments,
_Out_writes_bytes_to_(Length, *ReturnLength) PWSTR Buffer,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength
);
typedef struct _PARSE_MESSAGE_CONTEXT
{
ULONG fFlags;
ULONG cwSavColumn;
SIZE_T iwSrc;
SIZE_T iwDst;
SIZE_T iwDstSpace;
va_list lpvArgStart;
} PARSE_MESSAGE_CONTEXT, *PPARSE_MESSAGE_CONTEXT;
#define INIT_PARSE_MESSAGE_CONTEXT(ctx) { (ctx)->fFlags = 0; }
#define TEST_PARSE_MESSAGE_CONTEXT_FLAG(ctx, flag) ((ctx)->fFlags & (flag))
#define SET_PARSE_MESSAGE_CONTEXT_FLAG(ctx, flag) ((ctx)->fFlags |= (flag))
#define CLEAR_PARSE_MESSAGE_CONTEXT_FLAG(ctx, flag) ((ctx)->fFlags &= ~(flag))
NTSYSAPI
NTSTATUS
NTAPI
RtlFormatMessageEx(
_In_ PWSTR MessageFormat,
_In_ ULONG MaximumWidth,
_In_ BOOLEAN IgnoreInserts,
_In_ BOOLEAN ArgumentsAreAnsi,
_In_ BOOLEAN ArgumentsAreAnArray,
_In_ va_list *Arguments,
_Out_writes_bytes_to_(Length, *ReturnLength) PWSTR Buffer,
_In_ ULONG Length,
_Out_opt_ PULONG ReturnLength,
_Out_opt_ PPARSE_MESSAGE_CONTEXT ParseContext
);
// Errors
NTSYSAPI
ULONG
NTAPI
RtlNtStatusToDosError(
_In_ NTSTATUS Status
);
NTSYSAPI
ULONG
NTAPI
RtlNtStatusToDosErrorNoTeb(
_In_ NTSTATUS Status
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetLastNtStatus(
VOID
);
NTSYSAPI
LONG
NTAPI
RtlGetLastWin32Error(
VOID
);
NTSYSAPI
VOID
NTAPI
RtlSetLastWin32ErrorAndNtStatusFromNtStatus(
_In_ NTSTATUS Status
);
NTSYSAPI
VOID
NTAPI
RtlSetLastWin32Error(
_In_ LONG Win32Error
);
NTSYSAPI
VOID
NTAPI
RtlRestoreLastWin32Error(
_In_ LONG Win32Error
);
#define RTL_ERRORMODE_FAILCRITICALERRORS 0x0010
#define RTL_ERRORMODE_NOGPFAULTERRORBOX 0x0020
#define RTL_ERRORMODE_NOOPENFILEERRORBOX 0x0040
NTSYSAPI
ULONG
NTAPI
RtlGetThreadErrorMode(
VOID
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetThreadErrorMode(
_In_ ULONG NewMode,
_Out_opt_ PULONG OldMode
);
// Windows Error Reporting
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlReportException(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord,
_In_ ULONG Flags
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlReportExceptionEx(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord,
_In_ ULONG Flags,
_In_ PLARGE_INTEGER Timeout
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlWerpReportException(
_In_ ULONG ProcessId,
_In_ HANDLE CrashReportSharedMem,
_In_ ULONG Flags,
_Out_ PHANDLE CrashVerticalProcessHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlReportSilentProcessExit(
_In_ HANDLE ProcessHandle,
_In_ NTSTATUS ExitStatus
);
#endif
// Vectored Exception Handlers
NTSYSAPI
PVOID
NTAPI
RtlAddVectoredExceptionHandler(
_In_ ULONG First,
_In_ PVECTORED_EXCEPTION_HANDLER Handler
);
NTSYSAPI
ULONG
NTAPI
RtlRemoveVectoredExceptionHandler(
_In_ PVOID Handle
);
NTSYSAPI
PVOID
NTAPI
RtlAddVectoredContinueHandler(
_In_ ULONG First,
_In_ PVECTORED_EXCEPTION_HANDLER Handler
);
NTSYSAPI
ULONG
NTAPI
RtlRemoveVectoredContinueHandler(
_In_ PVOID Handle
);
// Random
NTSYSAPI
ULONG
NTAPI
RtlUniform(
_Inout_ PULONG Seed
);
NTSYSAPI
ULONG
NTAPI
RtlRandom(
_Inout_ PULONG Seed
);
NTSYSAPI
ULONG
NTAPI
RtlRandomEx(
_Inout_ PULONG Seed
);
NTSYSAPI
NTSTATUS
NTAPI
RtlComputeImportTableHash(
_In_ HANDLE FileHandle,
_Out_writes_bytes_(16) PCHAR Hash,
_In_ ULONG ImportTableHashRevision // must be 1
);
// Integer conversion
NTSYSAPI
NTSTATUS
NTAPI
RtlIntegerToChar(
_In_ ULONG Value,
_In_opt_ ULONG Base,
_In_ LONG OutputLength, // negative to pad to width
_Out_ PSTR String
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCharToInteger(
_In_ PSTR String,
_In_opt_ ULONG Base,
_Out_ PULONG Value
);
NTSYSAPI
NTSTATUS
NTAPI
RtlLargeIntegerToChar(
_In_ PLARGE_INTEGER Value,
_In_opt_ ULONG Base,
_In_ LONG OutputLength,
_Out_ PSTR String
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIntegerToUnicodeString(
_In_ ULONG Value,
_In_opt_ ULONG Base,
_Inout_ PUNICODE_STRING String
);
NTSYSAPI
NTSTATUS
NTAPI
RtlInt64ToUnicodeString(
_In_ ULONGLONG Value,
_In_opt_ ULONG Base,
_Inout_ PUNICODE_STRING String
);
#ifdef _WIN64
#define RtlIntPtrToUnicodeString(Value, Base, String) RtlInt64ToUnicodeString(Value, Base, String)
#else
#define RtlIntPtrToUnicodeString(Value, Base, String) RtlIntegerToUnicodeString(Value, Base, String)
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlUnicodeStringToInteger(
_In_ PUNICODE_STRING String,
_In_opt_ ULONG Base,
_Out_ PULONG Value
);
// IPv4/6 conversion
struct in_addr;
struct in6_addr;
NTSYSAPI
PWSTR
NTAPI
RtlIpv4AddressToStringW(
_In_ const struct in_addr *Address,
_Out_writes_(16) PWSTR AddressString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIpv4AddressToStringExW(
_In_ const struct in_addr *Address,
_In_ USHORT Port,
_Out_writes_to_(*AddressStringLength, *AddressStringLength) PWSTR AddressString,
_Inout_ PULONG AddressStringLength
);
NTSYSAPI
PWSTR
NTAPI
RtlIpv6AddressToStringW(
_In_ const struct in6_addr *Address,
_Out_writes_(46) PWSTR AddressString
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIpv6AddressToStringExW(
_In_ const struct in6_addr *Address,
_In_ ULONG ScopeId,
_In_ USHORT Port,
_Out_writes_to_(*AddressStringLength, *AddressStringLength) PWSTR AddressString,
_Inout_ PULONG AddressStringLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIpv4StringToAddressW(
_In_ PCWSTR AddressString,
_In_ BOOLEAN Strict,
_Out_ LPCWSTR *Terminator,
_Out_ struct in_addr *Address
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIpv4StringToAddressExW(
_In_ PCWSTR AddressString,
_In_ BOOLEAN Strict,
_Out_ struct in_addr *Address,
_Out_ PUSHORT Port
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIpv6StringToAddressW(
_In_ PCWSTR AddressString,
_Out_ PCWSTR *Terminator,
_Out_ struct in6_addr *Address
);
NTSYSAPI
NTSTATUS
NTAPI
RtlIpv6StringToAddressExW(
_In_ PCWSTR AddressString,
_Out_ struct in6_addr *Address,
_Out_ PULONG ScopeId,
_Out_ PUSHORT Port
);
#define RtlIpv4AddressToString RtlIpv4AddressToStringW
#define RtlIpv4AddressToStringEx RtlIpv4AddressToStringExW
#define RtlIpv6AddressToString RtlIpv6AddressToStringW
#define RtlIpv6AddressToStringEx RtlIpv6AddressToStringExW
#define RtlIpv4StringToAddress RtlIpv4StringToAddressW
#define RtlIpv4StringToAddressEx RtlIpv4StringToAddressExW
#define RtlIpv6StringToAddress RtlIpv6StringToAddressW
#define RtlIpv6StringToAddressEx RtlIpv6StringToAddressExW
// Time
typedef struct _TIME_FIELDS
{
CSHORT Year; // 1601...
CSHORT Month; // 1..12
CSHORT Day; // 1..31
CSHORT Hour; // 0..23
CSHORT Minute; // 0..59
CSHORT Second; // 0..59
CSHORT Milliseconds; // 0..999
CSHORT Weekday; // 0..6 = Sunday..Saturday
} TIME_FIELDS, *PTIME_FIELDS;
NTSYSAPI
BOOLEAN
NTAPI
RtlCutoverTimeToSystemTime(
_In_ PTIME_FIELDS CutoverTime,
_Out_ PLARGE_INTEGER SystemTime,
_In_ PLARGE_INTEGER CurrentSystemTime,
_In_ BOOLEAN ThisYear
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSystemTimeToLocalTime(
_In_ PLARGE_INTEGER SystemTime,
_Out_ PLARGE_INTEGER LocalTime
);
NTSYSAPI
NTSTATUS
NTAPI
RtlLocalTimeToSystemTime(
_In_ PLARGE_INTEGER LocalTime,
_Out_ PLARGE_INTEGER SystemTime
);
NTSYSAPI
VOID
NTAPI
RtlTimeToElapsedTimeFields(
_In_ PLARGE_INTEGER Time,
_Out_ PTIME_FIELDS TimeFields
);
NTSYSAPI
VOID
NTAPI
RtlTimeToTimeFields(
_In_ PLARGE_INTEGER Time,
_Out_ PTIME_FIELDS TimeFields
);
NTSYSAPI
BOOLEAN
NTAPI
RtlTimeFieldsToTime(
_In_ PTIME_FIELDS TimeFields, // Weekday is ignored
_Out_ PLARGE_INTEGER Time
);
NTSYSAPI
BOOLEAN
NTAPI
RtlTimeToSecondsSince1980(
_In_ PLARGE_INTEGER Time,
_Out_ PULONG ElapsedSeconds
);
NTSYSAPI
VOID
NTAPI
RtlSecondsSince1980ToTime(
_In_ ULONG ElapsedSeconds,
_Out_ PLARGE_INTEGER Time
);
NTSYSAPI
BOOLEAN
NTAPI
RtlTimeToSecondsSince1970(
_In_ PLARGE_INTEGER Time,
_Out_ PULONG ElapsedSeconds
);
NTSYSAPI
VOID
NTAPI
RtlSecondsSince1970ToTime(
_In_ ULONG ElapsedSeconds,
_Out_ PLARGE_INTEGER Time
);
// Time zones
typedef struct _RTL_TIME_ZONE_INFORMATION
{
LONG Bias;
WCHAR StandardName[32];
TIME_FIELDS StandardStart;
LONG StandardBias;
WCHAR DaylightName[32];
TIME_FIELDS DaylightStart;
LONG DaylightBias;
} RTL_TIME_ZONE_INFORMATION, *PRTL_TIME_ZONE_INFORMATION;
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryTimeZoneInformation(
_Out_ PRTL_TIME_ZONE_INFORMATION TimeZoneInformation
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetTimeZoneInformation(
_In_ PRTL_TIME_ZONE_INFORMATION TimeZoneInformation
);
// Bitmaps
typedef struct _RTL_BITMAP
{
ULONG SizeOfBitMap;
PULONG Buffer;
} RTL_BITMAP, *PRTL_BITMAP;
NTSYSAPI
VOID
NTAPI
RtlInitializeBitMap(
_Out_ PRTL_BITMAP BitMapHeader,
_In_ PULONG BitMapBuffer,
_In_ ULONG SizeOfBitMap
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlTestBit(
_In_ PRTL_BITMAP BitMapHeader,
_In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitNumber
);
NTSYSAPI
VOID
NTAPI
RtlClearAllBits(
_In_ PRTL_BITMAP BitMapHeader
);
NTSYSAPI
VOID
NTAPI
RtlSetAllBits(
_In_ PRTL_BITMAP BitMapHeader
);
_Success_(return != -1)
_Check_return_
NTSYSAPI
ULONG
NTAPI
RtlFindClearBits(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG NumberToFind,
_In_ ULONG HintIndex
);
_Success_(return != -1)
_Check_return_
NTSYSAPI
ULONG
NTAPI
RtlFindSetBits(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG NumberToFind,
_In_ ULONG HintIndex
);
_Success_(return != -1)
NTSYSAPI
ULONG
NTAPI
RtlFindClearBitsAndSet(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG NumberToFind,
_In_ ULONG HintIndex
);
_Success_(return != -1)
NTSYSAPI
ULONG
NTAPI
RtlFindSetBitsAndClear(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG NumberToFind,
_In_ ULONG HintIndex
);
NTSYSAPI
VOID
NTAPI
RtlClearBits(
_In_ PRTL_BITMAP BitMapHeader,
_In_range_(0, BitMapHeader->SizeOfBitMap - NumberToClear) ULONG StartingIndex,
_In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToClear
);
NTSYSAPI
VOID
NTAPI
RtlSetBits(
_In_ PRTL_BITMAP BitMapHeader,
_In_range_(0, BitMapHeader->SizeOfBitMap - NumberToSet) ULONG StartingIndex,
_In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToSet
);
NTSYSAPI
CCHAR
NTAPI
RtlFindMostSignificantBit(
_In_ ULONGLONG Set
);
NTSYSAPI
CCHAR
NTAPI
RtlFindLeastSignificantBit(
_In_ ULONGLONG Set
);
typedef struct _RTL_BITMAP_RUN
{
ULONG StartingIndex;
ULONG NumberOfBits;
} RTL_BITMAP_RUN, *PRTL_BITMAP_RUN;
NTSYSAPI
ULONG
NTAPI
RtlFindClearRuns(
_In_ PRTL_BITMAP BitMapHeader,
_Out_writes_to_(SizeOfRunArray, return) PRTL_BITMAP_RUN RunArray,
_In_range_(>, 0) ULONG SizeOfRunArray,
_In_ BOOLEAN LocateLongestRuns
);
NTSYSAPI
ULONG
NTAPI
RtlFindLongestRunClear(
_In_ PRTL_BITMAP BitMapHeader,
_Out_ PULONG StartingIndex
);
NTSYSAPI
ULONG
NTAPI
RtlFindFirstRunClear(
_In_ PRTL_BITMAP BitMapHeader,
_Out_ PULONG StartingIndex
);
_Check_return_
FORCEINLINE
BOOLEAN
RtlCheckBit(
_In_ PRTL_BITMAP BitMapHeader,
_In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitPosition
)
{
#ifdef _WIN64
return BitTest64((LONG64 const *)BitMapHeader->Buffer, (LONG64)BitPosition);
#else
return (((PLONG)BitMapHeader->Buffer)[BitPosition / 32] >> (BitPosition % 32)) & 0x1;
#endif
}
NTSYSAPI
ULONG
NTAPI
RtlNumberOfClearBits(
_In_ PRTL_BITMAP BitMapHeader
);
NTSYSAPI
ULONG
NTAPI
RtlNumberOfSetBits(
_In_ PRTL_BITMAP BitMapHeader
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlAreBitsClear(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG StartingIndex,
_In_ ULONG Length
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlAreBitsSet(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG StartingIndex,
_In_ ULONG Length
);
NTSYSAPI
ULONG
NTAPI
RtlFindNextForwardRunClear(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG FromIndex,
_Out_ PULONG StartingRunIndex
);
NTSYSAPI
ULONG
NTAPI
RtlFindLastBackwardRunClear(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG FromIndex,
_Out_ PULONG StartingRunIndex
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
ULONG
NTAPI
RtlNumberOfSetBitsUlongPtr(
_In_ ULONG_PTR Target
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
VOID
NTAPI
RtlInterlockedClearBitRun(
_In_ PRTL_BITMAP BitMapHeader,
_In_range_(0, BitMapHeader->SizeOfBitMap - NumberToClear) ULONG StartingIndex,
_In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToClear
);
// rev
NTSYSAPI
VOID
NTAPI
RtlInterlockedSetBitRun(
_In_ PRTL_BITMAP BitMapHeader,
_In_range_(0, BitMapHeader->SizeOfBitMap - NumberToSet) ULONG StartingIndex,
_In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToSet
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSAPI
VOID
NTAPI
RtlCopyBitMap(
_In_ PRTL_BITMAP Source,
_In_ PRTL_BITMAP Destination,
_In_range_(0, Destination->SizeOfBitMap - 1) ULONG TargetBit
);
NTSYSAPI
VOID
NTAPI
RtlExtractBitMap(
_In_ PRTL_BITMAP Source,
_In_ PRTL_BITMAP Destination,
_In_range_(0, Source->SizeOfBitMap - 1) ULONG TargetBit,
_In_range_(0, Source->SizeOfBitMap) ULONG NumberOfBits
);
NTSYSAPI
ULONG
NTAPI
RtlNumberOfClearBitsInRange(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG StartingIndex,
_In_ ULONG Length
);
NTSYSAPI
ULONG
NTAPI
RtlNumberOfSetBitsInRange(
_In_ PRTL_BITMAP BitMapHeader,
_In_ ULONG StartingIndex,
_In_ ULONG Length
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10)
// private
typedef struct _RTL_BITMAP_EX
{
ULONG64 SizeOfBitMap;
PULONG64 Buffer;
} RTL_BITMAP_EX, *PRTL_BITMAP_EX;
// rev
NTSYSAPI
VOID
NTAPI
RtlInitializeBitMapEx(
_Out_ PRTL_BITMAP_EX BitMapHeader,
_In_ PULONG64 BitMapBuffer,
_In_ ULONG64 SizeOfBitMap
);
// rev
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlTestBitEx(
_In_ PRTL_BITMAP_EX BitMapHeader,
_In_range_(<, BitMapHeader->SizeOfBitMap) ULONG64 BitNumber
);
#endif
// Handle tables
typedef struct _RTL_HANDLE_TABLE_ENTRY
{
union
{
ULONG Flags; // allocated entries have the low bit set
struct _RTL_HANDLE_TABLE_ENTRY *NextFree;
};
} RTL_HANDLE_TABLE_ENTRY, *PRTL_HANDLE_TABLE_ENTRY;
#define RTL_HANDLE_ALLOCATED (USHORT)0x0001
typedef struct _RTL_HANDLE_TABLE
{
ULONG MaximumNumberOfHandles;
ULONG SizeOfHandleTableEntry;
ULONG Reserved[2];
PRTL_HANDLE_TABLE_ENTRY FreeHandles;
PRTL_HANDLE_TABLE_ENTRY CommittedHandles;
PRTL_HANDLE_TABLE_ENTRY UnCommittedHandles;
PRTL_HANDLE_TABLE_ENTRY MaxReservedHandles;
} RTL_HANDLE_TABLE, *PRTL_HANDLE_TABLE;
NTSYSAPI
VOID
NTAPI
RtlInitializeHandleTable(
_In_ ULONG MaximumNumberOfHandles,
_In_ ULONG SizeOfHandleTableEntry,
_Out_ PRTL_HANDLE_TABLE HandleTable
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyHandleTable(
_Inout_ PRTL_HANDLE_TABLE HandleTable
);
NTSYSAPI
PRTL_HANDLE_TABLE_ENTRY
NTAPI
RtlAllocateHandle(
_In_ PRTL_HANDLE_TABLE HandleTable,
_Out_opt_ PULONG HandleIndex
);
NTSYSAPI
BOOLEAN
NTAPI
RtlFreeHandle(
_In_ PRTL_HANDLE_TABLE HandleTable,
_In_ PRTL_HANDLE_TABLE_ENTRY Handle
);
NTSYSAPI
BOOLEAN
NTAPI
RtlIsValidHandle(
_In_ PRTL_HANDLE_TABLE HandleTable,
_In_ PRTL_HANDLE_TABLE_ENTRY Handle
);
NTSYSAPI
BOOLEAN
NTAPI
RtlIsValidIndexHandle(
_In_ PRTL_HANDLE_TABLE HandleTable,
_In_ ULONG HandleIndex,
_Out_ PRTL_HANDLE_TABLE_ENTRY *Handle
);
// Atom tables
#define RTL_ATOM_MAXIMUM_INTEGER_ATOM (RTL_ATOM)0xc000
#define RTL_ATOM_INVALID_ATOM (RTL_ATOM)0x0000
#define RTL_ATOM_TABLE_DEFAULT_NUMBER_OF_BUCKETS 37
#define RTL_ATOM_MAXIMUM_NAME_LENGTH 255
#define RTL_ATOM_PINNED 0x01
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateAtomTable(
_In_ ULONG NumberOfBuckets,
_Out_ PVOID *AtomTableHandle
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDestroyAtomTable(
_In_ _Post_invalid_ PVOID AtomTableHandle
);
NTSYSAPI
NTSTATUS
NTAPI
RtlEmptyAtomTable(
_In_ PVOID AtomTableHandle,
_In_ BOOLEAN IncludePinnedAtoms
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAtomToAtomTable(
_In_ PVOID AtomTableHandle,
_In_ PWSTR AtomName,
_Inout_opt_ PRTL_ATOM Atom
);
NTSYSAPI
NTSTATUS
NTAPI
RtlLookupAtomInAtomTable(
_In_ PVOID AtomTableHandle,
_In_ PWSTR AtomName,
_Out_opt_ PRTL_ATOM Atom
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteAtomFromAtomTable(
_In_ PVOID AtomTableHandle,
_In_ RTL_ATOM Atom
);
NTSYSAPI
NTSTATUS
NTAPI
RtlPinAtomInAtomTable(
_In_ PVOID AtomTableHandle,
_In_ RTL_ATOM Atom
);
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryAtomInAtomTable(
_In_ PVOID AtomTableHandle,
_In_ RTL_ATOM Atom,
_Out_opt_ PULONG AtomUsage,
_Out_opt_ PULONG AtomFlags,
_Inout_updates_bytes_to_opt_(*AtomNameLength, *AtomNameLength) PWSTR AtomName,
_Inout_opt_ PULONG AtomNameLength
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlGetIntegerAtom(
_In_ PWSTR AtomName,
_Out_opt_ PUSHORT IntegerAtom
);
#endif
// SIDs
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlValidSid(
_In_ PSID Sid
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlEqualSid(
_In_ PSID Sid1,
_In_ PSID Sid2
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlEqualPrefixSid(
_In_ PSID Sid1,
_In_ PSID Sid2
);
NTSYSAPI
ULONG
NTAPI
RtlLengthRequiredSid(
_In_ ULONG SubAuthorityCount
);
NTSYSAPI
PVOID
NTAPI
RtlFreeSid(
_In_ _Post_invalid_ PSID Sid
);
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
RtlAllocateAndInitializeSid(
_In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
_In_ UCHAR SubAuthorityCount,
_In_ ULONG SubAuthority0,
_In_ ULONG SubAuthority1,
_In_ ULONG SubAuthority2,
_In_ ULONG SubAuthority3,
_In_ ULONG SubAuthority4,
_In_ ULONG SubAuthority5,
_In_ ULONG SubAuthority6,
_In_ ULONG SubAuthority7,
_Outptr_ PSID *Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlInitializeSid(
_Out_ PSID Sid,
_In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
_In_ UCHAR SubAuthorityCount
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSAPI
NTSTATUS
NTAPI
RtlInitializeSidEx(
_Out_writes_bytes_(SECURITY_SID_SIZE(SubAuthorityCount)) PSID Sid,
_In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
_In_ UCHAR SubAuthorityCount,
...
);
#endif
NTSYSAPI
PSID_IDENTIFIER_AUTHORITY
NTAPI
RtlIdentifierAuthoritySid(
_In_ PSID Sid
);
NTSYSAPI
PULONG
NTAPI
RtlSubAuthoritySid(
_In_ PSID Sid,
_In_ ULONG SubAuthority
);
NTSYSAPI
PUCHAR
NTAPI
RtlSubAuthorityCountSid(
_In_ PSID Sid
);
NTSYSAPI
ULONG
NTAPI
RtlLengthSid(
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCopySid(
_In_ ULONG DestinationSidLength,
_In_reads_bytes_(DestinationSidLength) PSID DestinationSid,
_In_ PSID SourceSid
);
// ros
NTSYSAPI
NTSTATUS
NTAPI
RtlCopySidAndAttributesArray(
_In_ ULONG Count,
_In_ PSID_AND_ATTRIBUTES Src,
_In_ ULONG SidAreaSize,
_In_ PSID_AND_ATTRIBUTES Dest,
_In_ PSID SidArea,
_Out_ PSID *RemainingSidArea,
_Out_ PULONG RemainingSidAreaSize
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateServiceSid(
_In_ PUNICODE_STRING ServiceName,
_Out_writes_bytes_opt_(*ServiceSidLength) PSID ServiceSid,
_Inout_ PULONG ServiceSidLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSidDominates(
_In_ PSID Sid1,
_In_ PSID Sid2,
_Out_ PBOOLEAN Dominates
);
#endif
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlSidDominatesForTrust(
_In_ PSID Sid1,
_In_ PSID Sid2,
_Out_ PBOOLEAN DominatesTrust // TokenProcessTrustLevel
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSidEqualLevel(
_In_ PSID Sid1,
_In_ PSID Sid2,
_Out_ PBOOLEAN EqualLevel
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSidIsHigherLevel(
_In_ PSID Sid1,
_In_ PSID Sid2,
_Out_ PBOOLEAN HigherLevel
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateVirtualAccountSid(
_In_ PUNICODE_STRING Name,
_In_ ULONG BaseSubAuthority,
_Out_writes_bytes_(*SidLength) PSID Sid,
_Inout_ PULONG SidLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSAPI
NTSTATUS
NTAPI
RtlReplaceSidInSd(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ PSID OldSid,
_In_ PSID NewSid,
_Out_ ULONG *NumChanges
);
#endif
#define MAX_UNICODE_STACK_BUFFER_LENGTH 256
NTSYSAPI
NTSTATUS
NTAPI
RtlConvertSidToUnicodeString(
_Inout_ PUNICODE_STRING UnicodeString,
_In_ PSID Sid,
_In_ BOOLEAN AllocateDestinationString
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSidHashInitialize(
_In_reads_(SidCount) PSID_AND_ATTRIBUTES SidAttr,
_In_ ULONG SidCount,
_Out_ PSID_AND_ATTRIBUTES_HASH SidAttrHash
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
PSID_AND_ATTRIBUTES
NTAPI
RtlSidHashLookup(
_In_ PSID_AND_ATTRIBUTES_HASH SidAttrHash,
_In_ PSID Sid
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsElevatedRid(
_In_ PSID_AND_ATTRIBUTES SidAttr
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS2)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlDeriveCapabilitySidsFromName(
_Inout_ PUNICODE_STRING UnicodeString,
_Out_ PSID CapabilityGroupSid,
_Out_ PSID CapabilitySid
);
#endif
// Security Descriptors
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateSecurityDescriptor(
_Out_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ ULONG Revision
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlValidSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
NTSYSAPI
ULONG
NTAPI
RtlLengthSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
_Check_return_
NTSYSAPI
BOOLEAN
NTAPI
RtlValidRelativeSecurityDescriptor(
_In_reads_bytes_(SecurityDescriptorLength) PSECURITY_DESCRIPTOR SecurityDescriptorInput,
_In_ ULONG SecurityDescriptorLength,
_In_ SECURITY_INFORMATION RequiredInformation
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetControlSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PSECURITY_DESCRIPTOR_CONTROL Control,
_Out_ PULONG Revision
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetControlSecurityDescriptor(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,
_In_ SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetAttributesSecurityDescriptor(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ SECURITY_DESCRIPTOR_CONTROL Control,
_Out_ PULONG Revision
);
NTSYSAPI
BOOLEAN
NTAPI
RtlGetSecurityDescriptorRMControl(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PUCHAR RMControl
);
NTSYSAPI
VOID
NTAPI
RtlSetSecurityDescriptorRMControl(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PUCHAR RMControl
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetDaclSecurityDescriptor(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ BOOLEAN DaclPresent,
_In_opt_ PACL Dacl,
_In_opt_ BOOLEAN DaclDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetDaclSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PBOOLEAN DaclPresent,
_Out_ PACL *Dacl,
_Out_ PBOOLEAN DaclDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetSaclSecurityDescriptor(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ BOOLEAN SaclPresent,
_In_opt_ PACL Sacl,
_In_opt_ BOOLEAN SaclDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetSaclSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PBOOLEAN SaclPresent,
_Out_ PACL *Sacl,
_Out_ PBOOLEAN SaclDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetSaclSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PBOOLEAN SaclPresent,
_Out_ PACL *Sacl,
_Out_ PBOOLEAN SaclDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetOwnerSecurityDescriptor(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID Owner,
_In_opt_ BOOLEAN OwnerDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetOwnerSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PSID *Owner,
_Out_ PBOOLEAN OwnerDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetGroupSecurityDescriptor(
_Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID Group,
_In_opt_ BOOLEAN GroupDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetGroupSecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_Out_ PSID *Group,
_Out_ PBOOLEAN GroupDefaulted
);
NTSYSAPI
NTSTATUS
NTAPI
RtlMakeSelfRelativeSD(
_In_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor,
_Out_writes_bytes_(*BufferLength) PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
_Inout_ PULONG BufferLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAbsoluteToSelfRelativeSD(
_In_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor,
_Out_writes_bytes_to_opt_(*BufferLength, *BufferLength) PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
_Inout_ PULONG BufferLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSelfRelativeToAbsoluteSD(
_In_ PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
_Out_writes_bytes_to_opt_(*AbsoluteSecurityDescriptorSize, *AbsoluteSecurityDescriptorSize) PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor,
_Inout_ PULONG AbsoluteSecurityDescriptorSize,
_Out_writes_bytes_to_opt_(*DaclSize, *DaclSize) PACL Dacl,
_Inout_ PULONG DaclSize,
_Out_writes_bytes_to_opt_(*SaclSize, *SaclSize) PACL Sacl,
_Inout_ PULONG SaclSize,
_Out_writes_bytes_to_opt_(*OwnerSize, *OwnerSize) PSID Owner,
_Inout_ PULONG OwnerSize,
_Out_writes_bytes_to_opt_(*PrimaryGroupSize, *PrimaryGroupSize) PSID PrimaryGroup,
_Inout_ PULONG PrimaryGroupSize
);
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlSelfRelativeToAbsoluteSD2(
_Inout_ PSECURITY_DESCRIPTOR pSelfRelativeSecurityDescriptor,
_Inout_ PULONG pBufferSize
);
// Access masks
NTSYSAPI
BOOLEAN
NTAPI
RtlAreAllAccessesGranted(
_In_ ACCESS_MASK GrantedAccess,
_In_ ACCESS_MASK DesiredAccess
);
NTSYSAPI
BOOLEAN
NTAPI
RtlAreAnyAccessesGranted(
_In_ ACCESS_MASK GrantedAccess,
_In_ ACCESS_MASK DesiredAccess
);
NTSYSAPI
VOID
NTAPI
RtlMapGenericMask(
_Inout_ PACCESS_MASK AccessMask,
_In_ PGENERIC_MAPPING GenericMapping
);
// ACLs
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateAcl(
_Out_writes_bytes_(AclLength) PACL Acl,
_In_ ULONG AclLength,
_In_ ULONG AclRevision
);
NTSYSAPI
BOOLEAN
NTAPI
RtlValidAcl(
_In_ PACL Acl
);
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryInformationAcl(
_In_ PACL Acl,
_Out_writes_bytes_(AclInformationLength) PVOID AclInformation,
_In_ ULONG AclInformationLength,
_In_ ACL_INFORMATION_CLASS AclInformationClass
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetInformationAcl(
_Inout_ PACL Acl,
_In_reads_bytes_(AclInformationLength) PVOID AclInformation,
_In_ ULONG AclInformationLength,
_In_ ACL_INFORMATION_CLASS AclInformationClass
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG StartingAceIndex,
_In_reads_bytes_(AceListLength) PVOID AceList,
_In_ ULONG AceListLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteAce(
_Inout_ PACL Acl,
_In_ ULONG AceIndex
);
NTSYSAPI
NTSTATUS
NTAPI
RtlGetAce(
_In_ PACL Acl,
_In_ ULONG AceIndex,
_Outptr_ PVOID *Ace
);
NTSYSAPI
BOOLEAN
NTAPI
RtlFirstFreeAce(
_In_ PACL Acl,
_Out_ PVOID *FirstFree
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
PVOID
NTAPI
RtlFindAceByType(
_In_ PACL pAcl,
_In_ UCHAR AceType,
_Out_opt_ PULONG pIndex
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
BOOLEAN
NTAPI
RtlOwnerAcesPresent(
_In_ PACL pAcl
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAccessAllowedAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ACCESS_MASK AccessMask,
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAccessAllowedAceEx(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ ACCESS_MASK AccessMask,
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAccessDeniedAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ACCESS_MASK AccessMask,
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAccessDeniedAceEx(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ ACCESS_MASK AccessMask,
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAuditAccessAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ACCESS_MASK AccessMask,
_In_ PSID Sid,
_In_ BOOLEAN AuditSuccess,
_In_ BOOLEAN AuditFailure
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAuditAccessAceEx(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ ACCESS_MASK AccessMask,
_In_ PSID Sid,
_In_ BOOLEAN AuditSuccess,
_In_ BOOLEAN AuditFailure
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAccessAllowedObjectAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ ACCESS_MASK AccessMask,
_In_opt_ PGUID ObjectTypeGuid,
_In_opt_ PGUID InheritedObjectTypeGuid,
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAccessDeniedObjectAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ ACCESS_MASK AccessMask,
_In_opt_ PGUID ObjectTypeGuid,
_In_opt_ PGUID InheritedObjectTypeGuid,
_In_ PSID Sid
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddAuditAccessObjectAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ ACCESS_MASK AccessMask,
_In_opt_ PGUID ObjectTypeGuid,
_In_opt_ PGUID InheritedObjectTypeGuid,
_In_ PSID Sid,
_In_ BOOLEAN AuditSuccess,
_In_ BOOLEAN AuditFailure
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddCompoundAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ UCHAR AceType,
_In_ ACCESS_MASK AccessMask,
_In_ PSID ServerSid,
_In_ PSID ClientSid
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlAddMandatoryAce(
_Inout_ PACL Acl,
_In_ ULONG AceRevision,
_In_ ULONG AceFlags,
_In_ PSID Sid,
_In_ UCHAR AceType,
_In_ ACCESS_MASK AccessMask
);
#endif
// Named pipes
NTSYSAPI
NTSTATUS
NTAPI
RtlDefaultNpAcl(
_Out_ PACL *Acl
);
// Security objects
NTSYSAPI
NTSTATUS
NTAPI
RtlNewSecurityObject(
_In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
_In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
_Out_ PSECURITY_DESCRIPTOR *NewDescriptor,
_In_ BOOLEAN IsDirectoryObject,
_In_opt_ HANDLE Token,
_In_ PGENERIC_MAPPING GenericMapping
);
NTSYSAPI
NTSTATUS
NTAPI
RtlNewSecurityObjectEx(
_In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
_In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
_Out_ PSECURITY_DESCRIPTOR *NewDescriptor,
_In_opt_ GUID *ObjectType,
_In_ BOOLEAN IsDirectoryObject,
_In_ ULONG AutoInheritFlags, // SEF_*
_In_opt_ HANDLE Token,
_In_ PGENERIC_MAPPING GenericMapping
);
NTSYSAPI
NTSTATUS
NTAPI
RtlNewSecurityObjectWithMultipleInheritance(
_In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
_In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
_Out_ PSECURITY_DESCRIPTOR *NewDescriptor,
_In_opt_ GUID **ObjectType,
_In_ ULONG GuidCount,
_In_ BOOLEAN IsDirectoryObject,
_In_ ULONG AutoInheritFlags, // SEF_*
_In_opt_ HANDLE Token,
_In_ PGENERIC_MAPPING GenericMapping
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteSecurityObject(
_Inout_ PSECURITY_DESCRIPTOR *ObjectDescriptor
);
NTSYSAPI
NTSTATUS
NTAPI
RtlQuerySecurityObject(
_In_ PSECURITY_DESCRIPTOR ObjectDescriptor,
_In_ SECURITY_INFORMATION SecurityInformation,
_Out_opt_ PSECURITY_DESCRIPTOR ResultantDescriptor,
_In_ ULONG DescriptorLength,
_Out_ PULONG ReturnLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetSecurityObject(
_In_ SECURITY_INFORMATION SecurityInformation,
_In_ PSECURITY_DESCRIPTOR ModificationDescriptor,
_Inout_ PSECURITY_DESCRIPTOR *ObjectsSecurityDescriptor,
_In_ PGENERIC_MAPPING GenericMapping,
_In_opt_ HANDLE Token
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetSecurityObjectEx(
_In_ SECURITY_INFORMATION SecurityInformation,
_In_ PSECURITY_DESCRIPTOR ModificationDescriptor,
_Inout_ PSECURITY_DESCRIPTOR *ObjectsSecurityDescriptor,
_In_ ULONG AutoInheritFlags, // SEF_*
_In_ PGENERIC_MAPPING GenericMapping,
_In_opt_ HANDLE Token
);
NTSYSAPI
NTSTATUS
NTAPI
RtlConvertToAutoInheritSecurityObject(
_In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
_In_ PSECURITY_DESCRIPTOR CurrentSecurityDescriptor,
_Out_ PSECURITY_DESCRIPTOR *NewSecurityDescriptor,
_In_opt_ GUID *ObjectType,
_In_ BOOLEAN IsDirectoryObject,
_In_ PGENERIC_MAPPING GenericMapping
);
NTSYSAPI
NTSTATUS
NTAPI
RtlNewInstanceSecurityObject(
_In_ BOOLEAN ParentDescriptorChanged,
_In_ BOOLEAN CreatorDescriptorChanged,
_In_ PLUID OldClientTokenModifiedId,
_Out_ PLUID NewClientTokenModifiedId,
_In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
_In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
_Out_ PSECURITY_DESCRIPTOR *NewDescriptor,
_In_ BOOLEAN IsDirectoryObject,
_In_ HANDLE Token,
_In_ PGENERIC_MAPPING GenericMapping
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCopySecurityDescriptor(
_In_ PSECURITY_DESCRIPTOR InputSecurityDescriptor,
_Out_ PSECURITY_DESCRIPTOR *OutputSecurityDescriptor
);
// Misc. security
NTSYSAPI
VOID
NTAPI
RtlRunEncodeUnicodeString(
_Inout_ PUCHAR Seed,
_In_ PUNICODE_STRING String
);
NTSYSAPI
VOID
NTAPI
RtlRunDecodeUnicodeString(
_In_ UCHAR Seed,
_In_ PUNICODE_STRING String
);
NTSYSAPI
NTSTATUS
NTAPI
RtlImpersonateSelf(
_In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlImpersonateSelfEx(
_In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
_In_opt_ ACCESS_MASK AdditionalAccess,
_Out_opt_ PHANDLE ThreadToken
);
#endif
NTSYSAPI
NTSTATUS
NTAPI
RtlAdjustPrivilege(
_In_ ULONG Privilege,
_In_ BOOLEAN Enable,
_In_ BOOLEAN Client,
_Out_ PBOOLEAN WasEnabled
);
#define RTL_ACQUIRE_PRIVILEGE_REVERT 0x00000001
#define RTL_ACQUIRE_PRIVILEGE_PROCESS 0x00000002
NTSYSAPI
NTSTATUS
NTAPI
RtlAcquirePrivilege(
_In_ PULONG Privilege,
_In_ ULONG NumPriv,
_In_ ULONG Flags,
_Out_ PVOID *ReturnedState
);
NTSYSAPI
VOID
NTAPI
RtlReleasePrivilege(
_In_ PVOID StatePointer
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlRemovePrivileges(
_In_ HANDLE TokenHandle,
_In_ PULONG PrivilegesToKeep,
_In_ ULONG PrivilegeCount
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN8)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlIsUntrustedObject(
_In_opt_ HANDLE Handle,
_In_opt_ PVOID Object,
_Out_ PBOOLEAN IsUntrustedObject
);
NTSYSAPI
ULONG
NTAPI
RtlQueryValidationRunlevel(
_In_opt_ PUNICODE_STRING ComponentName
);
#endif
// Private namespaces
#if (NTDDI_VERSION >= NTDDI_VISTA)
// begin_private
NTSYSAPI
PVOID
NTAPI
RtlCreateBoundaryDescriptor(
_In_ PUNICODE_STRING Name,
_In_ ULONG Flags
);
NTSYSAPI
VOID
NTAPI
RtlDeleteBoundaryDescriptor(
_In_ PVOID BoundaryDescriptor
);
NTSYSAPI
NTSTATUS
NTAPI
RtlAddSIDToBoundaryDescriptor(
_Inout_ PVOID *BoundaryDescriptor,
_In_ PSID RequiredSid
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlAddIntegrityLabelToBoundaryDescriptor(
_Inout_ PVOID *BoundaryDescriptor,
_In_ PSID IntegrityLabel
);
#endif
// end_private
#endif
// Version
NTSYSAPI
NTSTATUS
NTAPI
RtlGetVersion(
_Out_ PRTL_OSVERSIONINFOW lpVersionInformation
);
NTSYSAPI
NTSTATUS
NTAPI
RtlVerifyVersionInfo(
_In_ PRTL_OSVERSIONINFOEXW VersionInfo,
_In_ ULONG TypeMask,
_In_ ULONGLONG ConditionMask
);
// rev
NTSYSAPI
VOID
NTAPI
RtlGetNtVersionNumbers(
_Out_opt_ PULONG NtMajorVersion,
_Out_opt_ PULONG NtMinorVersion,
_Out_opt_ PULONG NtBuildNumber
);
// System information
// rev
NTSYSAPI
ULONG
NTAPI
RtlGetNtGlobalFlags(
VOID
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlGetNtProductType(
_Out_ PNT_PRODUCT_TYPE NtProductType
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS2)
// private
NTSYSAPI
ULONG
NTAPI
RtlGetSuiteMask(
VOID
);
#endif
// Thread pool (old)
NTSYSAPI
NTSTATUS
NTAPI
RtlRegisterWait(
_Out_ PHANDLE WaitHandle,
_In_ HANDLE Handle,
_In_ WAITORTIMERCALLBACKFUNC Function,
_In_ PVOID Context,
_In_ ULONG Milliseconds,
_In_ ULONG Flags
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeregisterWait(
_In_ HANDLE WaitHandle
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeregisterWaitEx(
_In_ HANDLE WaitHandle,
_In_ HANDLE Event
);
NTSYSAPI
NTSTATUS
NTAPI
RtlQueueWorkItem(
_In_ WORKERCALLBACKFUNC Function,
_In_ PVOID Context,
_In_ ULONG Flags
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetIoCompletionCallback(
_In_ HANDLE FileHandle,
_In_ APC_CALLBACK_FUNCTION CompletionProc,
_In_ ULONG Flags
);
typedef NTSTATUS (NTAPI *PRTL_START_POOL_THREAD)(
_In_ PTHREAD_START_ROUTINE Function,
_In_ PVOID Parameter,
_Out_ PHANDLE ThreadHandle
);
typedef NTSTATUS (NTAPI *PRTL_EXIT_POOL_THREAD)(
_In_ NTSTATUS ExitStatus
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSetThreadPoolStartFunc(
_In_ PRTL_START_POOL_THREAD StartPoolThread,
_In_ PRTL_EXIT_POOL_THREAD ExitPoolThread
);
NTSYSAPI
VOID
NTAPI
RtlUserThreadStart(
_In_ PTHREAD_START_ROUTINE Function,
_In_ PVOID Parameter
);
NTSYSAPI
VOID
NTAPI
LdrInitializeThunk(
_In_ PCONTEXT ContextRecord,
_In_ PVOID Parameter
);
// Timer support
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateTimerQueue(
_Out_ PHANDLE TimerQueueHandle
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateTimer(
_In_ HANDLE TimerQueueHandle,
_Out_ PHANDLE Handle,
_In_ WAITORTIMERCALLBACKFUNC Function,
_In_opt_ PVOID Context,
_In_ ULONG DueTime,
_In_ ULONG Period,
_In_ ULONG Flags
);
NTSYSAPI
NTSTATUS
NTAPI
RtlUpdateTimer(
_In_ HANDLE TimerQueueHandle,
_In_ HANDLE TimerHandle,
_In_ ULONG DueTime,
_In_ ULONG Period
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteTimer(
_In_ HANDLE TimerQueueHandle,
_In_ HANDLE TimerToCancel,
_In_ HANDLE Event
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteTimerQueue(
_In_ HANDLE TimerQueueHandle
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteTimerQueueEx(
_In_ HANDLE TimerQueueHandle,
_In_ HANDLE Event
);
// Registry access
NTSYSAPI
NTSTATUS
NTAPI
RtlFormatCurrentUserKeyPath(
_Out_ PUNICODE_STRING CurrentUserKeyPath
);
NTSYSAPI
NTSTATUS
NTAPI
RtlOpenCurrentUser(
_In_ ACCESS_MASK DesiredAccess,
_Out_ PHANDLE CurrentUserKey
);
#define RTL_REGISTRY_ABSOLUTE 0
#define RTL_REGISTRY_SERVICES 1 // \Registry\Machine\System\CurrentControlSet\Services
#define RTL_REGISTRY_CONTROL 2 // \Registry\Machine\System\CurrentControlSet\Control
#define RTL_REGISTRY_WINDOWS_NT 3 // \Registry\Machine\Software\Microsoft\Windows NT\CurrentVersion
#define RTL_REGISTRY_DEVICEMAP 4 // \Registry\Machine\Hardware\DeviceMap
#define RTL_REGISTRY_USER 5 // \Registry\User\CurrentUser
#define RTL_REGISTRY_MAXIMUM 6
#define RTL_REGISTRY_HANDLE 0x40000000
#define RTL_REGISTRY_OPTIONAL 0x80000000
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateRegistryKey(
_In_ ULONG RelativeTo,
_In_ PWSTR Path
);
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckRegistryKey(
_In_ ULONG RelativeTo,
_In_ PWSTR Path
);
typedef NTSTATUS (NTAPI *PRTL_QUERY_REGISTRY_ROUTINE)(
_In_ PWSTR ValueName,
_In_ ULONG ValueType,
_In_ PVOID ValueData,
_In_ ULONG ValueLength,
_In_ PVOID Context,
_In_ PVOID EntryContext
);
typedef struct _RTL_QUERY_REGISTRY_TABLE
{
PRTL_QUERY_REGISTRY_ROUTINE QueryRoutine;
ULONG Flags;
PWSTR Name;
PVOID EntryContext;
ULONG DefaultType;
PVOID DefaultData;
ULONG DefaultLength;
} RTL_QUERY_REGISTRY_TABLE, *PRTL_QUERY_REGISTRY_TABLE;
#define RTL_QUERY_REGISTRY_SUBKEY 0x00000001
#define RTL_QUERY_REGISTRY_TOPKEY 0x00000002
#define RTL_QUERY_REGISTRY_REQUIRED 0x00000004
#define RTL_QUERY_REGISTRY_NOVALUE 0x00000008
#define RTL_QUERY_REGISTRY_NOEXPAND 0x00000010
#define RTL_QUERY_REGISTRY_DIRECT 0x00000020
#define RTL_QUERY_REGISTRY_DELETE 0x00000040
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryRegistryValues(
_In_ ULONG RelativeTo,
_In_ PWSTR Path,
_In_ PRTL_QUERY_REGISTRY_TABLE QueryTable,
_In_ PVOID Context,
_In_opt_ PVOID Environment
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryRegistryValuesEx(
_In_ ULONG RelativeTo,
_In_ PWSTR Path,
_In_ PRTL_QUERY_REGISTRY_TABLE QueryTable,
_In_ PVOID Context,
_In_opt_ PVOID Environment
);
NTSYSAPI
NTSTATUS
NTAPI
RtlWriteRegistryValue(
_In_ ULONG RelativeTo,
_In_ PWSTR Path,
_In_ PWSTR ValueName,
_In_ ULONG ValueType,
_In_ PVOID ValueData,
_In_ ULONG ValueLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeleteRegistryValue(
_In_ ULONG RelativeTo,
_In_ PWSTR Path,
_In_ PWSTR ValueName
);
// Thread profiling
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlEnableThreadProfiling(
_In_ HANDLE ThreadHandle,
_In_ ULONG Flags,
_In_ ULONG64 HardwareCounters,
_Out_ PVOID *PerformanceDataHandle
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlDisableThreadProfiling(
_In_ PVOID PerformanceDataHandle
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryThreadProfiling(
_In_ HANDLE ThreadHandle,
_Out_ PBOOLEAN Enabled
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlReadThreadProfilingData(
_In_ HANDLE PerformanceDataHandle,
_In_ ULONG Flags,
_Out_ PPERFORMANCE_DATA PerformanceData
);
#endif
// WOW64
NTSYSAPI
NTSTATUS
NTAPI
RtlGetNativeSystemInformation(
_In_ ULONG SystemInformationClass,
_In_ PVOID NativeSystemInformation,
_In_ ULONG InformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSAPI
NTSTATUS
NTAPI
RtlQueueApcWow64Thread(
_In_ HANDLE ThreadHandle,
_In_ PPS_APC_ROUTINE ApcRoutine,
_In_opt_ PVOID ApcArgument1,
_In_opt_ PVOID ApcArgument2,
_In_opt_ PVOID ApcArgument3
);
NTSYSAPI
NTSTATUS
NTAPI
RtlWow64EnableFsRedirection(
_In_ BOOLEAN Wow64FsEnableRedirection
);
NTSYSAPI
NTSTATUS
NTAPI
RtlWow64EnableFsRedirectionEx(
_In_ PVOID Wow64FsEnableRedirection,
_Out_ PVOID *OldFsRedirectionLevel
);
// Misc.
NTSYSAPI
ULONG32
NTAPI
RtlComputeCrc32(
_In_ ULONG32 PartialCrc,
_In_ PVOID Buffer,
_In_ ULONG Length
);
NTSYSAPI
PVOID
NTAPI
RtlEncodePointer(
_In_ PVOID Ptr
);
NTSYSAPI
PVOID
NTAPI
RtlDecodePointer(
_In_ PVOID Ptr
);
NTSYSAPI
PVOID
NTAPI
RtlEncodeSystemPointer(
_In_ PVOID Ptr
);
NTSYSAPI
PVOID
NTAPI
RtlDecodeSystemPointer(
_In_ PVOID Ptr
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlEncodeRemotePointer(
_In_ HANDLE ProcessHandle,
_In_ PVOID Pointer,
_Out_ PVOID *EncodedPointer
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlDecodeRemotePointer(
_In_ HANDLE ProcessHandle,
_In_ PVOID Pointer,
_Out_ PVOID *DecodedPointer
);
#endif
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsProcessorFeaturePresent(
_In_ ULONG ProcessorFeature
);
// rev
NTSYSAPI
ULONG
NTAPI
RtlGetCurrentProcessorNumber(
VOID
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
// rev
NTSYSAPI
VOID
NTAPI
RtlGetCurrentProcessorNumberEx(
_Out_ PPROCESSOR_NUMBER ProcessorNumber
);
#endif
// Stack support
NTSYSAPI
VOID
NTAPI
RtlPushFrame(
_In_ PTEB_ACTIVE_FRAME Frame
);
NTSYSAPI
VOID
NTAPI
RtlPopFrame(
_In_ PTEB_ACTIVE_FRAME Frame
);
NTSYSAPI
PTEB_ACTIVE_FRAME
NTAPI
RtlGetFrame(
VOID
);
#define RTL_WALK_USER_MODE_STACK 0x00000001
#define RTL_WALK_VALID_FLAGS 0x00000001
#define RTL_STACK_WALKING_MODE_FRAMES_TO_SKIP_SHIFT 0x00000008
// private
NTSYSAPI
ULONG
NTAPI
RtlWalkFrameChain(
_Out_writes_(Count - (Flags >> RTL_STACK_WALKING_MODE_FRAMES_TO_SKIP_SHIFT)) PVOID *Callers,
_In_ ULONG Count,
_In_ ULONG Flags
);
// rev
NTSYSAPI
VOID
NTAPI
RtlGetCallersAddress( // Use the intrinsic _ReturnAddress instead.
_Out_ PVOID *CallersAddress,
_Out_ PVOID *CallersCaller
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
NTSYSAPI
ULONG64
NTAPI
RtlGetEnabledExtendedFeatures(
_In_ ULONG64 FeatureMask
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS4)
// msdn
NTSYSAPI
ULONG64
NTAPI
RtlGetEnabledExtendedAndSupervisorFeatures(
_In_ ULONG64 FeatureMask
);
// msdn
_Ret_maybenull_
_Success_(return != NULL)
NTSYSAPI
PVOID
NTAPI
RtlLocateSupervisorFeature(
_In_ PXSAVE_AREA_HEADER XStateHeader,
_In_range_(XSTATE_AVX, MAXIMUM_XSTATE_FEATURES - 1) ULONG FeatureId,
_Out_opt_ PULONG Length
);
#endif
// private
typedef union _RTL_ELEVATION_FLAGS
{
ULONG Flags;
struct
{
ULONG ElevationEnabled : 1;
ULONG VirtualizationEnabled : 1;
ULONG InstallerDetectEnabled : 1;
ULONG ReservedBits : 29;
};
} RTL_ELEVATION_FLAGS, *PRTL_ELEVATION_FLAGS;
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryElevationFlags(
_Out_ PRTL_ELEVATION_FLAGS Flags
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlRegisterThreadWithCsrss(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlLockCurrentThread(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlUnlockCurrentThread(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlLockModuleSection(
_In_ PVOID Address
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlUnlockModuleSection(
_In_ PVOID Address
);
#endif
// begin_msdn:"Winternl"
#define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
// private
typedef struct _RTL_UNLOAD_EVENT_TRACE
{
PVOID BaseAddress;
SIZE_T SizeOfImage;
ULONG Sequence;
ULONG TimeDateStamp;
ULONG CheckSum;
WCHAR ImageName[32];
ULONG Version[2];
} RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
typedef struct _RTL_UNLOAD_EVENT_TRACE32
{
ULONG BaseAddress;
ULONG SizeOfImage;
ULONG Sequence;
ULONG TimeDateStamp;
ULONG CheckSum;
WCHAR ImageName[32];
ULONG Version[2];
} RTL_UNLOAD_EVENT_TRACE32, *PRTL_UNLOAD_EVENT_TRACE32;
NTSYSAPI
PRTL_UNLOAD_EVENT_TRACE
NTAPI
RtlGetUnloadEventTrace(
VOID
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
VOID
NTAPI
RtlGetUnloadEventTraceEx(
_Out_ PULONG *ElementSize,
_Out_ PULONG *ElementCount,
_Out_ PVOID *EventTrace // works across all processes
);
#endif
// end_msdn
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
LOGICAL
NTAPI
RtlQueryPerformanceCounter(
_Out_ PLARGE_INTEGER PerformanceCounter
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
LOGICAL
NTAPI
RtlQueryPerformanceFrequency(
_Out_ PLARGE_INTEGER PerformanceFrequency
);
#endif
// Image Mitigation
// rev
typedef enum _IMAGE_MITIGATION_POLICY
{
ImageDepPolicy, // RTL_IMAGE_MITIGATION_DEP_POLICY
ImageAslrPolicy, // RTL_IMAGE_MITIGATION_ASLR_POLICY
ImageDynamicCodePolicy, // RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY
ImageStrictHandleCheckPolicy, // RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY
ImageSystemCallDisablePolicy, // RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY
ImageMitigationOptionsMask,
ImageExtensionPointDisablePolicy, // RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY
ImageControlFlowGuardPolicy, // RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY
ImageSignaturePolicy, // RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY
ImageFontDisablePolicy, // RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY
ImageImageLoadPolicy, // RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY
ImagePayloadRestrictionPolicy, // RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY
ImageChildProcessPolicy, // RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY
ImageSehopPolicy, // RTL_IMAGE_MITIGATION_SEHOP_POLICY
ImageHeapPolicy, // RTL_IMAGE_MITIGATION_HEAP_POLICY
MaxImageMitigationPolicy
} IMAGE_MITIGATION_POLICY;
// rev
typedef union _RTL_IMAGE_MITIGATION_POLICY
{
struct
{
ULONG64 AuditState : 2;
ULONG64 AuditFlag : 1;
ULONG64 EnableAdditionalAuditingOption : 1;
ULONG64 Reserved : 60;
};
struct
{
ULONG64 PolicyState : 2;
ULONG64 AlwaysInherit : 1;
ULONG64 EnableAdditionalPolicyOption : 1;
ULONG64 AuditReserved : 60;
};
} RTL_IMAGE_MITIGATION_POLICY, *PRTL_IMAGE_MITIGATION_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_DEP_POLICY
{
RTL_IMAGE_MITIGATION_POLICY Dep;
} RTL_IMAGE_MITIGATION_DEP_POLICY, *PRTL_IMAGE_MITIGATION_DEP_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_ASLR_POLICY
{
RTL_IMAGE_MITIGATION_POLICY ForceRelocateImages;
RTL_IMAGE_MITIGATION_POLICY BottomUpRandomization;
RTL_IMAGE_MITIGATION_POLICY HighEntropyRandomization;
} RTL_IMAGE_MITIGATION_ASLR_POLICY, *PRTL_IMAGE_MITIGATION_ASLR_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY
{
RTL_IMAGE_MITIGATION_POLICY BlockDynamicCode;
} RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY, *PRTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY
{
RTL_IMAGE_MITIGATION_POLICY StrictHandleChecks;
} RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY, *PRTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY
{
RTL_IMAGE_MITIGATION_POLICY BlockWin32kSystemCalls;
} RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY, *PRTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY
{
RTL_IMAGE_MITIGATION_POLICY DisableExtensionPoints;
} RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY, *PRTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY
{
RTL_IMAGE_MITIGATION_POLICY ControlFlowGuard;
RTL_IMAGE_MITIGATION_POLICY StrictControlFlowGuard;
} RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY, *PRTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY
{
RTL_IMAGE_MITIGATION_POLICY BlockNonMicrosoftSignedBinaries;
RTL_IMAGE_MITIGATION_POLICY EnforceSigningOnModuleDependencies;
} RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY, *PRTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY
{
RTL_IMAGE_MITIGATION_POLICY DisableNonSystemFonts;
} RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY, *PRTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY
{
RTL_IMAGE_MITIGATION_POLICY BlockRemoteImageLoads;
RTL_IMAGE_MITIGATION_POLICY BlockLowLabelImageLoads;
RTL_IMAGE_MITIGATION_POLICY PreferSystem32;
} RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY, *PRTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY
{
RTL_IMAGE_MITIGATION_POLICY EnableExportAddressFilter;
RTL_IMAGE_MITIGATION_POLICY EnableExportAddressFilterPlus;
RTL_IMAGE_MITIGATION_POLICY EnableImportAddressFilter;
RTL_IMAGE_MITIGATION_POLICY EnableRopStackPivot;
RTL_IMAGE_MITIGATION_POLICY EnableRopCallerCheck;
RTL_IMAGE_MITIGATION_POLICY EnableRopSimExec;
WCHAR EafPlusModuleList[512]; // 19H1
} RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY, *PRTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY
{
RTL_IMAGE_MITIGATION_POLICY DisallowChildProcessCreation;
} RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY, *PRTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_SEHOP_POLICY
{
RTL_IMAGE_MITIGATION_POLICY Sehop;
} RTL_IMAGE_MITIGATION_SEHOP_POLICY, *PRTL_IMAGE_MITIGATION_SEHOP_POLICY;
// rev
typedef struct _RTL_IMAGE_MITIGATION_HEAP_POLICY
{
RTL_IMAGE_MITIGATION_POLICY TerminateOnHeapErrors;
} RTL_IMAGE_MITIGATION_HEAP_POLICY, *PRTL_IMAGE_MITIGATION_HEAP_POLICY;
typedef enum _RTL_IMAGE_MITIGATION_OPTION_STATE
{
RtlMitigationOptionStateNotConfigured,
RtlMitigationOptionStateOn,
RtlMitigationOptionStateOff
} RTL_IMAGE_MITIGATION_OPTION_STATE;
// rev from PROCESS_MITIGATION_FLAGS
#define RTL_IMAGE_MITIGATION_FLAG_RESET 0x1
#define RTL_IMAGE_MITIGATION_FLAG_REMOVE 0x2
#define RTL_IMAGE_MITIGATION_FLAG_OSDEFAULT 0x4
#define RTL_IMAGE_MITIGATION_FLAG_AUDIT 0x8
#if (NTDDI_VERSION >= NTDDI_WIN10_RS3)
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryImageMitigationPolicy(
_In_opt_ PWSTR ImagePath, // NULL for system-wide defaults
_In_ IMAGE_MITIGATION_POLICY Policy,
_In_ ULONG Flags,
_Inout_ PVOID Buffer,
_In_ ULONG BufferSize
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlSetImageMitigationPolicy(
_In_opt_ PWSTR ImagePath, // NULL for system-wide defaults
_In_ IMAGE_MITIGATION_POLICY Policy,
_In_ ULONG Flags,
_Inout_ PVOID Buffer,
_In_ ULONG BufferSize
);
#endif
// session
// rev
NTSYSAPI
ULONG
NTAPI
RtlGetCurrentServiceSessionId(
VOID
);
// private
NTSYSAPI
ULONG
NTAPI
RtlGetActiveConsoleId(
VOID
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
// private
NTSYSAPI
ULONGLONG
NTAPI
RtlGetConsoleSessionForegroundProcessId(
VOID
);
#endif
// Appcontainer
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGetTokenNamedObjectPath(
_In_ HANDLE Token,
_In_opt_ PSID Sid,
_Out_ PUNICODE_STRING ObjectPath // RtlFreeUnicodeString
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGetAppContainerNamedObjectPath(
_In_opt_ HANDLE Token,
_In_opt_ PSID AppContainerSid,
_In_ BOOLEAN RelativePath,
_Out_ PUNICODE_STRING ObjectPath // RtlFreeUnicodeString
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGetAppContainerParent(
_In_ PSID AppContainerSid,
_Out_ PSID* AppContainerSidParent // RtlFreeSid
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckSandboxedToken(
_In_opt_ HANDLE TokenHandle,
_Out_ PBOOLEAN IsSandboxed
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckTokenCapability(
_In_opt_ HANDLE TokenHandle,
_In_ PSID CapabilitySidToCheck,
_Out_ PBOOLEAN HasCapability
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCapabilityCheck(
_In_opt_ HANDLE TokenHandle,
_In_ PUNICODE_STRING CapabilityName,
_Out_ PBOOLEAN HasCapability
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckTokenMembership(
_In_opt_ HANDLE TokenHandle,
_In_ PSID SidToCheck,
_Out_ PBOOLEAN IsMember
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckTokenMembershipEx(
_In_opt_ HANDLE TokenHandle,
_In_ PSID SidToCheck,
_In_ ULONG Flags, // CTMF_VALID_FLAGS
_Out_ PBOOLEAN IsMember
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryTokenHostIdAsUlong64(
_In_ HANDLE TokenHandle,
_Out_ PULONG64 HostId // (WIN://PKGHOSTID)
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlIsParentOfChildAppContainer(
_In_ PSID ParentAppContainerSid,
_In_ PSID ChildAppContainerSid
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsCapabilitySid(
_In_ PSID Sid
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsPackageSid(
_In_ PSID Sid
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsValidProcessTrustLabelSid(
_In_ PSID Sid
);
NTSYSAPI
BOOLEAN
NTAPI
RtlIsStateSeparationEnabled(
VOID
);
typedef enum _APPCONTAINER_SID_TYPE
{
NotAppContainerSidType,
ChildAppContainerSidType,
ParentAppContainerSidType,
InvalidAppContainerSidType,
MaxAppContainerSidType
} APPCONTAINER_SID_TYPE, *PAPPCONTAINER_SID_TYPE;
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlGetAppContainerSidType(
_In_ PSID AppContainerSid,
_Out_ PAPPCONTAINER_SID_TYPE AppContainerSidType
);
NTSYSAPI
NTSTATUS
NTAPI
RtlFlsAlloc(
_In_ PFLS_CALLBACK_FUNCTION Callback,
_Out_ PULONG FlsIndex
);
NTSYSAPI
NTSTATUS
NTAPI
RtlFlsFree(
_In_ ULONG FlsIndex
);
typedef enum _STATE_LOCATION_TYPE
{
LocationTypeRegistry,
LocationTypeFileSystem,
LocationTypeMaximum
} STATE_LOCATION_TYPE;
// private
NTSYSAPI
NTSTATUS
NTAPI
RtlGetPersistedStateLocation(
_In_ PCWSTR SourceID,
_In_opt_ PCWSTR CustomValue,
_In_opt_ PCWSTR DefaultPath,
_In_ STATE_LOCATION_TYPE StateLocationType,
_Out_writes_bytes_to_opt_(BufferLengthIn, *BufferLengthOut) PWCHAR TargetPath,
_In_ ULONG BufferLengthIn,
_Out_opt_ PULONG BufferLengthOut
);
// msdn
NTSYSAPI
BOOLEAN
NTAPI
RtlIsCloudFilesPlaceholder(
_In_ ULONG FileAttributes,
_In_ ULONG ReparseTag
);
// msdn
NTSYSAPI
BOOLEAN
NTAPI
RtlIsPartialPlaceholder(
_In_ ULONG FileAttributes,
_In_ ULONG ReparseTag
);
// msdn
NTSYSAPI
NTSTATUS
NTAPI
RtlIsPartialPlaceholderFileHandle(
_In_ HANDLE FileHandle,
_Out_ PBOOLEAN IsPartialPlaceholder
);
// msdn
NTSYSAPI
NTSTATUS
NTAPI
RtlIsPartialPlaceholderFileInfo(
_In_ PVOID InfoBuffer,
_In_ FILE_INFORMATION_CLASS InfoClass,
_Out_ PBOOLEAN IsPartialPlaceholder
);
// rev
NTSYSAPI
BOOLEAN
NTAPI
RtlIsNonEmptyDirectoryReparsePointAllowed(
_In_ ULONG ReparseTag
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlAppxIsFileOwnedByTrustedInstaller(
_In_ HANDLE FileHandle,
_Out_ PBOOLEAN IsFileOwnedByTrustedInstaller
);
// rev
typedef struct _PS_PKG_CLAIM
{
ULONGLONG Flags;
ULONGLONG Origin;
} PS_PKG_CLAIM, *PPS_PKG_CLAIM;
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryPackageClaims(
_In_ HANDLE TokenHandle,
_Out_writes_bytes_to_opt_(*PackageSize, *PackageSize) PWSTR PackageFullName,
_Inout_opt_ PSIZE_T PackageSize,
_Out_writes_bytes_to_opt_(*AppIdSize, *AppIdSize) PWSTR AppId,
_Inout_opt_ PSIZE_T AppIdSize,
_Out_opt_ PGUID DynamicId,
_Out_opt_ PPS_PKG_CLAIM PkgClaim,
_Out_opt_ PULONG64 AttributesPresent
);
// Protected policies
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlQueryProtectedPolicy(
_In_ PGUID PolicyGuid,
_Out_ PULONG_PTR PolicyValue
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlSetProtectedPolicy(
_In_ PGUID PolicyGuid,
_In_ ULONG_PTR PolicyValue,
_Out_ PULONG_PTR OldPolicyValue
);
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
// private
NTSYSAPI
BOOLEAN
NTAPI
RtlIsMultiSessionSku(
VOID
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN10_RS1)
// private
NTSYSAPI
BOOLEAN
NTAPI
RtlIsMultiUsersInSessionSku(
VOID
);
#endif
// private
typedef enum _RTL_BSD_ITEM_TYPE
{
RtlBsdItemVersionNumber,
RtlBsdItemProductType,
RtlBsdItemAabEnabled,
RtlBsdItemAabTimeout,
RtlBsdItemBootGood,
RtlBsdItemBootShutdown,
RtlBsdSleepInProgress,
RtlBsdPowerTransition,
RtlBsdItemBootAttemptCount,
RtlBsdItemBootCheckpoint,
RtlBsdItemBootId,
RtlBsdItemShutdownBootId,
RtlBsdItemReportedAbnormalShutdownBootId,
RtlBsdItemErrorInfo,
RtlBsdItemPowerButtonPressInfo,
RtlBsdItemChecksum,
RtlBsdItemMax
} RTL_BSD_ITEM_TYPE;
// private
typedef struct _RTL_BSD_ITEM
{
RTL_BSD_ITEM_TYPE Type;
PVOID DataBuffer;
ULONG DataLength;
} RTL_BSD_ITEM, *PRTL_BSD_ITEM;
// ros
NTSYSAPI
NTSTATUS
NTAPI
RtlCreateBootStatusDataFile(
VOID
);
// ros
NTSYSAPI
NTSTATUS
NTAPI
RtlLockBootStatusData(
_Out_ PHANDLE FileHandle
);
// ros
NTSYSAPI
NTSTATUS
NTAPI
RtlUnlockBootStatusData(
_In_ HANDLE FileHandle
);
// ros
NTSYSAPI
NTSTATUS
NTAPI
RtlGetSetBootStatusData(
_In_ HANDLE FileHandle,
_In_ BOOLEAN Read,
_In_ RTL_BSD_ITEM_TYPE DataClass,
_In_ PVOID Buffer,
_In_ ULONG BufferSize,
_Out_opt_ PULONG ReturnLength
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckBootStatusIntegrity(
_In_ HANDLE FileHandle,
_Out_ PBOOLEAN Verified
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlCheckPortableOperatingSystem(
_Out_ PBOOLEAN IsPortable // VOID
);
// rev
NTSYSAPI
NTSTATUS
NTAPI
RtlSetPortableOperatingSystem(
_In_ BOOLEAN IsPortable
);
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSAPI
OS_DEPLOYEMENT_STATE_VALUES
NTAPI
RtlOsDeploymentState(
_Reserved_ _In_ ULONG Flags
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSAPI
NTSTATUS
NTAPI
RtlFindClosestEncodableLength(
_In_ ULONGLONG SourceLength,
_Out_ PULONGLONG TargetLength
);
#endif
// Memory cache
typedef NTSTATUS (NTAPI *PRTL_SECURE_MEMORY_CACHE_CALLBACK)(
_In_ PVOID Address,
_In_ SIZE_T Length
);
// ros
NTSYSAPI
NTSTATUS
NTAPI
RtlRegisterSecureMemoryCacheCallback(
_In_ PRTL_SECURE_MEMORY_CACHE_CALLBACK Callback
);
NTSYSAPI
NTSTATUS
NTAPI
RtlDeregisterSecureMemoryCacheCallback(
_In_ PRTL_SECURE_MEMORY_CACHE_CALLBACK Callback
);
// ros
NTSYSAPI
BOOLEAN
NTAPI
RtlFlushSecureMemoryCache(
_In_ PVOID MemoryCache,
_In_opt_ SIZE_T MemoryLength
);
// #include <ntseapi.h>
// Privileges
#define SE_MIN_WELL_KNOWN_PRIVILEGE (2L)
#define SE_CREATE_TOKEN_PRIVILEGE (2L)
#define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE (3L)
#define SE_LOCK_MEMORY_PRIVILEGE (4L)
#define SE_INCREASE_QUOTA_PRIVILEGE (5L)
#define SE_MACHINE_ACCOUNT_PRIVILEGE (6L)
#define SE_TCB_PRIVILEGE (7L)
#define SE_SECURITY_PRIVILEGE (8L)
#define SE_TAKE_OWNERSHIP_PRIVILEGE (9L)
#define SE_LOAD_DRIVER_PRIVILEGE (10L)
#define SE_SYSTEM_PROFILE_PRIVILEGE (11L)
#define SE_SYSTEMTIME_PRIVILEGE (12L)
#define SE_PROF_SINGLE_PROCESS_PRIVILEGE (13L)
#define SE_INC_BASE_PRIORITY_PRIVILEGE (14L)
#define SE_CREATE_PAGEFILE_PRIVILEGE (15L)
#define SE_CREATE_PERMANENT_PRIVILEGE (16L)
#define SE_BACKUP_PRIVILEGE (17L)
#define SE_RESTORE_PRIVILEGE (18L)
#define SE_SHUTDOWN_PRIVILEGE (19L)
#define SE_DEBUG_PRIVILEGE (20L)
#define SE_AUDIT_PRIVILEGE (21L)
#define SE_SYSTEM_ENVIRONMENT_PRIVILEGE (22L)
#define SE_CHANGE_NOTIFY_PRIVILEGE (23L)
#define SE_REMOTE_SHUTDOWN_PRIVILEGE (24L)
#define SE_UNDOCK_PRIVILEGE (25L)
#define SE_SYNC_AGENT_PRIVILEGE (26L)
#define SE_ENABLE_DELEGATION_PRIVILEGE (27L)
#define SE_MANAGE_VOLUME_PRIVILEGE (28L)
#define SE_IMPERSONATE_PRIVILEGE (29L)
#define SE_CREATE_GLOBAL_PRIVILEGE (30L)
#define SE_TRUSTED_CREDMAN_ACCESS_PRIVILEGE (31L)
#define SE_RELABEL_PRIVILEGE (32L)
#define SE_INC_WORKING_SET_PRIVILEGE (33L)
#define SE_TIME_ZONE_PRIVILEGE (34L)
#define SE_CREATE_SYMBOLIC_LINK_PRIVILEGE (35L)
#define SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE (36L)
#define SE_MAX_WELL_KNOWN_PRIVILEGE SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE
// Authz
// begin_rev
// Types
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_INVALID 0x00
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_INT64 0x01
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_UINT64 0x02
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_STRING 0x03
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_FQBN 0x04
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_SID 0x05
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_BOOLEAN 0x06
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING 0x10
// Flags
#define TOKEN_SECURITY_ATTRIBUTE_NON_INHERITABLE 0x0001
#define TOKEN_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE 0x0002
#define TOKEN_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY 0x0004
#define TOKEN_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT 0x0008
#define TOKEN_SECURITY_ATTRIBUTE_DISABLED 0x0010
#define TOKEN_SECURITY_ATTRIBUTE_MANDATORY 0x0020
#define TOKEN_SECURITY_ATTRIBUTE_COMPARE_IGNORE 0x0040
#define TOKEN_SECURITY_ATTRIBUTE_VALID_FLAGS ( \
TOKEN_SECURITY_ATTRIBUTE_NON_INHERITABLE | \
TOKEN_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE | \
TOKEN_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY | \
TOKEN_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT | \
TOKEN_SECURITY_ATTRIBUTE_DISABLED | \
TOKEN_SECURITY_ATTRIBUTE_MANDATORY)
#define TOKEN_SECURITY_ATTRIBUTE_CUSTOM_FLAGS 0xffff0000
// end_rev
// private
typedef struct _TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE
{
ULONG64 Version;
UNICODE_STRING Name;
} TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE, *PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE;
// private
typedef struct _TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE
{
PVOID pValue;
ULONG ValueLength;
} TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE, *PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE;
// private
typedef struct _TOKEN_SECURITY_ATTRIBUTE_V1
{
UNICODE_STRING Name;
USHORT ValueType;
USHORT Reserved;
ULONG Flags;
ULONG ValueCount;
union
{
PLONG64 pInt64;
PULONG64 pUint64;
PUNICODE_STRING pString;
PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE pFqbn;
PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE pOctetString;
} Values;
} TOKEN_SECURITY_ATTRIBUTE_V1, *PTOKEN_SECURITY_ATTRIBUTE_V1;
// rev
#define TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 1
// rev
#define TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1
// private
typedef struct _TOKEN_SECURITY_ATTRIBUTES_INFORMATION
{
USHORT Version;
USHORT Reserved;
ULONG AttributeCount;
union
{
PTOKEN_SECURITY_ATTRIBUTE_V1 pAttributeV1;
} Attribute;
} TOKEN_SECURITY_ATTRIBUTES_INFORMATION, *PTOKEN_SECURITY_ATTRIBUTES_INFORMATION;
// rev
typedef struct _TOKEN_PROCESS_TRUST_LEVEL
{
PSID TrustLevelSid;
} TOKEN_PROCESS_TRUST_LEVEL, *PTOKEN_PROCESS_TRUST_LEVEL;
// Tokens
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateToken(
_Out_ PHANDLE TokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ TOKEN_TYPE TokenType,
_In_ PLUID AuthenticationId,
_In_ PLARGE_INTEGER ExpirationTime,
_In_ PTOKEN_USER User,
_In_ PTOKEN_GROUPS Groups,
_In_ PTOKEN_PRIVILEGES Privileges,
_In_opt_ PTOKEN_OWNER Owner,
_In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
_In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
_In_ PTOKEN_SOURCE TokenSource
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateToken(
_Out_ PHANDLE TokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ TOKEN_TYPE TokenType,
_In_ PLUID AuthenticationId,
_In_ PLARGE_INTEGER ExpirationTime,
_In_ PTOKEN_USER User,
_In_ PTOKEN_GROUPS Groups,
_In_ PTOKEN_PRIVILEGES Privileges,
_In_opt_ PTOKEN_OWNER Owner,
_In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
_In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
_In_ PTOKEN_SOURCE TokenSource
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateLowBoxToken(
_Out_ PHANDLE TokenHandle,
_In_ HANDLE ExistingTokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PSID PackageSid,
_In_ ULONG CapabilityCount,
_In_reads_opt_(CapabilityCount) PSID_AND_ATTRIBUTES Capabilities,
_In_ ULONG HandleCount,
_In_reads_opt_(HandleCount) HANDLE *Handles
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateLowBoxToken(
_Out_ PHANDLE TokenHandle,
_In_ HANDLE ExistingTokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ PSID PackageSid,
_In_ ULONG CapabilityCount,
_In_reads_opt_(CapabilityCount) PSID_AND_ATTRIBUTES Capabilities,
_In_ ULONG HandleCount,
_In_reads_opt_(HandleCount) HANDLE *Handles
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateTokenEx(
_Out_ PHANDLE TokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ TOKEN_TYPE TokenType,
_In_ PLUID AuthenticationId,
_In_ PLARGE_INTEGER ExpirationTime,
_In_ PTOKEN_USER User,
_In_ PTOKEN_GROUPS Groups,
_In_ PTOKEN_PRIVILEGES Privileges,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION UserAttributes,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION DeviceAttributes,
_In_opt_ PTOKEN_GROUPS DeviceGroups,
_In_opt_ PTOKEN_MANDATORY_POLICY TokenMandatoryPolicy,
_In_opt_ PTOKEN_OWNER Owner,
_In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
_In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
_In_ PTOKEN_SOURCE TokenSource
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateTokenEx(
_Out_ PHANDLE TokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ TOKEN_TYPE TokenType,
_In_ PLUID AuthenticationId,
_In_ PLARGE_INTEGER ExpirationTime,
_In_ PTOKEN_USER User,
_In_ PTOKEN_GROUPS Groups,
_In_ PTOKEN_PRIVILEGES Privileges,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION UserAttributes,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION DeviceAttributes,
_In_opt_ PTOKEN_GROUPS DeviceGroups,
_In_opt_ PTOKEN_MANDATORY_POLICY TokenMandatoryPolicy,
_In_opt_ PTOKEN_OWNER Owner,
_In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
_In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
_In_ PTOKEN_SOURCE TokenSource
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenProcessToken(
_In_ HANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenProcessToken(
_In_ HANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenProcessTokenEx(
_In_ HANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenProcessTokenEx(
_In_ HANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG HandleAttributes,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenThreadToken(
_In_ HANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ BOOLEAN OpenAsSelf,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenThreadToken(
_In_ HANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ BOOLEAN OpenAsSelf,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenThreadTokenEx(
_In_ HANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ BOOLEAN OpenAsSelf,
_In_ ULONG HandleAttributes,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenThreadTokenEx(
_In_ HANDLE ThreadHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ BOOLEAN OpenAsSelf,
_In_ ULONG HandleAttributes,
_Out_ PHANDLE TokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDuplicateToken(
_In_ HANDLE ExistingTokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ BOOLEAN EffectiveOnly,
_In_ TOKEN_TYPE TokenType,
_Out_ PHANDLE NewTokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDuplicateToken(
_In_ HANDLE ExistingTokenHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ BOOLEAN EffectiveOnly,
_In_ TOKEN_TYPE TokenType,
_Out_ PHANDLE NewTokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationToken(
_In_ HANDLE TokenHandle,
_In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
_Out_writes_bytes_(TokenInformationLength) PVOID TokenInformation,
_In_ ULONG TokenInformationLength,
_Out_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationToken(
_In_ HANDLE TokenHandle,
_In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
_Out_writes_bytes_(TokenInformationLength) PVOID TokenInformation,
_In_ ULONG TokenInformationLength,
_Out_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationToken(
_In_ HANDLE TokenHandle,
_In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
_In_reads_bytes_(TokenInformationLength) PVOID TokenInformation,
_In_ ULONG TokenInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationToken(
_In_ HANDLE TokenHandle,
_In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
_In_reads_bytes_(TokenInformationLength) PVOID TokenInformation,
_In_ ULONG TokenInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAdjustPrivilegesToken(
_In_ HANDLE TokenHandle,
_In_ BOOLEAN DisableAllPrivileges,
_In_opt_ PTOKEN_PRIVILEGES NewState,
_In_ ULONG BufferLength,
_Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState,
_Out_ _When_(PreviousState == NULL, _Out_opt_) PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAdjustPrivilegesToken(
_In_ HANDLE TokenHandle,
_In_ BOOLEAN DisableAllPrivileges,
_In_opt_ PTOKEN_PRIVILEGES NewState,
_In_ ULONG BufferLength,
_Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState,
_Out_ _When_(PreviousState == NULL, _Out_opt_) PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAdjustGroupsToken(
_In_ HANDLE TokenHandle,
_In_ BOOLEAN ResetToDefault,
_In_opt_ PTOKEN_GROUPS NewState,
_In_opt_ ULONG BufferLength,
_Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_GROUPS PreviousState,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAdjustGroupsToken(
_In_ HANDLE TokenHandle,
_In_ BOOLEAN ResetToDefault,
_In_opt_ PTOKEN_GROUPS NewState,
_In_opt_ ULONG BufferLength,
_Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_GROUPS PreviousState,
_Out_opt_ PULONG ReturnLength
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAdjustTokenClaimsAndDeviceGroups(
_In_ HANDLE TokenHandle,
_In_ BOOLEAN UserResetToDefault,
_In_ BOOLEAN DeviceResetToDefault,
_In_ BOOLEAN DeviceGroupsResetToDefault,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewUserState,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewDeviceState,
_In_opt_ PTOKEN_GROUPS NewDeviceGroupsState,
_In_ ULONG UserBufferLength,
_Out_writes_bytes_to_opt_(UserBufferLength, *UserReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousUserState,
_In_ ULONG DeviceBufferLength,
_Out_writes_bytes_to_opt_(DeviceBufferLength, *DeviceReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousDeviceState,
_In_ ULONG DeviceGroupsBufferLength,
_Out_writes_bytes_to_opt_(DeviceGroupsBufferLength, *DeviceGroupsReturnBufferLength) PTOKEN_GROUPS PreviousDeviceGroups,
_Out_opt_ PULONG UserReturnLength,
_Out_opt_ PULONG DeviceReturnLength,
_Out_opt_ PULONG DeviceGroupsReturnBufferLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAdjustTokenClaimsAndDeviceGroups(
_In_ HANDLE TokenHandle,
_In_ BOOLEAN UserResetToDefault,
_In_ BOOLEAN DeviceResetToDefault,
_In_ BOOLEAN DeviceGroupsResetToDefault,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewUserState,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewDeviceState,
_In_opt_ PTOKEN_GROUPS NewDeviceGroupsState,
_In_ ULONG UserBufferLength,
_Out_writes_bytes_to_opt_(UserBufferLength, *UserReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousUserState,
_In_ ULONG DeviceBufferLength,
_Out_writes_bytes_to_opt_(DeviceBufferLength, *DeviceReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousDeviceState,
_In_ ULONG DeviceGroupsBufferLength,
_Out_writes_bytes_to_opt_(DeviceGroupsBufferLength, *DeviceGroupsReturnBufferLength) PTOKEN_GROUPS PreviousDeviceGroups,
_Out_opt_ PULONG UserReturnLength,
_Out_opt_ PULONG DeviceReturnLength,
_Out_opt_ PULONG DeviceGroupsReturnBufferLength
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFilterToken(
_In_ HANDLE ExistingTokenHandle,
_In_ ULONG Flags,
_In_opt_ PTOKEN_GROUPS SidsToDisable,
_In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
_In_opt_ PTOKEN_GROUPS RestrictedSids,
_Out_ PHANDLE NewTokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFilterToken(
_In_ HANDLE ExistingTokenHandle,
_In_ ULONG Flags,
_In_opt_ PTOKEN_GROUPS SidsToDisable,
_In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
_In_opt_ PTOKEN_GROUPS RestrictedSids,
_Out_ PHANDLE NewTokenHandle
);
#if (NTDDI_VERSION >= NTDDI_WIN8)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFilterTokenEx(
_In_ HANDLE ExistingTokenHandle,
_In_ ULONG Flags,
_In_opt_ PTOKEN_GROUPS SidsToDisable,
_In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
_In_opt_ PTOKEN_GROUPS RestrictedSids,
_In_ ULONG DisableUserClaimsCount,
_In_opt_ PUNICODE_STRING UserClaimsToDisable,
_In_ ULONG DisableDeviceClaimsCount,
_In_opt_ PUNICODE_STRING DeviceClaimsToDisable,
_In_opt_ PTOKEN_GROUPS DeviceGroupsToDisable,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedUserAttributes,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedDeviceAttributes,
_In_opt_ PTOKEN_GROUPS RestrictedDeviceGroups,
_Out_ PHANDLE NewTokenHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFilterTokenEx(
_In_ HANDLE ExistingTokenHandle,
_In_ ULONG Flags,
_In_opt_ PTOKEN_GROUPS SidsToDisable,
_In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
_In_opt_ PTOKEN_GROUPS RestrictedSids,
_In_ ULONG DisableUserClaimsCount,
_In_opt_ PUNICODE_STRING UserClaimsToDisable,
_In_ ULONG DisableDeviceClaimsCount,
_In_opt_ PUNICODE_STRING DeviceClaimsToDisable,
_In_opt_ PTOKEN_GROUPS DeviceGroupsToDisable,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedUserAttributes,
_In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedDeviceAttributes,
_In_opt_ PTOKEN_GROUPS RestrictedDeviceGroups,
_Out_ PHANDLE NewTokenHandle
);
#endif
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCompareTokens(
_In_ HANDLE FirstTokenHandle,
_In_ HANDLE SecondTokenHandle,
_Out_ PBOOLEAN Equal
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCompareTokens(
_In_ HANDLE FirstTokenHandle,
_In_ HANDLE SecondTokenHandle,
_Out_ PBOOLEAN Equal
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrivilegeCheck(
_In_ HANDLE ClientToken,
_Inout_ PPRIVILEGE_SET RequiredPrivileges,
_Out_ PBOOLEAN Result
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrivilegeCheck(
_In_ HANDLE ClientToken,
_Inout_ PPRIVILEGE_SET RequiredPrivileges,
_Out_ PBOOLEAN Result
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtImpersonateAnonymousToken(
_In_ HANDLE ThreadHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwImpersonateAnonymousToken(
_In_ HANDLE ThreadHandle
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQuerySecurityAttributesToken(
_In_ HANDLE TokenHandle,
_In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes,
_In_ ULONG NumberOfAttributes,
_Out_writes_bytes_(Length) PVOID Buffer, // PTOKEN_SECURITY_ATTRIBUTES_INFORMATION
_In_ ULONG Length,
_Out_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQuerySecurityAttributesToken(
_In_ HANDLE TokenHandle,
_In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes,
_In_ ULONG NumberOfAttributes,
_Out_writes_bytes_(Length) PVOID Buffer, // PTOKEN_SECURITY_ATTRIBUTES_INFORMATION
_In_ ULONG Length,
_Out_ PULONG ReturnLength
);
#endif
// Access checking
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheck(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_ PGENERIC_MAPPING GenericMapping,
_Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
_Inout_ PULONG PrivilegeSetLength,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheck(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_ PGENERIC_MAPPING GenericMapping,
_Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
_Inout_ PULONG PrivilegeSetLength,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheckByType(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
_Inout_ PULONG PrivilegeSetLength,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheckByType(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
_Inout_ PULONG PrivilegeSetLength,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheckByTypeResultList(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
_Inout_ PULONG PrivilegeSetLength,
_Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
_Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheckByTypeResultList(
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
_Inout_ PULONG PrivilegeSetLength,
_Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
_Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus
);
// Signing
#if (NTDDI_VERSION >= NTDDI_WIN10)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetCachedSigningLevel(
_In_ ULONG Flags,
_In_ SE_SIGNING_LEVEL InputSigningLevel,
_In_reads_(SourceFileCount) PHANDLE SourceFiles,
_In_ ULONG SourceFileCount,
_In_opt_ HANDLE TargetFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetCachedSigningLevel(
_In_ ULONG Flags,
_In_ SE_SIGNING_LEVEL InputSigningLevel,
_In_reads_(SourceFileCount) PHANDLE SourceFiles,
_In_ ULONG SourceFileCount,
_In_opt_ HANDLE TargetFile
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetCachedSigningLevel(
_In_ HANDLE File,
_Out_ PULONG Flags,
_Out_ PSE_SIGNING_LEVEL SigningLevel,
_Out_writes_bytes_to_opt_(*ThumbprintSize, *ThumbprintSize) PUCHAR Thumbprint,
_Inout_opt_ PULONG ThumbprintSize,
_Out_opt_ PULONG ThumbprintAlgorithm
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetCachedSigningLevel(
_In_ HANDLE File,
_Out_ PULONG Flags,
_Out_ PSE_SIGNING_LEVEL SigningLevel,
_Out_writes_bytes_to_opt_(*ThumbprintSize, *ThumbprintSize) PUCHAR Thumbprint,
_Inout_opt_ PULONG ThumbprintSize,
_Out_opt_ PULONG ThumbprintAlgorithm
);
#endif
// Audit alarm
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheckAndAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ ACCESS_MASK DesiredAccess,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheckAndAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ ACCESS_MASK DesiredAccess,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheckByTypeAndAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ ACCESS_MASK DesiredAccess,
_In_ AUDIT_EVENT_TYPE AuditType,
_In_ ULONG Flags,
_In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheckByTypeAndAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ ACCESS_MASK DesiredAccess,
_In_ AUDIT_EVENT_TYPE AuditType,
_In_ ULONG Flags,
_In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_ PACCESS_MASK GrantedAccess,
_Out_ PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheckByTypeResultListAndAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ ACCESS_MASK DesiredAccess,
_In_ AUDIT_EVENT_TYPE AuditType,
_In_ ULONG Flags,
_In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
_Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheckByTypeResultListAndAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ ACCESS_MASK DesiredAccess,
_In_ AUDIT_EVENT_TYPE AuditType,
_In_ ULONG Flags,
_In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
_Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtAccessCheckByTypeResultListAndAuditAlarmByHandle(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ HANDLE ClientToken,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ ACCESS_MASK DesiredAccess,
_In_ AUDIT_EVENT_TYPE AuditType,
_In_ ULONG Flags,
_In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
_Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwAccessCheckByTypeResultListAndAuditAlarmByHandle(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ HANDLE ClientToken,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_opt_ PSID PrincipalSelfSid,
_In_ ACCESS_MASK DesiredAccess,
_In_ AUDIT_EVENT_TYPE AuditType,
_In_ ULONG Flags,
_In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
_In_ ULONG ObjectTypeListLength,
_In_ PGENERIC_MAPPING GenericMapping,
_In_ BOOLEAN ObjectCreation,
_Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
_Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_ ACCESS_MASK GrantedAccess,
_In_opt_ PPRIVILEGE_SET Privileges,
_In_ BOOLEAN ObjectCreation,
_In_ BOOLEAN AccessGranted,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ PUNICODE_STRING ObjectTypeName,
_In_ PUNICODE_STRING ObjectName,
_In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_ ACCESS_MASK GrantedAccess,
_In_opt_ PPRIVILEGE_SET Privileges,
_In_ BOOLEAN ObjectCreation,
_In_ BOOLEAN AccessGranted,
_Out_ PBOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrivilegeObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_ PPRIVILEGE_SET Privileges,
_In_ BOOLEAN AccessGranted
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrivilegeObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ HANDLE ClientToken,
_In_ ACCESS_MASK DesiredAccess,
_In_ PPRIVILEGE_SET Privileges,
_In_ BOOLEAN AccessGranted
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCloseObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ BOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCloseObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ BOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtDeleteObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ BOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwDeleteObjectAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_opt_ PVOID HandleId,
_In_ BOOLEAN GenerateOnClose
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrivilegedServiceAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_ PUNICODE_STRING ServiceName,
_In_ HANDLE ClientToken,
_In_ PPRIVILEGE_SET Privileges,
_In_ BOOLEAN AccessGranted
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrivilegedServiceAuditAlarm(
_In_ PUNICODE_STRING SubsystemName,
_In_ PUNICODE_STRING ServiceName,
_In_ HANDLE ClientToken,
_In_ PPRIVILEGE_SET Privileges,
_In_ BOOLEAN AccessGranted
);
// #include <nttmapi.h>
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateTransactionManager(
_Out_ PHANDLE TmHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PUNICODE_STRING LogFileName,
_In_opt_ ULONG CreateOptions,
_In_opt_ ULONG CommitStrength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateTransactionManager(
_Out_ PHANDLE TmHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PUNICODE_STRING LogFileName,
_In_opt_ ULONG CreateOptions,
_In_opt_ ULONG CommitStrength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenTransactionManager(
_Out_ PHANDLE TmHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PUNICODE_STRING LogFileName,
_In_opt_ LPGUID TmIdentity,
_In_opt_ ULONG OpenOptions
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenTransactionManager(
_Out_ PHANDLE TmHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PUNICODE_STRING LogFileName,
_In_opt_ LPGUID TmIdentity,
_In_opt_ ULONG OpenOptions
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRenameTransactionManager(
_In_ PUNICODE_STRING LogFileName,
_In_ LPGUID ExistingTransactionManagerGuid
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRenameTransactionManager(
_In_ PUNICODE_STRING LogFileName,
_In_ LPGUID ExistingTransactionManagerGuid
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRollforwardTransactionManager(
_In_ HANDLE TransactionManagerHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRollforwardTransactionManager(
_In_ HANDLE TransactionManagerHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRecoverTransactionManager(
_In_ HANDLE TransactionManagerHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRecoverTransactionManager(
_In_ HANDLE TransactionManagerHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationTransactionManager(
_In_ HANDLE TransactionManagerHandle,
_In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
_Out_writes_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
_In_ ULONG TransactionManagerInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationTransactionManager(
_In_ HANDLE TransactionManagerHandle,
_In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
_Out_writes_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
_In_ ULONG TransactionManagerInformationLength,
_Out_opt_ PULONG ReturnLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationTransactionManager(
_In_opt_ HANDLE TmHandle,
_In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
_In_reads_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
_In_ ULONG TransactionManagerInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationTransactionManager(
_In_opt_ HANDLE TmHandle,
_In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
_In_reads_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
_In_ ULONG TransactionManagerInformationLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtEnumerateTransactionObject(
_In_opt_ HANDLE RootObjectHandle,
_In_ KTMOBJECT_TYPE QueryType,
_Inout_updates_bytes_(ObjectCursorLength) PKTMOBJECT_CURSOR ObjectCursor,
_In_ ULONG ObjectCursorLength,
_Out_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwEnumerateTransactionObject(
_In_opt_ HANDLE RootObjectHandle,
_In_ KTMOBJECT_TYPE QueryType,
_Inout_updates_bytes_(ObjectCursorLength) PKTMOBJECT_CURSOR ObjectCursor,
_In_ ULONG ObjectCursorLength,
_Out_ PULONG ReturnLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateTransaction(
_Out_ PHANDLE TransactionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ LPGUID Uow,
_In_opt_ HANDLE TmHandle,
_In_opt_ ULONG CreateOptions,
_In_opt_ ULONG IsolationLevel,
_In_opt_ ULONG IsolationFlags,
_In_opt_ PLARGE_INTEGER Timeout,
_In_opt_ PUNICODE_STRING Description
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateTransaction(
_Out_ PHANDLE TransactionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ LPGUID Uow,
_In_opt_ HANDLE TmHandle,
_In_opt_ ULONG CreateOptions,
_In_opt_ ULONG IsolationLevel,
_In_opt_ ULONG IsolationFlags,
_In_opt_ PLARGE_INTEGER Timeout,
_In_opt_ PUNICODE_STRING Description
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenTransaction(
_Out_ PHANDLE TransactionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ LPGUID Uow,
_In_opt_ HANDLE TmHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenTransaction(
_Out_ PHANDLE TransactionHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_ LPGUID Uow,
_In_opt_ HANDLE TmHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationTransaction(
_In_ HANDLE TransactionHandle,
_In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
_Out_writes_bytes_(TransactionInformationLength) PVOID TransactionInformation,
_In_ ULONG TransactionInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationTransaction(
_In_ HANDLE TransactionHandle,
_In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
_Out_writes_bytes_(TransactionInformationLength) PVOID TransactionInformation,
_In_ ULONG TransactionInformationLength,
_Out_opt_ PULONG ReturnLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationTransaction(
_In_ HANDLE TransactionHandle,
_In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
_In_reads_bytes_(TransactionInformationLength) PVOID TransactionInformation,
_In_ ULONG TransactionInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationTransaction(
_In_ HANDLE TransactionHandle,
_In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
_In_reads_bytes_(TransactionInformationLength) PVOID TransactionInformation,
_In_ ULONG TransactionInformationLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCommitTransaction(
_In_ HANDLE TransactionHandle,
_In_ BOOLEAN Wait
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCommitTransaction(
_In_ HANDLE TransactionHandle,
_In_ BOOLEAN Wait
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRollbackTransaction(
_In_ HANDLE TransactionHandle,
_In_ BOOLEAN Wait
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRollbackTransaction(
_In_ HANDLE TransactionHandle,
_In_ BOOLEAN Wait
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateEnlistment(
_Out_ PHANDLE EnlistmentHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE ResourceManagerHandle,
_In_ HANDLE TransactionHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ ULONG CreateOptions,
_In_ NOTIFICATION_MASK NotificationMask,
_In_opt_ PVOID EnlistmentKey
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateEnlistment(
_Out_ PHANDLE EnlistmentHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE ResourceManagerHandle,
_In_ HANDLE TransactionHandle,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ ULONG CreateOptions,
_In_ NOTIFICATION_MASK NotificationMask,
_In_opt_ PVOID EnlistmentKey
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenEnlistment(
_Out_ PHANDLE EnlistmentHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE ResourceManagerHandle,
_In_ LPGUID EnlistmentGuid,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenEnlistment(
_Out_ PHANDLE EnlistmentHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE ResourceManagerHandle,
_In_ LPGUID EnlistmentGuid,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
_Out_writes_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
_In_ ULONG EnlistmentInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
_Out_writes_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
_In_ ULONG EnlistmentInformationLength,
_Out_opt_ PULONG ReturnLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationEnlistment(
_In_opt_ HANDLE EnlistmentHandle,
_In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
_In_reads_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
_In_ ULONG EnlistmentInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationEnlistment(
_In_opt_ HANDLE EnlistmentHandle,
_In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
_In_reads_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
_In_ ULONG EnlistmentInformationLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRecoverEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PVOID EnlistmentKey
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRecoverEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PVOID EnlistmentKey
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrePrepareEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrePrepareEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrepareEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrepareEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCommitEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCommitEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRollbackEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRollbackEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrePrepareComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrePrepareComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPrepareComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPrepareComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCommitComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCommitComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtReadOnlyEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwReadOnlyEnlistment(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRollbackComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRollbackComplete(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSinglePhaseReject(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSinglePhaseReject(
_In_ HANDLE EnlistmentHandle,
_In_opt_ PLARGE_INTEGER TmVirtualClock
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtCreateResourceManager(
_Out_ PHANDLE ResourceManagerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE TmHandle,
_In_ LPGUID RmGuid,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ ULONG CreateOptions,
_In_opt_ PUNICODE_STRING Description
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwCreateResourceManager(
_Out_ PHANDLE ResourceManagerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE TmHandle,
_In_ LPGUID RmGuid,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ ULONG CreateOptions,
_In_opt_ PUNICODE_STRING Description
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtOpenResourceManager(
_Out_ PHANDLE ResourceManagerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE TmHandle,
_In_opt_ LPGUID ResourceManagerGuid,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwOpenResourceManager(
_Out_ PHANDLE ResourceManagerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ HANDLE TmHandle,
_In_opt_ LPGUID ResourceManagerGuid,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRecoverResourceManager(
_In_ HANDLE ResourceManagerHandle
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRecoverResourceManager(
_In_ HANDLE ResourceManagerHandle
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtGetNotificationResourceManager(
_In_ HANDLE ResourceManagerHandle,
_Out_ PTRANSACTION_NOTIFICATION TransactionNotification,
_In_ ULONG NotificationLength,
_In_opt_ PLARGE_INTEGER Timeout,
_Out_opt_ PULONG ReturnLength,
_In_ ULONG Asynchronous,
_In_opt_ ULONG_PTR AsynchronousContext
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwGetNotificationResourceManager(
_In_ HANDLE ResourceManagerHandle,
_Out_ PTRANSACTION_NOTIFICATION TransactionNotification,
_In_ ULONG NotificationLength,
_In_opt_ PLARGE_INTEGER Timeout,
_Out_opt_ PULONG ReturnLength,
_In_ ULONG Asynchronous,
_In_opt_ ULONG_PTR AsynchronousContext
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationResourceManager(
_In_ HANDLE ResourceManagerHandle,
_In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
_Out_writes_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
_In_ ULONG ResourceManagerInformationLength,
_Out_opt_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwQueryInformationResourceManager(
_In_ HANDLE ResourceManagerHandle,
_In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
_Out_writes_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
_In_ ULONG ResourceManagerInformationLength,
_Out_opt_ PULONG ReturnLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtSetInformationResourceManager(
_In_ HANDLE ResourceManagerHandle,
_In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
_In_reads_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
_In_ ULONG ResourceManagerInformationLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwSetInformationResourceManager(
_In_ HANDLE ResourceManagerHandle,
_In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
_In_reads_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
_In_ ULONG ResourceManagerInformationLength
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRegisterProtocolAddressInformation(
_In_ HANDLE ResourceManager,
_In_ PCRM_PROTOCOL_ID ProtocolId,
_In_ ULONG ProtocolInformationSize,
_In_ PVOID ProtocolInformation,
_In_opt_ ULONG CreateOptions
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRegisterProtocolAddressInformation(
_In_ HANDLE ResourceManager,
_In_ PCRM_PROTOCOL_ID ProtocolId,
_In_ ULONG ProtocolInformationSize,
_In_ PVOID ProtocolInformation,
_In_opt_ ULONG CreateOptions
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPropagationComplete(
_In_ HANDLE ResourceManagerHandle,
_In_ ULONG RequestCookie,
_In_ ULONG BufferLength,
_In_ PVOID Buffer
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPropagationComplete(
_In_ HANDLE ResourceManagerHandle,
_In_ ULONG RequestCookie,
_In_ ULONG BufferLength,
_In_ PVOID Buffer
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
NTSYSCALLAPI
NTSTATUS
NTAPI
NtPropagationFailed(
_In_ HANDLE ResourceManagerHandle,
_In_ ULONG RequestCookie,
_In_ NTSTATUS PropStatus
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwPropagationFailed(
_In_ HANDLE ResourceManagerHandle,
_In_ ULONG RequestCookie,
_In_ NTSTATUS PropStatus
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtFreezeTransactions(
_In_ PLARGE_INTEGER FreezeTimeout,
_In_ PLARGE_INTEGER ThawTimeout
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwFreezeTransactions(
_In_ PLARGE_INTEGER FreezeTimeout,
_In_ PLARGE_INTEGER ThawTimeout
);
#endif
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtThawTransactions(
VOID
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwThawTransactions(
VOID
);
#endif
// #include <nttp.h>
// Some types are already defined in winnt.h.
typedef struct _TP_ALPC TP_ALPC, *PTP_ALPC;
// private
typedef VOID (NTAPI *PTP_ALPC_CALLBACK)(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_Inout_opt_ PVOID Context,
_In_ PTP_ALPC Alpc
);
// rev
typedef VOID (NTAPI *PTP_ALPC_CALLBACK_EX)(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_Inout_opt_ PVOID Context,
_In_ PTP_ALPC Alpc,
_In_ PVOID ApcContext
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpAllocPool(
_Out_ PTP_POOL *PoolReturn,
_Reserved_ PVOID Reserved
);
// winbase:CloseThreadpool
NTSYSAPI
VOID
NTAPI
TpReleasePool(
_Inout_ PTP_POOL Pool
);
// winbase:SetThreadpoolThreadMaximum
NTSYSAPI
VOID
NTAPI
TpSetPoolMaxThreads(
_Inout_ PTP_POOL Pool,
_In_ LONG MaxThreads
);
// private
NTSYSAPI
NTSTATUS
NTAPI
TpSetPoolMinThreads(
_Inout_ PTP_POOL Pool,
_In_ LONG MinThreads
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
TpQueryPoolStackInformation(
_In_ PTP_POOL Pool,
_Out_ PTP_POOL_STACK_INFORMATION PoolStackInformation
);
#endif
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
TpSetPoolStackInformation(
_Inout_ PTP_POOL Pool,
_In_ PTP_POOL_STACK_INFORMATION PoolStackInformation
);
#endif
// private
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpAllocCleanupGroup(
_Out_ PTP_CLEANUP_GROUP *CleanupGroupReturn
);
// winbase:CloseThreadpoolCleanupGroup
NTSYSAPI
VOID
NTAPI
TpReleaseCleanupGroup(
_Inout_ PTP_CLEANUP_GROUP CleanupGroup
);
// winbase:CloseThreadpoolCleanupGroupMembers
NTSYSAPI
VOID
NTAPI
TpReleaseCleanupGroupMembers(
_Inout_ PTP_CLEANUP_GROUP CleanupGroup,
_In_ LOGICAL CancelPendingCallbacks,
_Inout_opt_ PVOID CleanupParameter
);
// winbase:SetEventWhenCallbackReturns
NTSYSAPI
VOID
NTAPI
TpCallbackSetEventOnCompletion(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_In_ HANDLE Event
);
// winbase:ReleaseSemaphoreWhenCallbackReturns
NTSYSAPI
VOID
NTAPI
TpCallbackReleaseSemaphoreOnCompletion(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_In_ HANDLE Semaphore,
_In_ LONG ReleaseCount
);
// winbase:ReleaseMutexWhenCallbackReturns
NTSYSAPI
VOID
NTAPI
TpCallbackReleaseMutexOnCompletion(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_In_ HANDLE Mutex
);
// winbase:LeaveCriticalSectionWhenCallbackReturns
NTSYSAPI
VOID
NTAPI
TpCallbackLeaveCriticalSectionOnCompletion(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_Inout_ PRTL_CRITICAL_SECTION CriticalSection
);
// winbase:FreeLibraryWhenCallbackReturns
NTSYSAPI
VOID
NTAPI
TpCallbackUnloadDllOnCompletion(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_In_ PVOID DllHandle
);
// winbase:CallbackMayRunLong
NTSYSAPI
NTSTATUS
NTAPI
TpCallbackMayRunLong(
_Inout_ PTP_CALLBACK_INSTANCE Instance
);
// winbase:DisassociateCurrentThreadFromCallback
NTSYSAPI
VOID
NTAPI
TpDisassociateCallback(
_Inout_ PTP_CALLBACK_INSTANCE Instance
);
// winbase:TrySubmitThreadpoolCallback
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpSimpleTryPost(
_In_ PTP_SIMPLE_CALLBACK Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
// private
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpAllocWork(
_Out_ PTP_WORK *WorkReturn,
_In_ PTP_WORK_CALLBACK Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
// winbase:CloseThreadpoolWork
NTSYSAPI
VOID
NTAPI
TpReleaseWork(
_Inout_ PTP_WORK Work
);
// winbase:SubmitThreadpoolWork
NTSYSAPI
VOID
NTAPI
TpPostWork(
_Inout_ PTP_WORK Work
);
// winbase:WaitForThreadpoolWorkCallbacks
NTSYSAPI
VOID
NTAPI
TpWaitForWork(
_Inout_ PTP_WORK Work,
_In_ LOGICAL CancelPendingCallbacks
);
// private
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpAllocTimer(
_Out_ PTP_TIMER *Timer,
_In_ PTP_TIMER_CALLBACK Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
// winbase:CloseThreadpoolTimer
NTSYSAPI
VOID
NTAPI
TpReleaseTimer(
_Inout_ PTP_TIMER Timer
);
// winbase:SetThreadpoolTimer
NTSYSAPI
VOID
NTAPI
TpSetTimer(
_Inout_ PTP_TIMER Timer,
_In_opt_ PLARGE_INTEGER DueTime,
_In_ LONG Period,
_In_opt_ LONG WindowLength
);
// winbase:IsThreadpoolTimerSet
NTSYSAPI
LOGICAL
NTAPI
TpIsTimerSet(
_In_ PTP_TIMER Timer
);
// winbase:WaitForThreadpoolTimerCallbacks
NTSYSAPI
VOID
NTAPI
TpWaitForTimer(
_Inout_ PTP_TIMER Timer,
_In_ LOGICAL CancelPendingCallbacks
);
// private
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpAllocWait(
_Out_ PTP_WAIT *WaitReturn,
_In_ PTP_WAIT_CALLBACK Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
// winbase:CloseThreadpoolWait
NTSYSAPI
VOID
NTAPI
TpReleaseWait(
_Inout_ PTP_WAIT Wait
);
// winbase:SetThreadpoolWait
NTSYSAPI
VOID
NTAPI
TpSetWait(
_Inout_ PTP_WAIT Wait,
_In_opt_ HANDLE Handle,
_In_opt_ PLARGE_INTEGER Timeout
);
// winbase:WaitForThreadpoolWaitCallbacks
NTSYSAPI
VOID
NTAPI
TpWaitForWait(
_Inout_ PTP_WAIT Wait,
_In_ LOGICAL CancelPendingCallbacks
);
// private
typedef VOID (NTAPI *PTP_IO_CALLBACK)(
_Inout_ PTP_CALLBACK_INSTANCE Instance,
_Inout_opt_ PVOID Context,
_In_ PVOID ApcContext,
_In_ PIO_STATUS_BLOCK IoSB,
_In_ PTP_IO Io
);
// private
_Check_return_
NTSYSAPI
NTSTATUS
NTAPI
TpAllocIoCompletion(
_Out_ PTP_IO *IoReturn,
_In_ HANDLE File,
_In_ PTP_IO_CALLBACK Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
// winbase:CloseThreadpoolIo
NTSYSAPI
VOID
NTAPI
TpReleaseIoCompletion(
_Inout_ PTP_IO Io
);
// winbase:StartThreadpoolIo
NTSYSAPI
VOID
NTAPI
TpStartAsyncIoOperation(
_Inout_ PTP_IO Io
);
// winbase:CancelThreadpoolIo
NTSYSAPI
VOID
NTAPI
TpCancelAsyncIoOperation(
_Inout_ PTP_IO Io
);
// winbase:WaitForThreadpoolIoCallbacks
NTSYSAPI
VOID
NTAPI
TpWaitForIoCompletion(
_Inout_ PTP_IO Io,
_In_ LOGICAL CancelPendingCallbacks
);
// private
NTSYSAPI
NTSTATUS
NTAPI
TpAllocAlpcCompletion(
_Out_ PTP_ALPC *AlpcReturn,
_In_ HANDLE AlpcPort,
_In_ PTP_ALPC_CALLBACK Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
#if (NTDDI_VERSION >= NTDDI_WIN7)
// rev
NTSYSAPI
NTSTATUS
NTAPI
TpAllocAlpcCompletionEx(
_Out_ PTP_ALPC *AlpcReturn,
_In_ HANDLE AlpcPort,
_In_ PTP_ALPC_CALLBACK_EX Callback,
_Inout_opt_ PVOID Context,
_In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
);
#endif
// private
NTSYSAPI
VOID
NTAPI
TpReleaseAlpcCompletion(
_Inout_ PTP_ALPC Alpc
);
// private
NTSYSAPI
VOID
NTAPI
TpWaitForAlpcCompletion(
_Inout_ PTP_ALPC Alpc
);
// private
typedef enum _TP_TRACE_TYPE
{
TpTraceThreadPriority = 1,
TpTraceThreadAffinity,
MaxTpTraceType
} TP_TRACE_TYPE;
// private
NTSYSAPI
VOID
NTAPI
TpCaptureCaller(
_In_ TP_TRACE_TYPE Type
);
// private
NTSYSAPI
VOID
NTAPI
TpCheckTerminateWorker(
_In_ HANDLE Thread
);
#endif
// #include <ntxcapi.h>
NTSYSAPI
BOOLEAN
NTAPI
RtlDispatchException(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord
);
NTSYSAPI
DECLSPEC_NORETURN
VOID
NTAPI
RtlRaiseStatus(
_In_ NTSTATUS Status
);
NTSYSAPI
VOID
NTAPI
RtlRaiseException(
_In_ PEXCEPTION_RECORD ExceptionRecord
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtContinue(
_In_ PCONTEXT ContextRecord,
_In_ BOOLEAN TestAlert
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwContinue(
_In_ PCONTEXT ContextRecord,
_In_ BOOLEAN TestAlert
);
NTSYSCALLAPI
NTSTATUS
NTAPI
NtRaiseException(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord,
_In_ BOOLEAN FirstChance
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwRaiseException(
_In_ PEXCEPTION_RECORD ExceptionRecord,
_In_ PCONTEXT ContextRecord,
_In_ BOOLEAN FirstChance
);
__analysis_noreturn
NTSYSCALLAPI
VOID
NTAPI
RtlAssert(
_In_ PVOID VoidFailedAssertion,
_In_ PVOID VoidFileName,
_In_ ULONG LineNumber,
_In_opt_ PSTR MutableMessage
);
#define RTL_ASSERT(exp) \
((!(exp)) ? (RtlAssert((PVOID)#exp, (PVOID)__FILE__, __LINE__, NULL), FALSE) : TRUE)
#define RTL_ASSERTMSG(msg, exp) \
((!(exp)) ? (RtlAssert((PVOID)#exp, (PVOID)__FILE__, __LINE__, msg), FALSE) : TRUE)
#define RTL_SOFT_ASSERT(_exp) \
((!(_exp)) ? (DbgPrint("%s(%d): Soft assertion failed\n Expression: %s\n", __FILE__, __LINE__, #_exp), FALSE) : TRUE)
#define RTL_SOFT_ASSERTMSG(_msg, _exp) \
((!(_exp)) ? (DbgPrint("%s(%d): Soft assertion failed\n Expression: %s\n Message: %s\n", __FILE__, __LINE__, #_exp, (_msg)), FALSE) : TRUE)
// #include <ntwow64.h>
#define WOW64_SYSTEM_DIRECTORY "SysWOW64"
#define WOW64_SYSTEM_DIRECTORY_U L"SysWOW64"
#define WOW64_X86_TAG " (x86)"
#define WOW64_X86_TAG_U L" (x86)"
// In USER_SHARED_DATA
typedef enum _WOW64_SHARED_INFORMATION
{
SharedNtdll32LdrInitializeThunk,
SharedNtdll32KiUserExceptionDispatcher,
SharedNtdll32KiUserApcDispatcher,
SharedNtdll32KiUserCallbackDispatcher,
SharedNtdll32ExpInterlockedPopEntrySListFault,
SharedNtdll32ExpInterlockedPopEntrySListResume,
SharedNtdll32ExpInterlockedPopEntrySListEnd,
SharedNtdll32RtlUserThreadStart,
SharedNtdll32pQueryProcessDebugInformationRemote,
SharedNtdll32BaseAddress,
SharedNtdll32LdrSystemDllInitBlock,
Wow64SharedPageEntriesCount
} WOW64_SHARED_INFORMATION;
// 32-bit definitions
#define WOW64_POINTER(Type) ULONG
typedef struct _RTL_BALANCED_NODE32
{
union
{
WOW64_POINTER(struct _RTL_BALANCED_NODE *) Children[2];
struct
{
WOW64_POINTER(struct _RTL_BALANCED_NODE *) Left;
WOW64_POINTER(struct _RTL_BALANCED_NODE *) Right;
};
};
union
{
WOW64_POINTER(UCHAR) Red : 1;
WOW64_POINTER(UCHAR) Balance : 2;
WOW64_POINTER(ULONG_PTR) ParentValue;
};
} RTL_BALANCED_NODE32, *PRTL_BALANCED_NODE32;
typedef struct _RTL_RB_TREE32
{
WOW64_POINTER(PRTL_BALANCED_NODE) Root;
WOW64_POINTER(PRTL_BALANCED_NODE) Min;
} RTL_RB_TREE32, *PRTL_RB_TREE32;
typedef struct _PEB_LDR_DATA32
{
ULONG Length;
BOOLEAN Initialized;
WOW64_POINTER(HANDLE) SsHandle;
LIST_ENTRY32 InLoadOrderModuleList;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
WOW64_POINTER(PVOID) EntryInProgress;
BOOLEAN ShutdownInProgress;
WOW64_POINTER(HANDLE) ShutdownThreadId;
} PEB_LDR_DATA32, *PPEB_LDR_DATA32;
typedef struct _LDR_SERVICE_TAG_RECORD32
{
WOW64_POINTER(struct _LDR_SERVICE_TAG_RECORD *) Next;
ULONG ServiceTag;
} LDR_SERVICE_TAG_RECORD32, *PLDR_SERVICE_TAG_RECORD32;
typedef struct _LDRP_CSLIST32
{
WOW64_POINTER(PSINGLE_LIST_ENTRY) Tail;
} LDRP_CSLIST32, *PLDRP_CSLIST32;
typedef struct _LDR_DDAG_NODE32
{
LIST_ENTRY32 Modules;
WOW64_POINTER(PLDR_SERVICE_TAG_RECORD) ServiceTagList;
ULONG LoadCount;
ULONG LoadWhileUnloadingCount;
ULONG LowestLink;
union
{
LDRP_CSLIST32 Dependencies;
SINGLE_LIST_ENTRY32 RemovalLink;
};
LDRP_CSLIST32 IncomingDependencies;
LDR_DDAG_STATE State;
SINGLE_LIST_ENTRY32 CondenseLink;
ULONG PreorderNumber;
} LDR_DDAG_NODE32, *PLDR_DDAG_NODE32;
#define LDR_DATA_TABLE_ENTRY_SIZE_WINXP_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, DdagNode)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN7_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, BaseNameHashValue)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN8_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, ImplicitPathOptions)
typedef struct _LDR_DATA_TABLE_ENTRY32
{
LIST_ENTRY32 InLoadOrderLinks;
LIST_ENTRY32 InMemoryOrderLinks;
union
{
LIST_ENTRY32 InInitializationOrderLinks;
LIST_ENTRY32 InProgressLinks;
};
WOW64_POINTER(PVOID) DllBase;
WOW64_POINTER(PVOID) EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING32 FullDllName;
UNICODE_STRING32 BaseDllName;
union
{
UCHAR FlagGroup[4];
ULONG Flags;
struct
{
ULONG PackagedBinary : 1;
ULONG MarkedForRemoval : 1;
ULONG ImageDll : 1;
ULONG LoadNotificationsSent : 1;
ULONG TelemetryEntryProcessed : 1;
ULONG ProcessStaticImport : 1;
ULONG InLegacyLists : 1;
ULONG InIndexes : 1;
ULONG ShimDll : 1;
ULONG InExceptionTable : 1;
ULONG ReservedFlags1 : 2;
ULONG LoadInProgress : 1;
ULONG LoadConfigProcessed : 1;
ULONG EntryProcessed : 1;
ULONG ProtectDelayLoad : 1;
ULONG ReservedFlags3 : 2;
ULONG DontCallForThreads : 1;
ULONG ProcessAttachCalled : 1;
ULONG ProcessAttachFailed : 1;
ULONG CorDeferredValidate : 1;
ULONG CorImage : 1;
ULONG DontRelocate : 1;
ULONG CorILOnly : 1;
ULONG ChpeImage : 1;
ULONG ReservedFlags5 : 2;
ULONG Redirected : 1;
ULONG ReservedFlags6 : 2;
ULONG CompatDatabaseProcessed : 1;
};
};
USHORT ObsoleteLoadCount;
USHORT TlsIndex;
LIST_ENTRY32 HashLinks;
ULONG TimeDateStamp;
WOW64_POINTER(struct _ACTIVATION_CONTEXT *) EntryPointActivationContext;
WOW64_POINTER(PVOID) Lock;
WOW64_POINTER(PLDR_DDAG_NODE) DdagNode;
LIST_ENTRY32 NodeModuleLink;
WOW64_POINTER(struct _LDRP_LOAD_CONTEXT *) LoadContext;
WOW64_POINTER(PVOID) ParentDllBase;
WOW64_POINTER(PVOID) SwitchBackContext;
RTL_BALANCED_NODE32 BaseAddressIndexNode;
RTL_BALANCED_NODE32 MappingInfoIndexNode;
WOW64_POINTER(ULONG_PTR) OriginalBase;
LARGE_INTEGER LoadTime;
ULONG BaseNameHashValue;
LDR_DLL_LOAD_REASON LoadReason;
ULONG ImplicitPathOptions;
ULONG ReferenceCount;
ULONG DependentLoadFlags;
UCHAR SigningLevel; // since REDSTONE2
} LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32;
typedef struct _CURDIR32
{
UNICODE_STRING32 DosPath;
WOW64_POINTER(HANDLE) Handle;
} CURDIR32, *PCURDIR32;
typedef struct _RTL_DRIVE_LETTER_CURDIR32
{
USHORT Flags;
USHORT Length;
ULONG TimeStamp;
STRING32 DosPath;
} RTL_DRIVE_LETTER_CURDIR32, *PRTL_DRIVE_LETTER_CURDIR32;
typedef struct _RTL_USER_PROCESS_PARAMETERS32
{
ULONG MaximumLength;
ULONG Length;
ULONG Flags;
ULONG DebugFlags;
WOW64_POINTER(HANDLE) ConsoleHandle;
ULONG ConsoleFlags;
WOW64_POINTER(HANDLE) StandardInput;
WOW64_POINTER(HANDLE) StandardOutput;
WOW64_POINTER(HANDLE) StandardError;
CURDIR32 CurrentDirectory;
UNICODE_STRING32 DllPath;
UNICODE_STRING32 ImagePathName;
UNICODE_STRING32 CommandLine;
WOW64_POINTER(PVOID) Environment;
ULONG StartingX;
ULONG StartingY;
ULONG CountX;
ULONG CountY;
ULONG CountCharsX;
ULONG CountCharsY;
ULONG FillAttribute;
ULONG WindowFlags;
ULONG ShowWindowFlags;
UNICODE_STRING32 WindowTitle;
UNICODE_STRING32 DesktopInfo;
UNICODE_STRING32 ShellInfo;
UNICODE_STRING32 RuntimeData;
RTL_DRIVE_LETTER_CURDIR32 CurrentDirectories[RTL_MAX_DRIVE_LETTERS];
WOW64_POINTER(ULONG_PTR) EnvironmentSize;
WOW64_POINTER(ULONG_PTR) EnvironmentVersion;
WOW64_POINTER(PVOID) PackageDependencyData;
ULONG ProcessGroupId;
ULONG LoaderThreads;
UNICODE_STRING32 RedirectionDllName; // REDSTONE4
UNICODE_STRING32 HeapPartitionName; // 19H1
WOW64_POINTER(ULONG_PTR) DefaultThreadpoolCpuSetMasks;
ULONG DefaultThreadpoolCpuSetMaskCount;
} RTL_USER_PROCESS_PARAMETERS32, *PRTL_USER_PROCESS_PARAMETERS32;
typedef struct _PEB32
{
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
union
{
BOOLEAN BitField;
struct
{
BOOLEAN ImageUsesLargePages : 1;
BOOLEAN IsProtectedProcess : 1;
BOOLEAN IsImageDynamicallyRelocated : 1;
BOOLEAN SkipPatchingUser32Forwarders : 1;
BOOLEAN IsPackagedProcess : 1;
BOOLEAN IsAppContainer : 1;
BOOLEAN IsProtectedProcessLight : 1;
BOOLEAN IsLongPathAwareProcess : 1;
};
};
WOW64_POINTER(HANDLE) Mutant;
WOW64_POINTER(PVOID) ImageBaseAddress;
WOW64_POINTER(PPEB_LDR_DATA) Ldr;
WOW64_POINTER(PRTL_USER_PROCESS_PARAMETERS) ProcessParameters;
WOW64_POINTER(PVOID) SubSystemData;
WOW64_POINTER(PVOID) ProcessHeap;
WOW64_POINTER(PRTL_CRITICAL_SECTION) FastPebLock;
WOW64_POINTER(PVOID) AtlThunkSListPtr;
WOW64_POINTER(PVOID) IFEOKey;
union
{
ULONG CrossProcessFlags;
struct
{
ULONG ProcessInJob : 1;
ULONG ProcessInitializing : 1;
ULONG ProcessUsingVEH : 1;
ULONG ProcessUsingVCH : 1;
ULONG ProcessUsingFTH : 1;
ULONG ReservedBits0 : 27;
};
};
union
{
WOW64_POINTER(PVOID) KernelCallbackTable;
WOW64_POINTER(PVOID) UserSharedInfoPtr;
};
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
WOW64_POINTER(PVOID) ApiSetMap;
ULONG TlsExpansionCounter;
WOW64_POINTER(PVOID) TlsBitmap;
ULONG TlsBitmapBits[2];
WOW64_POINTER(PVOID) ReadOnlySharedMemoryBase;
WOW64_POINTER(PVOID) HotpatchInformation;
WOW64_POINTER(PVOID *) ReadOnlyStaticServerData;
WOW64_POINTER(PVOID) AnsiCodePageData;
WOW64_POINTER(PVOID) OemCodePageData;
WOW64_POINTER(PVOID) UnicodeCaseTableData;
ULONG NumberOfProcessors;
ULONG NtGlobalFlag;
LARGE_INTEGER CriticalSectionTimeout;
WOW64_POINTER(SIZE_T) HeapSegmentReserve;
WOW64_POINTER(SIZE_T) HeapSegmentCommit;
WOW64_POINTER(SIZE_T) HeapDeCommitTotalFreeThreshold;
WOW64_POINTER(SIZE_T) HeapDeCommitFreeBlockThreshold;
ULONG NumberOfHeaps;
ULONG MaximumNumberOfHeaps;
WOW64_POINTER(PVOID *) ProcessHeaps;
WOW64_POINTER(PVOID) GdiSharedHandleTable;
WOW64_POINTER(PVOID) ProcessStarterHelper;
ULONG GdiDCAttributeList;
WOW64_POINTER(PRTL_CRITICAL_SECTION) LoaderLock;
ULONG OSMajorVersion;
ULONG OSMinorVersion;
USHORT OSBuildNumber;
USHORT OSCSDVersion;
ULONG OSPlatformId;
ULONG ImageSubsystem;
ULONG ImageSubsystemMajorVersion;
ULONG ImageSubsystemMinorVersion;
WOW64_POINTER(ULONG_PTR) ActiveProcessAffinityMask;
GDI_HANDLE_BUFFER32 GdiHandleBuffer;
WOW64_POINTER(PVOID) PostProcessInitRoutine;
WOW64_POINTER(PVOID) TlsExpansionBitmap;
ULONG TlsExpansionBitmapBits[32];
ULONG SessionId;
ULARGE_INTEGER AppCompatFlags;
ULARGE_INTEGER AppCompatFlagsUser;
WOW64_POINTER(PVOID) pShimData;
WOW64_POINTER(PVOID) AppCompatInfo;
UNICODE_STRING32 CSDVersion;
WOW64_POINTER(PVOID) ActivationContextData;
WOW64_POINTER(PVOID) ProcessAssemblyStorageMap;
WOW64_POINTER(PVOID) SystemDefaultActivationContextData;
WOW64_POINTER(PVOID) SystemAssemblyStorageMap;
WOW64_POINTER(SIZE_T) MinimumStackCommit;
WOW64_POINTER(PVOID) SparePointers[4];
ULONG SpareUlongs[5];
//WOW64_POINTER(PVOID *) FlsCallback;
//LIST_ENTRY32 FlsListHead;
//WOW64_POINTER(PVOID) FlsBitmap;
//ULONG FlsBitmapBits[FLS_MAXIMUM_AVAILABLE / (sizeof(ULONG) * 8)];
//ULONG FlsHighIndex;
WOW64_POINTER(PVOID) WerRegistrationData;
WOW64_POINTER(PVOID) WerShipAssertPtr;
WOW64_POINTER(PVOID) pContextData;
WOW64_POINTER(PVOID) pImageHeaderHash;
union
{
ULONG TracingFlags;
struct
{
ULONG HeapTracingEnabled : 1;
ULONG CritSecTracingEnabled : 1;
ULONG LibLoaderTracingEnabled : 1;
ULONG SpareTracingBits : 29;
};
};
ULONGLONG CsrServerReadOnlySharedMemoryBase;
WOW64_POINTER(PVOID) TppWorkerpListLock;
LIST_ENTRY32 TppWorkerpList;
WOW64_POINTER(PVOID) WaitOnAddressHashTable[128];
WOW64_POINTER(PVOID) TelemetryCoverageHeader; // REDSTONE3
ULONG CloudFileFlags;
ULONG CloudFileDiagFlags; // REDSTONE4
CHAR PlaceholderCompatibilityMode;
CHAR PlaceholderCompatibilityModeReserved[7];
} PEB32, *PPEB32;
C_ASSERT(FIELD_OFFSET(PEB32, IFEOKey) == 0x024);
C_ASSERT(FIELD_OFFSET(PEB32, UnicodeCaseTableData) == 0x060);
C_ASSERT(FIELD_OFFSET(PEB32, SystemAssemblyStorageMap) == 0x204);
C_ASSERT(FIELD_OFFSET(PEB32, pImageHeaderHash) == 0x23c);
C_ASSERT(FIELD_OFFSET(PEB32, WaitOnAddressHashTable) == 0x25c);
//C_ASSERT(sizeof(PEB32) == 0x460); // REDSTONE3
C_ASSERT(sizeof(PEB32) == 0x470);
#define GDI_BATCH_BUFFER_SIZE 310
typedef struct _GDI_TEB_BATCH32
{
ULONG Offset;
WOW64_POINTER(ULONG_PTR) HDC;
ULONG Buffer[GDI_BATCH_BUFFER_SIZE];
} GDI_TEB_BATCH32, *PGDI_TEB_BATCH32;
typedef struct _TEB32
{
NT_TIB32 NtTib;
WOW64_POINTER(PVOID) EnvironmentPointer;
CLIENT_ID32 ClientId;
WOW64_POINTER(PVOID) ActiveRpcHandle;
WOW64_POINTER(PVOID) ThreadLocalStoragePointer;
WOW64_POINTER(PPEB) ProcessEnvironmentBlock;
ULONG LastErrorValue;
ULONG CountOfOwnedCriticalSections;
WOW64_POINTER(PVOID) CsrClientThread;
WOW64_POINTER(PVOID) Win32ThreadInfo;
ULONG User32Reserved[26];
ULONG UserReserved[5];
WOW64_POINTER(PVOID) WOW32Reserved;
LCID CurrentLocale;
ULONG FpSoftwareStatusRegister;
WOW64_POINTER(PVOID) ReservedForDebuggerInstrumentation[16];
WOW64_POINTER(PVOID) SystemReserved1[36];
UCHAR WorkingOnBehalfTicket[8];
NTSTATUS ExceptionCode;
WOW64_POINTER(PVOID) ActivationContextStackPointer;
WOW64_POINTER(ULONG_PTR) InstrumentationCallbackSp;
WOW64_POINTER(ULONG_PTR) InstrumentationCallbackPreviousPc;
WOW64_POINTER(ULONG_PTR) InstrumentationCallbackPreviousSp;
BOOLEAN InstrumentationCallbackDisabled;
UCHAR SpareBytes[23];
ULONG TxFsContext;
GDI_TEB_BATCH32 GdiTebBatch;
CLIENT_ID32 RealClientId;
WOW64_POINTER(HANDLE) GdiCachedProcessHandle;
ULONG GdiClientPID;
ULONG GdiClientTID;
WOW64_POINTER(PVOID) GdiThreadLocalInfo;
WOW64_POINTER(ULONG_PTR) Win32ClientInfo[62];
WOW64_POINTER(PVOID) glDispatchTable[233];
WOW64_POINTER(ULONG_PTR) glReserved1[29];
WOW64_POINTER(PVOID) glReserved2;
WOW64_POINTER(PVOID) glSectionInfo;
WOW64_POINTER(PVOID) glSection;
WOW64_POINTER(PVOID) glTable;
WOW64_POINTER(PVOID) glCurrentRC;
WOW64_POINTER(PVOID) glContext;
NTSTATUS LastStatusValue;
UNICODE_STRING32 StaticUnicodeString;
WCHAR StaticUnicodeBuffer[261];
WOW64_POINTER(PVOID) DeallocationStack;
WOW64_POINTER(PVOID) TlsSlots[64];
LIST_ENTRY32 TlsLinks;
WOW64_POINTER(PVOID) Vdm;
WOW64_POINTER(PVOID) ReservedForNtRpc;
WOW64_POINTER(PVOID) DbgSsReserved[2];
ULONG HardErrorMode;
WOW64_POINTER(PVOID) Instrumentation[9];
GUID ActivityId;
WOW64_POINTER(PVOID) SubProcessTag;
WOW64_POINTER(PVOID) PerflibData;
WOW64_POINTER(PVOID) EtwTraceData;
WOW64_POINTER(PVOID) WinSockData;
ULONG GdiBatchCount;
union
{
PROCESSOR_NUMBER CurrentIdealProcessor;
ULONG IdealProcessorValue;
struct
{
UCHAR ReservedPad0;
UCHAR ReservedPad1;
UCHAR ReservedPad2;
UCHAR IdealProcessor;
};
};
ULONG GuaranteedStackBytes;
WOW64_POINTER(PVOID) ReservedForPerf;
WOW64_POINTER(PVOID) ReservedForOle;
ULONG WaitingOnLoaderLock;
WOW64_POINTER(PVOID) SavedPriorityState;
WOW64_POINTER(ULONG_PTR) ReservedForCodeCoverage;
WOW64_POINTER(PVOID) ThreadPoolData;
WOW64_POINTER(PVOID *) TlsExpansionSlots;
ULONG MuiGeneration;
ULONG IsImpersonating;
WOW64_POINTER(PVOID) NlsCache;
WOW64_POINTER(PVOID) pShimData;
USHORT HeapVirtualAffinity;
USHORT LowFragHeapDataSlot;
WOW64_POINTER(HANDLE) CurrentTransactionHandle;
WOW64_POINTER(PTEB_ACTIVE_FRAME) ActiveFrame;
WOW64_POINTER(PVOID) FlsData;
WOW64_POINTER(PVOID) PreferredLanguages;
WOW64_POINTER(PVOID) UserPrefLanguages;
WOW64_POINTER(PVOID) MergedPrefLanguages;
ULONG MuiImpersonation;
union
{
USHORT CrossTebFlags;
USHORT SpareCrossTebBits : 16;
};
union
{
USHORT SameTebFlags;
struct
{
USHORT SafeThunkCall : 1;
USHORT InDebugPrint : 1;
USHORT HasFiberData : 1;
USHORT SkipThreadAttach : 1;
USHORT WerInShipAssertCode : 1;
USHORT RanProcessInit : 1;
USHORT ClonedThread : 1;
USHORT SuppressDebugMsg : 1;
USHORT DisableUserStackWalk : 1;
USHORT RtlExceptionAttached : 1;
USHORT InitialThread : 1;
USHORT SessionAware : 1;
USHORT LoadOwner : 1;
USHORT LoaderWorker : 1;
USHORT SpareSameTebBits : 2;
};
};
WOW64_POINTER(PVOID) TxnScopeEnterCallback;
WOW64_POINTER(PVOID) TxnScopeExitCallback;
WOW64_POINTER(PVOID) TxnScopeContext;
ULONG LockCount;
LONG WowTebOffset;
WOW64_POINTER(PVOID) ResourceRetValue;
WOW64_POINTER(PVOID) ReservedForWdf;
ULONGLONG ReservedForCrt;
GUID EffectiveContainerId;
} TEB32, *PTEB32;
C_ASSERT(FIELD_OFFSET(TEB32, ProcessEnvironmentBlock) == 0x030);
C_ASSERT(FIELD_OFFSET(TEB32, ExceptionCode) == 0x1a4);
C_ASSERT(FIELD_OFFSET(TEB32, TxFsContext) == 0x1d0);
C_ASSERT(FIELD_OFFSET(TEB32, glContext) == 0xbf0);
C_ASSERT(FIELD_OFFSET(TEB32, StaticUnicodeBuffer) == 0xc00);
C_ASSERT(FIELD_OFFSET(TEB32, TlsLinks) == 0xf10);
C_ASSERT(FIELD_OFFSET(TEB32, DbgSsReserved) == 0xf20);
C_ASSERT(FIELD_OFFSET(TEB32, ActivityId) == 0xf50);
C_ASSERT(FIELD_OFFSET(TEB32, GdiBatchCount) == 0xf70);
C_ASSERT(FIELD_OFFSET(TEB32, TlsExpansionSlots) == 0xf94);
C_ASSERT(FIELD_OFFSET(TEB32, FlsData) == 0xfb4);
C_ASSERT(FIELD_OFFSET(TEB32, MuiImpersonation) == 0xfc4);
C_ASSERT(FIELD_OFFSET(TEB32, ReservedForCrt) == 0xfe8);
C_ASSERT(FIELD_OFFSET(TEB32, EffectiveContainerId) == 0xff0);
C_ASSERT(sizeof(TEB32) == 0x1000);
// Conversion
FORCEINLINE VOID UStr32ToUStr(
_Out_ PUNICODE_STRING Destination,
_In_ PUNICODE_STRING32 Source
)
{
Destination->Length = Source->Length;
Destination->MaximumLength = Source->MaximumLength;
Destination->Buffer = (PWCH)UlongToPtr(Source->Buffer);
}
FORCEINLINE VOID UStrToUStr32(
_Out_ PUNICODE_STRING32 Destination,
_In_ PUNICODE_STRING Source
)
{
Destination->Length = Source->Length;
Destination->MaximumLength = Source->MaximumLength;
Destination->Buffer = PtrToUlong(Source->Buffer);
}
#include <ntlsa.h>
// #include <ntsam.h>
#define SAM_MAXIMUM_LOOKUP_COUNT (1000)
#define SAM_MAXIMUM_LOOKUP_LENGTH (32000)
#define SAM_MAX_PASSWORD_LENGTH (256)
#define SAM_PASSWORD_ENCRYPTION_SALT_LEN (16)
typedef PVOID SAM_HANDLE, *PSAM_HANDLE;
typedef ULONG SAM_ENUMERATE_HANDLE, *PSAM_ENUMERATE_HANDLE;
typedef struct _SAM_RID_ENUMERATION
{
ULONG RelativeId;
UNICODE_STRING Name;
} SAM_RID_ENUMERATION, *PSAM_RID_ENUMERATION;
typedef struct _SAM_SID_ENUMERATION
{
PSID Sid;
UNICODE_STRING Name;
} SAM_SID_ENUMERATION, *PSAM_SID_ENUMERATION;
typedef struct _SAM_BYTE_ARRAY
{
ULONG Size;
_Field_size_bytes_(Size) PUCHAR Data;
} SAM_BYTE_ARRAY, *PSAM_BYTE_ARRAY;
typedef struct _SAM_BYTE_ARRAY_32K
{
ULONG Size;
_Field_size_bytes_(Size) PUCHAR Data;
} SAM_BYTE_ARRAY_32K, *PSAM_BYTE_ARRAY_32K;
typedef SAM_BYTE_ARRAY_32K SAM_SHELL_OBJECT_PROPERTIES, *PSAM_SHELL_OBJECT_PROPERTIES;
// Basic
NTSTATUS
NTAPI
SamFreeMemory(
_In_ PVOID Buffer
);
NTSTATUS
NTAPI
SamCloseHandle(
_In_ SAM_HANDLE SamHandle
);
_Check_return_
NTSTATUS
NTAPI
SamSetSecurityObject(
_In_ SAM_HANDLE ObjectHandle,
_In_ SECURITY_INFORMATION SecurityInformation,
_In_ PSECURITY_DESCRIPTOR SecurityDescriptor
);
_Check_return_
NTSTATUS
NTAPI
SamQuerySecurityObject(
_In_ SAM_HANDLE ObjectHandle,
_In_ SECURITY_INFORMATION SecurityInformation,
_Outptr_ PSECURITY_DESCRIPTOR *SecurityDescriptor
);
_Check_return_
NTSTATUS
NTAPI
SamRidToSid(
_In_ SAM_HANDLE ObjectHandle,
_In_ ULONG Rid,
_Outptr_ PSID *Sid
);
// Server
#define SAM_SERVER_CONNECT 0x0001
#define SAM_SERVER_SHUTDOWN 0x0002
#define SAM_SERVER_INITIALIZE 0x0004
#define SAM_SERVER_CREATE_DOMAIN 0x0008
#define SAM_SERVER_ENUMERATE_DOMAINS 0x0010
#define SAM_SERVER_LOOKUP_DOMAIN 0x0020
#define SAM_SERVER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
SAM_SERVER_CONNECT | \
SAM_SERVER_INITIALIZE | \
SAM_SERVER_CREATE_DOMAIN | \
SAM_SERVER_SHUTDOWN | \
SAM_SERVER_ENUMERATE_DOMAINS | \
SAM_SERVER_LOOKUP_DOMAIN)
#define SAM_SERVER_READ (STANDARD_RIGHTS_READ | \
SAM_SERVER_ENUMERATE_DOMAINS)
#define SAM_SERVER_WRITE (STANDARD_RIGHTS_WRITE | \
SAM_SERVER_INITIALIZE | \
SAM_SERVER_CREATE_DOMAIN | \
SAM_SERVER_SHUTDOWN)
#define SAM_SERVER_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
SAM_SERVER_CONNECT | \
SAM_SERVER_LOOKUP_DOMAIN)
// Functions
_Check_return_
NTSTATUS
NTAPI
SamConnect(
_In_opt_ PUNICODE_STRING ServerName,
_Out_ PSAM_HANDLE ServerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
_Check_return_
NTSTATUS
NTAPI
SamShutdownSamServer(
_In_ SAM_HANDLE ServerHandle
);
// Domain
#define DOMAIN_READ_PASSWORD_PARAMETERS 0x0001
#define DOMAIN_WRITE_PASSWORD_PARAMS 0x0002
#define DOMAIN_READ_OTHER_PARAMETERS 0x0004
#define DOMAIN_WRITE_OTHER_PARAMETERS 0x0008
#define DOMAIN_CREATE_USER 0x0010
#define DOMAIN_CREATE_GROUP 0x0020
#define DOMAIN_CREATE_ALIAS 0x0040
#define DOMAIN_GET_ALIAS_MEMBERSHIP 0x0080
#define DOMAIN_LIST_ACCOUNTS 0x0100
#define DOMAIN_LOOKUP 0x0200
#define DOMAIN_ADMINISTER_SERVER 0x0400
#define DOMAIN_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
DOMAIN_READ_OTHER_PARAMETERS | \
DOMAIN_WRITE_OTHER_PARAMETERS | \
DOMAIN_WRITE_PASSWORD_PARAMS | \
DOMAIN_CREATE_USER | \
DOMAIN_CREATE_GROUP | \
DOMAIN_CREATE_ALIAS | \
DOMAIN_GET_ALIAS_MEMBERSHIP | \
DOMAIN_LIST_ACCOUNTS | \
DOMAIN_READ_PASSWORD_PARAMETERS | \
DOMAIN_LOOKUP | \
DOMAIN_ADMINISTER_SERVER)
#define DOMAIN_READ (STANDARD_RIGHTS_READ | \
DOMAIN_GET_ALIAS_MEMBERSHIP | \
DOMAIN_READ_OTHER_PARAMETERS)
#define DOMAIN_WRITE (STANDARD_RIGHTS_WRITE | \
DOMAIN_WRITE_OTHER_PARAMETERS | \
DOMAIN_WRITE_PASSWORD_PARAMS | \
DOMAIN_CREATE_USER | \
DOMAIN_CREATE_GROUP | \
DOMAIN_CREATE_ALIAS | \
DOMAIN_ADMINISTER_SERVER)
#define DOMAIN_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
DOMAIN_READ_PASSWORD_PARAMETERS | \
DOMAIN_LIST_ACCOUNTS | \
DOMAIN_LOOKUP)
#define DOMAIN_PROMOTION_INCREMENT { 0x0, 0x10 }
#define DOMAIN_PROMOTION_MASK { 0x0, 0xfffffff0 }
// SamQueryInformationDomain/SamSetInformationDomain types
typedef enum _DOMAIN_INFORMATION_CLASS
{
DomainPasswordInformation = 1,
DomainGeneralInformation,
DomainLogoffInformation,
DomainOemInformation,
DomainNameInformation,
DomainReplicationInformation,
DomainServerRoleInformation,
DomainModifiedInformation,
DomainStateInformation,
DomainUasInformation,
DomainGeneralInformation2,
DomainLockoutInformation,
DomainModifiedInformation2
} DOMAIN_INFORMATION_CLASS;
typedef enum _DOMAIN_SERVER_ENABLE_STATE
{
DomainServerEnabled = 1,
DomainServerDisabled
} DOMAIN_SERVER_ENABLE_STATE, *PDOMAIN_SERVER_ENABLE_STATE;
typedef enum _DOMAIN_SERVER_ROLE
{
DomainServerRoleBackup = 2,
DomainServerRolePrimary
} DOMAIN_SERVER_ROLE, *PDOMAIN_SERVER_ROLE;
#include <pshpack4.h>
typedef struct _DOMAIN_GENERAL_INFORMATION
{
LARGE_INTEGER ForceLogoff;
UNICODE_STRING OemInformation;
UNICODE_STRING DomainName;
UNICODE_STRING ReplicaSourceNodeName;
LARGE_INTEGER DomainModifiedCount;
DOMAIN_SERVER_ENABLE_STATE DomainServerState;
DOMAIN_SERVER_ROLE DomainServerRole;
BOOLEAN UasCompatibilityRequired;
ULONG UserCount;
ULONG GroupCount;
ULONG AliasCount;
} DOMAIN_GENERAL_INFORMATION, *PDOMAIN_GENERAL_INFORMATION;
#include <poppack.h>
#include <pshpack4.h>
typedef struct _DOMAIN_GENERAL_INFORMATION2
{
DOMAIN_GENERAL_INFORMATION I1;
LARGE_INTEGER LockoutDuration; // delta time
LARGE_INTEGER LockoutObservationWindow; // delta time
USHORT LockoutThreshold;
} DOMAIN_GENERAL_INFORMATION2, *PDOMAIN_GENERAL_INFORMATION2;
#include <poppack.h>
typedef struct _DOMAIN_UAS_INFORMATION
{
BOOLEAN UasCompatibilityRequired;
} DOMAIN_UAS_INFORMATION;
#ifndef _DOMAIN_PASSWORD_INFORMATION_DEFINED // defined in ntsecapi.h
#define _DOMAIN_PASSWORD_INFORMATION_DEFINED
typedef struct _DOMAIN_PASSWORD_INFORMATION
{
USHORT MinPasswordLength;
USHORT PasswordHistoryLength;
ULONG PasswordProperties;
LARGE_INTEGER MaxPasswordAge;
LARGE_INTEGER MinPasswordAge;
} DOMAIN_PASSWORD_INFORMATION, *PDOMAIN_PASSWORD_INFORMATION;
// PasswordProperties flags
#define DOMAIN_PASSWORD_COMPLEX 0x00000001L
#define DOMAIN_PASSWORD_NO_ANON_CHANGE 0x00000002L
#define DOMAIN_PASSWORD_NO_CLEAR_CHANGE 0x00000004L
#define DOMAIN_LOCKOUT_ADMINS 0x00000008L
#define DOMAIN_PASSWORD_STORE_CLEARTEXT 0x00000010L
#define DOMAIN_REFUSE_PASSWORD_CHANGE 0x00000020L
#define DOMAIN_NO_LM_OWF_CHANGE 0x00000040L
#endif
typedef enum _DOMAIN_PASSWORD_CONSTRUCTION
{
DomainPasswordSimple = 1,
DomainPasswordComplex
} DOMAIN_PASSWORD_CONSTRUCTION;
typedef struct _DOMAIN_LOGOFF_INFORMATION
{
LARGE_INTEGER ForceLogoff;
} DOMAIN_LOGOFF_INFORMATION, *PDOMAIN_LOGOFF_INFORMATION;
typedef struct _DOMAIN_OEM_INFORMATION
{
UNICODE_STRING OemInformation;
} DOMAIN_OEM_INFORMATION, *PDOMAIN_OEM_INFORMATION;
typedef struct _DOMAIN_NAME_INFORMATION
{
UNICODE_STRING DomainName;
} DOMAIN_NAME_INFORMATION, *PDOMAIN_NAME_INFORMATION;
typedef struct _DOMAIN_SERVER_ROLE_INFORMATION
{
DOMAIN_SERVER_ROLE DomainServerRole;
} DOMAIN_SERVER_ROLE_INFORMATION, *PDOMAIN_SERVER_ROLE_INFORMATION;
typedef struct _DOMAIN_REPLICATION_INFORMATION
{
UNICODE_STRING ReplicaSourceNodeName;
} DOMAIN_REPLICATION_INFORMATION, *PDOMAIN_REPLICATION_INFORMATION;
typedef struct _DOMAIN_MODIFIED_INFORMATION
{
LARGE_INTEGER DomainModifiedCount;
LARGE_INTEGER CreationTime;
} DOMAIN_MODIFIED_INFORMATION, *PDOMAIN_MODIFIED_INFORMATION;
typedef struct _DOMAIN_MODIFIED_INFORMATION2
{
LARGE_INTEGER DomainModifiedCount;
LARGE_INTEGER CreationTime;
LARGE_INTEGER ModifiedCountAtLastPromotion;
} DOMAIN_MODIFIED_INFORMATION2, *PDOMAIN_MODIFIED_INFORMATION2;
typedef struct _DOMAIN_STATE_INFORMATION
{
DOMAIN_SERVER_ENABLE_STATE DomainServerState;
} DOMAIN_STATE_INFORMATION, *PDOMAIN_STATE_INFORMATION;
typedef struct _DOMAIN_LOCKOUT_INFORMATION
{
LARGE_INTEGER LockoutDuration; // delta time
LARGE_INTEGER LockoutObservationWindow; // delta time
USHORT LockoutThreshold; // zero means no lockout
} DOMAIN_LOCKOUT_INFORMATION, *PDOMAIN_LOCKOUT_INFORMATION;
// SamQueryDisplayInformation types
typedef enum _DOMAIN_DISPLAY_INFORMATION
{
DomainDisplayUser = 1,
DomainDisplayMachine,
DomainDisplayGroup,
DomainDisplayOemUser,
DomainDisplayOemGroup,
DomainDisplayServer
} DOMAIN_DISPLAY_INFORMATION, *PDOMAIN_DISPLAY_INFORMATION;
typedef struct _DOMAIN_DISPLAY_USER
{
ULONG Index;
ULONG Rid;
ULONG AccountControl;
UNICODE_STRING LogonName;
UNICODE_STRING AdminComment;
UNICODE_STRING FullName;
} DOMAIN_DISPLAY_USER, *PDOMAIN_DISPLAY_USER;
typedef struct _DOMAIN_DISPLAY_MACHINE
{
ULONG Index;
ULONG Rid;
ULONG AccountControl;
UNICODE_STRING Machine;
UNICODE_STRING Comment;
} DOMAIN_DISPLAY_MACHINE, *PDOMAIN_DISPLAY_MACHINE;
typedef struct _DOMAIN_DISPLAY_GROUP
{
ULONG Index;
ULONG Rid;
ULONG Attributes;
UNICODE_STRING Group;
UNICODE_STRING Comment;
} DOMAIN_DISPLAY_GROUP, *PDOMAIN_DISPLAY_GROUP;
typedef struct _DOMAIN_DISPLAY_OEM_USER
{
ULONG Index;
OEM_STRING User;
} DOMAIN_DISPLAY_OEM_USER, *PDOMAIN_DISPLAY_OEM_USER;
typedef struct _DOMAIN_DISPLAY_OEM_GROUP
{
ULONG Index;
OEM_STRING Group;
} DOMAIN_DISPLAY_OEM_GROUP, *PDOMAIN_DISPLAY_OEM_GROUP;
// SamQueryLocalizableAccountsInDomain types
typedef enum _DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION
{
DomainLocalizableAccountsBasic = 1,
} DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION, *PDOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION;
typedef struct _DOMAIN_LOCALIZABLE_ACCOUNTS_ENTRY
{
ULONG Rid;
SID_NAME_USE Use;
UNICODE_STRING Name;
UNICODE_STRING AdminComment;
} DOMAIN_LOCALIZABLE_ACCOUNT_ENTRY, *PDOMAIN_LOCALIZABLE_ACCOUNT_ENTRY;
typedef struct _DOMAIN_LOCALIZABLE_ACCOUNTS
{
ULONG Count;
_Field_size_(Count) DOMAIN_LOCALIZABLE_ACCOUNT_ENTRY *Entries;
} DOMAIN_LOCALIZABLE_ACCOUNTS_BASIC, *PDOMAIN_LOCALIZABLE_ACCOUNTS_BASIC;
typedef union _DOMAIN_LOCALIZABLE_INFO_BUFFER
{
DOMAIN_LOCALIZABLE_ACCOUNTS_BASIC Basic;
} DOMAIN_LOCALIZABLE_ACCOUNTS_INFO_BUFFER, *PDOMAIN_LOCALIZABLE_ACCOUNTS_INFO_BUFFER;
// Functions
_Check_return_
NTSTATUS
NTAPI
SamLookupDomainInSamServer(
_In_ SAM_HANDLE ServerHandle,
_In_ PUNICODE_STRING Name,
_Outptr_ PSID *DomainId
);
_Check_return_
NTSTATUS
NTAPI
SamEnumerateDomainsInSamServer(
_In_ SAM_HANDLE ServerHandle,
_Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
_Outptr_ PVOID *Buffer, // PSAM_SID_ENUMERATION *Buffer
_In_ ULONG PreferedMaximumLength,
_Out_ PULONG CountReturned
);
_Check_return_
NTSTATUS
NTAPI
SamOpenDomain(
_In_ SAM_HANDLE ServerHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ PSID DomainId,
_Out_ PSAM_HANDLE DomainHandle
);
_Check_return_
NTSTATUS
NTAPI
SamQueryInformationDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ DOMAIN_INFORMATION_CLASS DomainInformationClass,
_Outptr_ PVOID *Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamSetInformationDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ DOMAIN_INFORMATION_CLASS DomainInformationClass,
_In_ PVOID DomainInformation
);
_Check_return_
NTSTATUS
NTAPI
SamLookupNamesInDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ ULONG Count,
_In_reads_(Count) PUNICODE_STRING Names,
_Out_ _Deref_post_count_(Count) PULONG *RelativeIds,
_Out_ _Deref_post_count_(Count) PSID_NAME_USE *Use
);
_Check_return_
NTSTATUS
NTAPI
SamLookupIdsInDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ ULONG Count,
_In_reads_(Count) PULONG RelativeIds,
_Out_ _Deref_post_count_(Count) PUNICODE_STRING *Names,
_Out_ _Deref_post_opt_count_(Count) PSID_NAME_USE *Use
);
_Check_return_
NTSTATUS
NTAPI
SamRemoveMemberFromForeignDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ PSID MemberId
);
_Check_return_
NTSTATUS
NTAPI
SamQueryLocalizableAccountsInDomain(
_In_ SAM_HANDLE Domain,
_In_ ULONG Flags,
_In_ ULONG LanguageId,
_In_ DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION Class,
_Outptr_ PVOID *Buffer
);
// Group
#define GROUP_READ_INFORMATION 0x0001
#define GROUP_WRITE_ACCOUNT 0x0002
#define GROUP_ADD_MEMBER 0x0004
#define GROUP_REMOVE_MEMBER 0x0008
#define GROUP_LIST_MEMBERS 0x0010
#define GROUP_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
GROUP_LIST_MEMBERS | \
GROUP_WRITE_ACCOUNT | \
GROUP_ADD_MEMBER | \
GROUP_REMOVE_MEMBER | \
GROUP_READ_INFORMATION)
#define GROUP_READ (STANDARD_RIGHTS_READ | \
GROUP_LIST_MEMBERS)
#define GROUP_WRITE (STANDARD_RIGHTS_WRITE | \
GROUP_WRITE_ACCOUNT | \
GROUP_ADD_MEMBER | \
GROUP_REMOVE_MEMBER)
#define GROUP_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
GROUP_READ_INFORMATION)
typedef struct _GROUP_MEMBERSHIP
{
ULONG RelativeId;
ULONG Attributes;
} GROUP_MEMBERSHIP, *PGROUP_MEMBERSHIP;
// SamQueryInformationGroup/SamSetInformationGroup types
typedef enum _GROUP_INFORMATION_CLASS
{
GroupGeneralInformation = 1,
GroupNameInformation,
GroupAttributeInformation,
GroupAdminCommentInformation,
GroupReplicationInformation
} GROUP_INFORMATION_CLASS;
typedef struct _GROUP_GENERAL_INFORMATION
{
UNICODE_STRING Name;
ULONG Attributes;
ULONG MemberCount;
UNICODE_STRING AdminComment;
} GROUP_GENERAL_INFORMATION, *PGROUP_GENERAL_INFORMATION;
typedef struct _GROUP_NAME_INFORMATION
{
UNICODE_STRING Name;
} GROUP_NAME_INFORMATION, *PGROUP_NAME_INFORMATION;
typedef struct _GROUP_ATTRIBUTE_INFORMATION
{
ULONG Attributes;
} GROUP_ATTRIBUTE_INFORMATION, *PGROUP_ATTRIBUTE_INFORMATION;
typedef struct _GROUP_ADM_COMMENT_INFORMATION
{
UNICODE_STRING AdminComment;
} GROUP_ADM_COMMENT_INFORMATION, *PGROUP_ADM_COMMENT_INFORMATION;
// Functions
_Check_return_
NTSTATUS
NTAPI
SamEnumerateGroupsInDomain(
_In_ SAM_HANDLE DomainHandle,
_Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
_Outptr_ PVOID *Buffer, // PSAM_RID_ENUMERATION *
_In_ ULONG PreferedMaximumLength,
_Out_ PULONG CountReturned
);
_Check_return_
NTSTATUS
NTAPI
SamCreateGroupInDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ PUNICODE_STRING AccountName,
_In_ ACCESS_MASK DesiredAccess,
_Out_ PSAM_HANDLE GroupHandle,
_Out_ PULONG RelativeId
);
_Check_return_
NTSTATUS
NTAPI
SamOpenGroup(
_In_ SAM_HANDLE DomainHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG GroupId,
_Out_ PSAM_HANDLE GroupHandle
);
_Check_return_
NTSTATUS
NTAPI
SamDeleteGroup(
_In_ SAM_HANDLE GroupHandle
);
_Check_return_
NTSTATUS
NTAPI
SamQueryInformationGroup(
_In_ SAM_HANDLE GroupHandle,
_In_ GROUP_INFORMATION_CLASS GroupInformationClass,
_Outptr_ PVOID *Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamSetInformationGroup(
_In_ SAM_HANDLE GroupHandle,
_In_ GROUP_INFORMATION_CLASS GroupInformationClass,
_In_ PVOID Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamAddMemberToGroup(
_In_ SAM_HANDLE GroupHandle,
_In_ ULONG MemberId,
_In_ ULONG Attributes
);
_Check_return_
NTSTATUS
NTAPI
SamRemoveMemberFromGroup(
_In_ SAM_HANDLE GroupHandle,
_In_ ULONG MemberId
);
_Check_return_
NTSTATUS
NTAPI
SamGetMembersInGroup(
_In_ SAM_HANDLE GroupHandle,
_Out_ _Deref_post_count_(*MemberCount) PULONG *MemberIds,
_Out_ _Deref_post_count_(*MemberCount) PULONG *Attributes,
_Out_ PULONG MemberCount
);
_Check_return_
NTSTATUS
NTAPI
SamSetMemberAttributesOfGroup(
_In_ SAM_HANDLE GroupHandle,
_In_ ULONG MemberId,
_In_ ULONG Attributes
);
// Alias
#define ALIAS_ADD_MEMBER 0x0001
#define ALIAS_REMOVE_MEMBER 0x0002
#define ALIAS_LIST_MEMBERS 0x0004
#define ALIAS_READ_INFORMATION 0x0008
#define ALIAS_WRITE_ACCOUNT 0x0010
#define ALIAS_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
ALIAS_READ_INFORMATION | \
ALIAS_WRITE_ACCOUNT | \
ALIAS_LIST_MEMBERS | \
ALIAS_ADD_MEMBER | \
ALIAS_REMOVE_MEMBER)
#define ALIAS_READ (STANDARD_RIGHTS_READ | \
ALIAS_LIST_MEMBERS)
#define ALIAS_WRITE (STANDARD_RIGHTS_WRITE | \
ALIAS_WRITE_ACCOUNT | \
ALIAS_ADD_MEMBER | \
ALIAS_REMOVE_MEMBER)
#define ALIAS_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
ALIAS_READ_INFORMATION)
// SamQueryInformationAlias/SamSetInformationAlias types
typedef enum _ALIAS_INFORMATION_CLASS
{
AliasGeneralInformation = 1,
AliasNameInformation,
AliasAdminCommentInformation,
AliasReplicationInformation,
AliasExtendedInformation,
} ALIAS_INFORMATION_CLASS;
typedef struct _ALIAS_GENERAL_INFORMATION
{
UNICODE_STRING Name;
ULONG MemberCount;
UNICODE_STRING AdminComment;
} ALIAS_GENERAL_INFORMATION, *PALIAS_GENERAL_INFORMATION;
typedef struct _ALIAS_NAME_INFORMATION
{
UNICODE_STRING Name;
} ALIAS_NAME_INFORMATION, *PALIAS_NAME_INFORMATION;
typedef struct _ALIAS_ADM_COMMENT_INFORMATION
{
UNICODE_STRING AdminComment;
} ALIAS_ADM_COMMENT_INFORMATION, *PALIAS_ADM_COMMENT_INFORMATION;
#define ALIAS_ALL_NAME (0x00000001L)
#define ALIAS_ALL_MEMBER_COUNT (0x00000002L)
#define ALIAS_ALL_ADMIN_COMMENT (0x00000004L)
#define ALIAS_ALL_SHELL_ADMIN_OBJECT_PROPERTIES (0x00000008L)
typedef struct _ALIAS_EXTENDED_INFORMATION
{
ULONG WhichFields;
SAM_SHELL_OBJECT_PROPERTIES ShellAdminObjectProperties;
} ALIAS_EXTENDED_INFORMATION, *PALIAS_EXTENDED_INFORMATION;
// Functions
_Check_return_
NTSTATUS
NTAPI
SamEnumerateAliasesInDomain(
_In_ SAM_HANDLE DomainHandle,
_Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
_Outptr_ PVOID *Buffer, // PSAM_RID_ENUMERATION *Buffer
_In_ ULONG PreferedMaximumLength,
_Out_ PULONG CountReturned
);
_Check_return_
NTSTATUS
NTAPI
SamCreateAliasInDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ PUNICODE_STRING AccountName,
_In_ ACCESS_MASK DesiredAccess,
_Out_ PSAM_HANDLE AliasHandle,
_Out_ PULONG RelativeId
);
_Check_return_
NTSTATUS
NTAPI
SamOpenAlias(
_In_ SAM_HANDLE DomainHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG AliasId,
_Out_ PSAM_HANDLE AliasHandle
);
_Check_return_
NTSTATUS
NTAPI
SamDeleteAlias(
_In_ SAM_HANDLE AliasHandle
);
_Check_return_
NTSTATUS
NTAPI
SamQueryInformationAlias(
_In_ SAM_HANDLE AliasHandle,
_In_ ALIAS_INFORMATION_CLASS AliasInformationClass,
_Outptr_ PVOID *Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamSetInformationAlias(
_In_ SAM_HANDLE AliasHandle,
_In_ ALIAS_INFORMATION_CLASS AliasInformationClass,
_In_ PVOID Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamAddMemberToAlias(
_In_ SAM_HANDLE AliasHandle,
_In_ PSID MemberId
);
_Check_return_
NTSTATUS
NTAPI
SamAddMultipleMembersToAlias(
_In_ SAM_HANDLE AliasHandle,
_In_reads_(MemberCount) PSID *MemberIds,
_In_ ULONG MemberCount
);
_Check_return_
NTSTATUS
NTAPI
SamRemoveMemberFromAlias(
_In_ SAM_HANDLE AliasHandle,
_In_ PSID MemberId
);
_Check_return_
NTSTATUS
NTAPI
SamRemoveMultipleMembersFromAlias(
_In_ SAM_HANDLE AliasHandle,
_In_reads_(MemberCount) PSID *MemberIds,
_In_ ULONG MemberCount
);
_Check_return_
NTSTATUS
NTAPI
SamGetMembersInAlias(
_In_ SAM_HANDLE AliasHandle,
_Out_ _Deref_post_count_(*MemberCount) PSID **MemberIds,
_Out_ PULONG MemberCount
);
_Check_return_
NTSTATUS
NTAPI
SamGetAliasMembership(
_In_ SAM_HANDLE DomainHandle,
_In_ ULONG PassedCount,
_In_reads_(PassedCount) PSID *Sids,
_Out_ PULONG MembershipCount,
_Out_ _Deref_post_count_(*MembershipCount) PULONG *Aliases
);
// Group types
#define GROUP_TYPE_BUILTIN_LOCAL_GROUP 0x00000001
#define GROUP_TYPE_ACCOUNT_GROUP 0x00000002
#define GROUP_TYPE_RESOURCE_GROUP 0x00000004
#define GROUP_TYPE_UNIVERSAL_GROUP 0x00000008
#define GROUP_TYPE_APP_BASIC_GROUP 0x00000010
#define GROUP_TYPE_APP_QUERY_GROUP 0x00000020
#define GROUP_TYPE_SECURITY_ENABLED 0x80000000
#define GROUP_TYPE_RESOURCE_BEHAVOIR (GROUP_TYPE_RESOURCE_GROUP | \
GROUP_TYPE_APP_BASIC_GROUP | \
GROUP_TYPE_APP_QUERY_GROUP)
// User
#define USER_READ_GENERAL 0x0001
#define USER_READ_PREFERENCES 0x0002
#define USER_WRITE_PREFERENCES 0x0004
#define USER_READ_LOGON 0x0008
#define USER_READ_ACCOUNT 0x0010
#define USER_WRITE_ACCOUNT 0x0020
#define USER_CHANGE_PASSWORD 0x0040
#define USER_FORCE_PASSWORD_CHANGE 0x0080
#define USER_LIST_GROUPS 0x0100
#define USER_READ_GROUP_INFORMATION 0x0200
#define USER_WRITE_GROUP_INFORMATION 0x0400
#define USER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
USER_READ_PREFERENCES | \
USER_READ_LOGON | \
USER_LIST_GROUPS | \
USER_READ_GROUP_INFORMATION | \
USER_WRITE_PREFERENCES | \
USER_CHANGE_PASSWORD | \
USER_FORCE_PASSWORD_CHANGE | \
USER_READ_GENERAL | \
USER_READ_ACCOUNT | \
USER_WRITE_ACCOUNT | \
USER_WRITE_GROUP_INFORMATION)
#define USER_READ (STANDARD_RIGHTS_READ | \
USER_READ_PREFERENCES | \
USER_READ_LOGON | \
USER_READ_ACCOUNT | \
USER_LIST_GROUPS | \
USER_READ_GROUP_INFORMATION)
#define USER_WRITE (STANDARD_RIGHTS_WRITE | \
USER_WRITE_PREFERENCES | \
USER_CHANGE_PASSWORD)
#define USER_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
USER_READ_GENERAL | \
USER_CHANGE_PASSWORD)
// User account control flags
#define USER_ACCOUNT_DISABLED (0x00000001)
#define USER_HOME_DIRECTORY_REQUIRED (0x00000002)
#define USER_PASSWORD_NOT_REQUIRED (0x00000004)
#define USER_TEMP_DUPLICATE_ACCOUNT (0x00000008)
#define USER_NORMAL_ACCOUNT (0x00000010)
#define USER_MNS_LOGON_ACCOUNT (0x00000020)
#define USER_INTERDOMAIN_TRUST_ACCOUNT (0x00000040)
#define USER_WORKSTATION_TRUST_ACCOUNT (0x00000080)
#define USER_SERVER_TRUST_ACCOUNT (0x00000100)
#define USER_DONT_EXPIRE_PASSWORD (0x00000200)
#define USER_ACCOUNT_AUTO_LOCKED (0x00000400)
#define USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED (0x00000800)
#define USER_SMARTCARD_REQUIRED (0x00001000)
#define USER_TRUSTED_FOR_DELEGATION (0x00002000)
#define USER_NOT_DELEGATED (0x00004000)
#define USER_USE_DES_KEY_ONLY (0x00008000)
#define USER_DONT_REQUIRE_PREAUTH (0x00010000)
#define USER_PASSWORD_EXPIRED (0x00020000)
#define USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION (0x00040000)
#define USER_NO_AUTH_DATA_REQUIRED (0x00080000)
#define USER_PARTIAL_SECRETS_ACCOUNT (0x00100000)
#define USER_USE_AES_KEYS (0x00200000) // not used
#define NEXT_FREE_ACCOUNT_CONTROL_BIT (USER_USE_AES_KEYS << 1)
#define USER_MACHINE_ACCOUNT_MASK ( \
USER_INTERDOMAIN_TRUST_ACCOUNT | \
USER_WORKSTATION_TRUST_ACCOUNT | \
USER_SERVER_TRUST_ACCOUNT \
)
#define USER_ACCOUNT_TYPE_MASK ( \
USER_TEMP_DUPLICATE_ACCOUNT | \
USER_NORMAL_ACCOUNT | \
USER_MACHINE_ACCOUNT_MASK \
)
#define USER_COMPUTED_ACCOUNT_CONTROL_BITS ( \
USER_ACCOUNT_AUTO_LOCKED | \
USER_PASSWORD_EXPIRED \
)
// Logon times may be expressed in day, hour, or minute granularity.
#define SAM_DAYS_PER_WEEK (7)
#define SAM_HOURS_PER_WEEK (24 * SAM_DAYS_PER_WEEK)
#define SAM_MINUTES_PER_WEEK (60 * SAM_HOURS_PER_WEEK)
typedef struct _LOGON_HOURS
{
USHORT UnitsPerWeek;
// UnitsPerWeek is the number of equal length time units the week is
// divided into. This value is used to compute the length of the bit
// string in logon_hours. Must be less than or equal to
// SAM_UNITS_PER_WEEK (10080) for this release.
//
// LogonHours is a bit map of valid logon times. Each bit represents
// a unique division in a week. The largest bit map supported is 1260
// bytes (10080 bits), which represents minutes per week. In this case
// the first bit (bit 0, byte 0) is Sunday, 00:00:00 - 00-00:59; bit 1,
// byte 0 is Sunday, 00:01:00 - 00:01:59, etc. A NULL pointer means
// DONT_CHANGE for SamSetInformationUser() calls.
PUCHAR LogonHours;
} LOGON_HOURS, *PLOGON_HOURS;
typedef struct _SR_SECURITY_DESCRIPTOR
{
ULONG Length;
PUCHAR SecurityDescriptor;
} SR_SECURITY_DESCRIPTOR, *PSR_SECURITY_DESCRIPTOR;
// SamQueryInformationUser/SamSetInformationUser types
typedef enum _USER_INFORMATION_CLASS
{
UserGeneralInformation = 1,
UserPreferencesInformation,
UserLogonInformation,
UserLogonHoursInformation,
UserAccountInformation,
UserNameInformation,
UserAccountNameInformation,
UserFullNameInformation,
UserPrimaryGroupInformation,
UserHomeInformation,
UserScriptInformation,
UserProfileInformation,
UserAdminCommentInformation,
UserWorkStationsInformation,
UserSetPasswordInformation,
UserControlInformation,
UserExpiresInformation,
UserInternal1Information,
UserInternal2Information,
UserParametersInformation,
UserAllInformation,
UserInternal3Information,
UserInternal4Information,
UserInternal5Information,
UserInternal4InformationNew,
UserInternal5InformationNew,
UserInternal6Information,
UserExtendedInformation,
UserLogonUIInformation
} USER_INFORMATION_CLASS, *PUSER_INFORMATION_CLASS;
#include <pshpack4.h>
typedef struct _USER_ALL_INFORMATION
{
LARGE_INTEGER LastLogon;
LARGE_INTEGER LastLogoff;
LARGE_INTEGER PasswordLastSet;
LARGE_INTEGER AccountExpires;
LARGE_INTEGER PasswordCanChange;
LARGE_INTEGER PasswordMustChange;
UNICODE_STRING UserName;
UNICODE_STRING FullName;
UNICODE_STRING HomeDirectory;
UNICODE_STRING HomeDirectoryDrive;
UNICODE_STRING ScriptPath;
UNICODE_STRING ProfilePath;
UNICODE_STRING AdminComment;
UNICODE_STRING WorkStations;
UNICODE_STRING UserComment;
UNICODE_STRING Parameters;
UNICODE_STRING LmPassword;
UNICODE_STRING NtPassword;
UNICODE_STRING PrivateData;
SR_SECURITY_DESCRIPTOR SecurityDescriptor;
ULONG UserId;
ULONG PrimaryGroupId;
ULONG UserAccountControl;
ULONG WhichFields;
LOGON_HOURS LogonHours;
USHORT BadPasswordCount;
USHORT LogonCount;
USHORT CountryCode;
USHORT CodePage;
BOOLEAN LmPasswordPresent;
BOOLEAN NtPasswordPresent;
BOOLEAN PasswordExpired;
BOOLEAN PrivateDataSensitive;
} USER_ALL_INFORMATION, *PUSER_ALL_INFORMATION;
#include <poppack.h>
// Flags for WhichFields in USER_ALL_INFORMATION
#define USER_ALL_USERNAME 0x00000001
#define USER_ALL_FULLNAME 0x00000002
#define USER_ALL_USERID 0x00000004
#define USER_ALL_PRIMARYGROUPID 0x00000008
#define USER_ALL_ADMINCOMMENT 0x00000010
#define USER_ALL_USERCOMMENT 0x00000020
#define USER_ALL_HOMEDIRECTORY 0x00000040
#define USER_ALL_HOMEDIRECTORYDRIVE 0x00000080
#define USER_ALL_SCRIPTPATH 0x00000100
#define USER_ALL_PROFILEPATH 0x00000200
#define USER_ALL_WORKSTATIONS 0x00000400
#define USER_ALL_LASTLOGON 0x00000800
#define USER_ALL_LASTLOGOFF 0x00001000
#define USER_ALL_LOGONHOURS 0x00002000
#define USER_ALL_BADPASSWORDCOUNT 0x00004000
#define USER_ALL_LOGONCOUNT 0x00008000
#define USER_ALL_PASSWORDCANCHANGE 0x00010000
#define USER_ALL_PASSWORDMUSTCHANGE 0x00020000
#define USER_ALL_PASSWORDLASTSET 0x00040000
#define USER_ALL_ACCOUNTEXPIRES 0x00080000
#define USER_ALL_USERACCOUNTCONTROL 0x00100000
#define USER_ALL_PARAMETERS 0x00200000
#define USER_ALL_COUNTRYCODE 0x00400000
#define USER_ALL_CODEPAGE 0x00800000
#define USER_ALL_NTPASSWORDPRESENT 0x01000000 // field AND boolean
#define USER_ALL_LMPASSWORDPRESENT 0x02000000 // field AND boolean
#define USER_ALL_PRIVATEDATA 0x04000000 // field AND boolean
#define USER_ALL_PASSWORDEXPIRED 0x08000000
#define USER_ALL_SECURITYDESCRIPTOR 0x10000000
#define USER_ALL_OWFPASSWORD 0x20000000 // boolean
#define USER_ALL_UNDEFINED_MASK 0xc0000000
// Fields that require USER_READ_GENERAL access to read.
#define USER_ALL_READ_GENERAL_MASK (USER_ALL_USERNAME | \
USER_ALL_FULLNAME | \
USER_ALL_USERID | \
USER_ALL_PRIMARYGROUPID | \
USER_ALL_ADMINCOMMENT | \
USER_ALL_USERCOMMENT)
// Fields that require USER_READ_LOGON access to read.
#define USER_ALL_READ_LOGON_MASK (USER_ALL_HOMEDIRECTORY | \
USER_ALL_HOMEDIRECTORYDRIVE | \
USER_ALL_SCRIPTPATH | \
USER_ALL_PROFILEPATH | \
USER_ALL_WORKSTATIONS | \
USER_ALL_LASTLOGON | \
USER_ALL_LASTLOGOFF | \
USER_ALL_LOGONHOURS | \
USER_ALL_BADPASSWORDCOUNT | \
USER_ALL_LOGONCOUNT | \
USER_ALL_PASSWORDCANCHANGE | \
USER_ALL_PASSWORDMUSTCHANGE)
// Fields that require USER_READ_ACCOUNT access to read.
#define USER_ALL_READ_ACCOUNT_MASK (USER_ALL_PASSWORDLASTSET | \
USER_ALL_ACCOUNTEXPIRES | \
USER_ALL_USERACCOUNTCONTROL | \
USER_ALL_PARAMETERS)
// Fields that require USER_READ_PREFERENCES access to read.
#define USER_ALL_READ_PREFERENCES_MASK (USER_ALL_COUNTRYCODE | \
USER_ALL_CODEPAGE)
// Fields that can only be read by trusted clients.
#define USER_ALL_READ_TRUSTED_MASK (USER_ALL_NTPASSWORDPRESENT | \
USER_ALL_LMPASSWORDPRESENT | \
USER_ALL_PASSWORDEXPIRED | \
USER_ALL_SECURITYDESCRIPTOR | \
USER_ALL_PRIVATEDATA)
// Fields that can't be read.
#define USER_ALL_READ_CANT_MASK USER_ALL_UNDEFINED_MASK
// Fields that require USER_WRITE_ACCOUNT access to write.
#define USER_ALL_WRITE_ACCOUNT_MASK (USER_ALL_USERNAME | \
USER_ALL_FULLNAME | \
USER_ALL_PRIMARYGROUPID | \
USER_ALL_HOMEDIRECTORY | \
USER_ALL_HOMEDIRECTORYDRIVE | \
USER_ALL_SCRIPTPATH | \
USER_ALL_PROFILEPATH | \
USER_ALL_ADMINCOMMENT | \
USER_ALL_WORKSTATIONS | \
USER_ALL_LOGONHOURS | \
USER_ALL_ACCOUNTEXPIRES | \
USER_ALL_USERACCOUNTCONTROL | \
USER_ALL_PARAMETERS)
// Fields that require USER_WRITE_PREFERENCES access to write.
#define USER_ALL_WRITE_PREFERENCES_MASK (USER_ALL_USERCOMMENT | \
USER_ALL_COUNTRYCODE | \
USER_ALL_CODEPAGE)
// Fields that require USER_FORCE_PASSWORD_CHANGE access to write.
//
// Note that non-trusted clients only set the NT password as a
// UNICODE string. The wrapper will convert it to an LM password,
// OWF and encrypt both versions. Trusted clients can pass in OWF
// versions of either or both.
#define USER_ALL_WRITE_FORCE_PASSWORD_CHANGE_MASK \
(USER_ALL_NTPASSWORDPRESENT | \
USER_ALL_LMPASSWORDPRESENT | \
USER_ALL_PASSWORDEXPIRED)
// Fields that can only be written by trusted clients.
#define USER_ALL_WRITE_TRUSTED_MASK (USER_ALL_LASTLOGON | \
USER_ALL_LASTLOGOFF | \
USER_ALL_BADPASSWORDCOUNT | \
USER_ALL_LOGONCOUNT | \
USER_ALL_PASSWORDLASTSET | \
USER_ALL_SECURITYDESCRIPTOR | \
USER_ALL_PRIVATEDATA)
// Fields that can't be written.
#define USER_ALL_WRITE_CANT_MASK (USER_ALL_USERID | \
USER_ALL_PASSWORDCANCHANGE | \
USER_ALL_PASSWORDMUSTCHANGE | \
USER_ALL_UNDEFINED_MASK)
typedef struct _USER_GENERAL_INFORMATION
{
UNICODE_STRING UserName;
UNICODE_STRING FullName;
ULONG PrimaryGroupId;
UNICODE_STRING AdminComment;
UNICODE_STRING UserComment;
} USER_GENERAL_INFORMATION, *PUSER_GENERAL_INFORMATION;
typedef struct _USER_PREFERENCES_INFORMATION
{
UNICODE_STRING UserComment;
UNICODE_STRING Reserved1;
USHORT CountryCode;
USHORT CodePage;
} USER_PREFERENCES_INFORMATION, *PUSER_PREFERENCES_INFORMATION;
typedef struct _USER_PARAMETERS_INFORMATION
{
UNICODE_STRING Parameters;
} USER_PARAMETERS_INFORMATION, *PUSER_PARAMETERS_INFORMATION;
#include <pshpack4.h>
typedef struct _USER_LOGON_INFORMATION
{
UNICODE_STRING UserName;
UNICODE_STRING FullName;
ULONG UserId;
ULONG PrimaryGroupId;
UNICODE_STRING HomeDirectory;
UNICODE_STRING HomeDirectoryDrive;
UNICODE_STRING ScriptPath;
UNICODE_STRING ProfilePath;
UNICODE_STRING WorkStations;
LARGE_INTEGER LastLogon;
LARGE_INTEGER LastLogoff;
LARGE_INTEGER PasswordLastSet;
LARGE_INTEGER PasswordCanChange;
LARGE_INTEGER PasswordMustChange;
LOGON_HOURS LogonHours;
USHORT BadPasswordCount;
USHORT LogonCount;
ULONG UserAccountControl;
} USER_LOGON_INFORMATION, *PUSER_LOGON_INFORMATION;
#include <poppack.h>
#include <pshpack4.h>
typedef struct _USER_ACCOUNT_INFORMATION
{
UNICODE_STRING UserName;
UNICODE_STRING FullName;
ULONG UserId;
ULONG PrimaryGroupId;
UNICODE_STRING HomeDirectory;
UNICODE_STRING HomeDirectoryDrive;
UNICODE_STRING ScriptPath;
UNICODE_STRING ProfilePath;
UNICODE_STRING AdminComment;
UNICODE_STRING WorkStations;
LARGE_INTEGER LastLogon;
LARGE_INTEGER LastLogoff;
LOGON_HOURS LogonHours;
USHORT BadPasswordCount;
USHORT LogonCount;
LARGE_INTEGER PasswordLastSet;
LARGE_INTEGER AccountExpires;
ULONG UserAccountControl;
} USER_ACCOUNT_INFORMATION, *PUSER_ACCOUNT_INFORMATION;
#include <poppack.h>
typedef struct _USER_ACCOUNT_NAME_INFORMATION
{
UNICODE_STRING UserName;
} USER_ACCOUNT_NAME_INFORMATION, *PUSER_ACCOUNT_NAME_INFORMATION;
typedef struct _USER_FULL_NAME_INFORMATION
{
UNICODE_STRING FullName;
} USER_FULL_NAME_INFORMATION, *PUSER_FULL_NAME_INFORMATION;
typedef struct _USER_NAME_INFORMATION
{
UNICODE_STRING UserName;
UNICODE_STRING FullName;
} USER_NAME_INFORMATION, *PUSER_NAME_INFORMATION;
typedef struct _USER_PRIMARY_GROUP_INFORMATION
{
ULONG PrimaryGroupId;
} USER_PRIMARY_GROUP_INFORMATION, *PUSER_PRIMARY_GROUP_INFORMATION;
typedef struct _USER_HOME_INFORMATION
{
UNICODE_STRING HomeDirectory;
UNICODE_STRING HomeDirectoryDrive;
} USER_HOME_INFORMATION, *PUSER_HOME_INFORMATION;
typedef struct _USER_SCRIPT_INFORMATION
{
UNICODE_STRING ScriptPath;
} USER_SCRIPT_INFORMATION, *PUSER_SCRIPT_INFORMATION;
typedef struct _USER_PROFILE_INFORMATION
{
UNICODE_STRING ProfilePath;
} USER_PROFILE_INFORMATION, *PUSER_PROFILE_INFORMATION;
typedef struct _USER_ADMIN_COMMENT_INFORMATION
{
UNICODE_STRING AdminComment;
} USER_ADMIN_COMMENT_INFORMATION, *PUSER_ADMIN_COMMENT_INFORMATION;
typedef struct _USER_WORKSTATIONS_INFORMATION
{
UNICODE_STRING WorkStations;
} USER_WORKSTATIONS_INFORMATION, *PUSER_WORKSTATIONS_INFORMATION;
typedef struct _USER_SET_PASSWORD_INFORMATION
{
UNICODE_STRING Password;
BOOLEAN PasswordExpired;
} USER_SET_PASSWORD_INFORMATION, *PUSER_SET_PASSWORD_INFORMATION;
typedef struct _USER_CONTROL_INFORMATION
{
ULONG UserAccountControl;
} USER_CONTROL_INFORMATION, *PUSER_CONTROL_INFORMATION;
typedef struct _USER_EXPIRES_INFORMATION
{
LARGE_INTEGER AccountExpires;
} USER_EXPIRES_INFORMATION, *PUSER_EXPIRES_INFORMATION;
typedef struct _USER_LOGON_HOURS_INFORMATION
{
LOGON_HOURS LogonHours;
} USER_LOGON_HOURS_INFORMATION, *PUSER_LOGON_HOURS_INFORMATION;
typedef SAM_BYTE_ARRAY_32K SAM_USER_TILE, *PSAM_USER_TILE;
// 0xff000fff is reserved for internal callers and implementation.
#define USER_EXTENDED_FIELD_USER_TILE (0x00001000L)
#define USER_EXTENDED_FIELD_PASSWORD_HINT (0x00002000L)
#define USER_EXTENDED_FIELD_DONT_SHOW_IN_LOGON_UI (0x00004000L)
#define USER_EXTENDED_FIELD_SHELL_ADMIN_OBJECT_PROPERTIES (0x00008000L)
typedef struct _USER_EXTENDED_INFORMATION
{
ULONG ExtendedWhichFields;
SAM_USER_TILE UserTile;
UNICODE_STRING PasswordHint;
BOOLEAN DontShowInLogonUI;
SAM_SHELL_OBJECT_PROPERTIES ShellAdminObjectProperties;
} USER_EXTENDED_INFORMATION, *PUSER_EXTENDED_INFORMATION;
// For local callers only.
typedef struct _USER_LOGON_UI_INFORMATION
{
BOOLEAN PasswordIsBlank;
BOOLEAN AccountIsDisabled;
} USER_LOGON_UI_INFORMATION, *PUSER_LOGON_UI_INFORMATION;
// SamChangePasswordUser3 types
// Error values:
// * SAM_PWD_CHANGE_NO_ERROR
// * SAM_PWD_CHANGE_PASSWORD_TOO_SHORT
// * SAM_PWD_CHANGE_PWD_IN_HISTORY
// * SAM_PWD_CHANGE_USERNAME_IN_PASSWORD
// * SAM_PWD_CHANGE_FULLNAME_IN_PASSWORD
// * SAM_PWD_CHANGE_MACHINE_PASSWORD_NOT_DEFAULT
// * SAM_PWD_CHANGE_FAILED_BY_FILTER
typedef struct _USER_PWD_CHANGE_FAILURE_INFORMATION
{
ULONG ExtendedFailureReason;
UNICODE_STRING FilterModuleName;
} USER_PWD_CHANGE_FAILURE_INFORMATION,*PUSER_PWD_CHANGE_FAILURE_INFORMATION;
// ExtendedFailureReason values
#define SAM_PWD_CHANGE_NO_ERROR 0
#define SAM_PWD_CHANGE_PASSWORD_TOO_SHORT 1
#define SAM_PWD_CHANGE_PWD_IN_HISTORY 2
#define SAM_PWD_CHANGE_USERNAME_IN_PASSWORD 3
#define SAM_PWD_CHANGE_FULLNAME_IN_PASSWORD 4
#define SAM_PWD_CHANGE_NOT_COMPLEX 5
#define SAM_PWD_CHANGE_MACHINE_PASSWORD_NOT_DEFAULT 6
#define SAM_PWD_CHANGE_FAILED_BY_FILTER 7
#define SAM_PWD_CHANGE_PASSWORD_TOO_LONG 8
#define SAM_PWD_CHANGE_FAILURE_REASON_MAX 8
// Functions
_Check_return_
NTSTATUS
NTAPI
SamEnumerateUsersInDomain(
_In_ SAM_HANDLE DomainHandle,
_Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
_In_ ULONG UserAccountControl,
_Outptr_ PVOID *Buffer, // PSAM_RID_ENUMERATION *
_In_ ULONG PreferedMaximumLength,
_Out_ PULONG CountReturned
);
_Check_return_
NTSTATUS
NTAPI
SamCreateUserInDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ PUNICODE_STRING AccountName,
_In_ ACCESS_MASK DesiredAccess,
_Out_ PSAM_HANDLE UserHandle,
_Out_ PULONG RelativeId
);
_Check_return_
NTSTATUS
NTAPI
SamCreateUser2InDomain(
_In_ SAM_HANDLE DomainHandle,
_In_ PUNICODE_STRING AccountName,
_In_ ULONG AccountType,
_In_ ACCESS_MASK DesiredAccess,
_Out_ PSAM_HANDLE UserHandle,
_Out_ PULONG GrantedAccess,
_Out_ PULONG RelativeId
);
_Check_return_
NTSTATUS
NTAPI
SamOpenUser(
_In_ SAM_HANDLE DomainHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ ULONG UserId,
_Out_ PSAM_HANDLE UserHandle
);
_Check_return_
NTSTATUS
NTAPI
SamDeleteUser(
_In_ SAM_HANDLE UserHandle
);
_Check_return_
NTSTATUS
NTAPI
SamQueryInformationUser(
_In_ SAM_HANDLE UserHandle,
_In_ USER_INFORMATION_CLASS UserInformationClass,
_Outptr_ PVOID *Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamSetInformationUser(
_In_ SAM_HANDLE UserHandle,
_In_ USER_INFORMATION_CLASS UserInformationClass,
_In_ PVOID Buffer
);
_Check_return_
NTSTATUS
NTAPI
SamGetGroupsForUser(
_In_ SAM_HANDLE UserHandle,
_Out_ _Deref_post_count_(*MembershipCount) PGROUP_MEMBERSHIP *Groups,
_Out_ PULONG MembershipCount
);
_Check_return_
NTSTATUS
NTAPI
SamChangePasswordUser(
_In_ SAM_HANDLE UserHandle,
_In_ PUNICODE_STRING OldPassword,
_In_ PUNICODE_STRING NewPassword
);
_Check_return_
NTSTATUS
NTAPI
SamChangePasswordUser2(
_In_ PUNICODE_STRING ServerName,
_In_ PUNICODE_STRING UserName,
_In_ PUNICODE_STRING OldPassword,
_In_ PUNICODE_STRING NewPassword
);
_Check_return_
NTSTATUS
NTAPI
SamChangePasswordUser3(
_In_ PUNICODE_STRING ServerName,
_In_ PUNICODE_STRING UserName,
_In_ PUNICODE_STRING OldPassword,
_In_ PUNICODE_STRING NewPassword,
_Outptr_ PDOMAIN_PASSWORD_INFORMATION *EffectivePasswordPolicy,
_Outptr_ PUSER_PWD_CHANGE_FAILURE_INFORMATION *PasswordChangeFailureInfo
);
_Check_return_
NTSTATUS
NTAPI
SamQueryDisplayInformation(
_In_ SAM_HANDLE DomainHandle,
_In_ DOMAIN_DISPLAY_INFORMATION DisplayInformation,
_In_ ULONG Index,
_In_ ULONG EntryCount,
_In_ ULONG PreferredMaximumLength,
_In_ PULONG TotalAvailable,
_Out_ PULONG TotalReturned,
_Out_ PULONG ReturnedEntryCount,
_Outptr_ PVOID *SortedBuffer
);
_Check_return_
NTSTATUS
NTAPI
SamGetDisplayEnumerationIndex(
_In_ SAM_HANDLE DomainHandle,
_In_ DOMAIN_DISPLAY_INFORMATION DisplayInformation,
_In_ PUNICODE_STRING Prefix,
_Out_ PULONG Index
);
// Database replication
typedef enum _SECURITY_DB_DELTA_TYPE
{
SecurityDbNew = 1,
SecurityDbRename,
SecurityDbDelete,
SecurityDbChangeMemberAdd,
SecurityDbChangeMemberSet,
SecurityDbChangeMemberDel,
SecurityDbChange,
SecurityDbChangePassword
} SECURITY_DB_DELTA_TYPE, *PSECURITY_DB_DELTA_TYPE;
typedef enum _SECURITY_DB_OBJECT_TYPE
{
SecurityDbObjectSamDomain = 1,
SecurityDbObjectSamUser,
SecurityDbObjectSamGroup,
SecurityDbObjectSamAlias,
SecurityDbObjectLsaPolicy,
SecurityDbObjectLsaTDomain,
SecurityDbObjectLsaAccount,
SecurityDbObjectLsaSecret
} SECURITY_DB_OBJECT_TYPE, *PSECURITY_DB_OBJECT_TYPE;
typedef enum _SAM_ACCOUNT_TYPE
{
SamObjectUser = 1,
SamObjectGroup,
SamObjectAlias
} SAM_ACCOUNT_TYPE, *PSAM_ACCOUNT_TYPE;
#define SAM_USER_ACCOUNT (0x00000001)
#define SAM_GLOBAL_GROUP_ACCOUNT (0x00000002)
#define SAM_LOCAL_GROUP_ACCOUNT (0x00000004)
typedef struct _SAM_GROUP_MEMBER_ID
{
ULONG MemberRid;
} SAM_GROUP_MEMBER_ID, *PSAM_GROUP_MEMBER_ID;
typedef struct _SAM_ALIAS_MEMBER_ID
{
PSID MemberSid;
} SAM_ALIAS_MEMBER_ID, *PSAM_ALIAS_MEMBER_ID;
typedef union _SAM_DELTA_DATA
{
SAM_GROUP_MEMBER_ID GroupMemberId;
SAM_ALIAS_MEMBER_ID AliasMemberId;
ULONG AccountControl;
} SAM_DELTA_DATA, *PSAM_DELTA_DATA;
typedef NTSTATUS (NTAPI *PSAM_DELTA_NOTIFICATION_ROUTINE)(
_In_ PSID DomainSid,
_In_ SECURITY_DB_DELTA_TYPE DeltaType,
_In_ SECURITY_DB_OBJECT_TYPE ObjectType,
_In_ ULONG ObjectRid,
_In_opt_ PUNICODE_STRING ObjectName,
_In_ PLARGE_INTEGER ModifiedCount,
_In_opt_ PSAM_DELTA_DATA DeltaData
);
#define SAM_DELTA_NOTIFY_ROUTINE "DeltaNotify"
_Check_return_
NTSTATUS
NTAPI
SamRegisterObjectChangeNotification(
_In_ SECURITY_DB_OBJECT_TYPE ObjectType,
_In_ HANDLE NotificationEventHandle
);
NTSTATUS
NTAPI
SamUnregisterObjectChangeNotification(
_In_ SECURITY_DB_OBJECT_TYPE ObjectType,
_In_ HANDLE NotificationEventHandle
);
// Compatibility mode
#define SAM_SID_COMPATIBILITY_ALL 0
#define SAM_SID_COMPATIBILITY_LAX 1
#define SAM_SID_COMPATIBILITY_STRICT 2
_Check_return_
NTSTATUS
NTAPI
SamGetCompatibilityMode(
_In_ SAM_HANDLE ObjectHandle,
_Out_ ULONG *Mode
);
// Password validation
typedef enum _PASSWORD_POLICY_VALIDATION_TYPE
{
SamValidateAuthentication = 1,
SamValidatePasswordChange,
SamValidatePasswordReset
} PASSWORD_POLICY_VALIDATION_TYPE;
typedef struct _SAM_VALIDATE_PASSWORD_HASH
{
ULONG Length;
_Field_size_bytes_(Length) PUCHAR Hash;
} SAM_VALIDATE_PASSWORD_HASH, *PSAM_VALIDATE_PASSWORD_HASH;
// Flags for PresentFields in SAM_VALIDATE_PERSISTED_FIELDS
#define SAM_VALIDATE_PASSWORD_LAST_SET 0x00000001
#define SAM_VALIDATE_BAD_PASSWORD_TIME 0x00000002
#define SAM_VALIDATE_LOCKOUT_TIME 0x00000004
#define SAM_VALIDATE_BAD_PASSWORD_COUNT 0x00000008
#define SAM_VALIDATE_PASSWORD_HISTORY_LENGTH 0x00000010
#define SAM_VALIDATE_PASSWORD_HISTORY 0x00000020
typedef struct _SAM_VALIDATE_PERSISTED_FIELDS
{
ULONG PresentFields;
LARGE_INTEGER PasswordLastSet;
LARGE_INTEGER BadPasswordTime;
LARGE_INTEGER LockoutTime;
ULONG BadPasswordCount;
ULONG PasswordHistoryLength;
_Field_size_bytes_(PasswordHistoryLength) PSAM_VALIDATE_PASSWORD_HASH PasswordHistory;
} SAM_VALIDATE_PERSISTED_FIELDS, *PSAM_VALIDATE_PERSISTED_FIELDS;
typedef enum _SAM_VALIDATE_VALIDATION_STATUS
{
SamValidateSuccess = 0,
SamValidatePasswordMustChange,
SamValidateAccountLockedOut,
SamValidatePasswordExpired,
SamValidatePasswordIncorrect,
SamValidatePasswordIsInHistory,
SamValidatePasswordTooShort,
SamValidatePasswordTooLong,
SamValidatePasswordNotComplexEnough,
SamValidatePasswordTooRecent,
SamValidatePasswordFilterError
} SAM_VALIDATE_VALIDATION_STATUS, *PSAM_VALIDATE_VALIDATION_STATUS;
typedef struct _SAM_VALIDATE_STANDARD_OUTPUT_ARG
{
SAM_VALIDATE_PERSISTED_FIELDS ChangedPersistedFields;
SAM_VALIDATE_VALIDATION_STATUS ValidationStatus;
} SAM_VALIDATE_STANDARD_OUTPUT_ARG, *PSAM_VALIDATE_STANDARD_OUTPUT_ARG;
typedef struct _SAM_VALIDATE_AUTHENTICATION_INPUT_ARG
{
SAM_VALIDATE_PERSISTED_FIELDS InputPersistedFields;
BOOLEAN PasswordMatched;
} SAM_VALIDATE_AUTHENTICATION_INPUT_ARG, *PSAM_VALIDATE_AUTHENTICATION_INPUT_ARG;
typedef struct _SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG
{
SAM_VALIDATE_PERSISTED_FIELDS InputPersistedFields;
UNICODE_STRING ClearPassword;
UNICODE_STRING UserAccountName;
SAM_VALIDATE_PASSWORD_HASH HashedPassword;
BOOLEAN PasswordMatch; // denotes if the old password supplied by user matched or not
} SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG, *PSAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG;
typedef struct _SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG
{
SAM_VALIDATE_PERSISTED_FIELDS InputPersistedFields;
UNICODE_STRING ClearPassword;
UNICODE_STRING UserAccountName;
SAM_VALIDATE_PASSWORD_HASH HashedPassword;
BOOLEAN PasswordMustChangeAtNextLogon; // looked at only for password reset
BOOLEAN ClearLockout; // can be used clear user account lockout
}SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG, *PSAM_VALIDATE_PASSWORD_RESET_INPUT_ARG;
typedef union _SAM_VALIDATE_INPUT_ARG
{
SAM_VALIDATE_AUTHENTICATION_INPUT_ARG ValidateAuthenticationInput;
SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG ValidatePasswordChangeInput;
SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG ValidatePasswordResetInput;
} SAM_VALIDATE_INPUT_ARG, *PSAM_VALIDATE_INPUT_ARG;
typedef union _SAM_VALIDATE_OUTPUT_ARG
{
SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidateAuthenticationOutput;
SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidatePasswordChangeOutput;
SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidatePasswordResetOutput;
} SAM_VALIDATE_OUTPUT_ARG, *PSAM_VALIDATE_OUTPUT_ARG;
_Check_return_
NTSTATUS
NTAPI
SamValidatePassword(
_In_opt_ PUNICODE_STRING ServerName,
_In_ PASSWORD_POLICY_VALIDATION_TYPE ValidationType,
_In_ PSAM_VALIDATE_INPUT_ARG InputArg,
_Out_ PSAM_VALIDATE_OUTPUT_ARG *OutputArg
);
// Generic operation
typedef enum _SAM_GENERIC_OPERATION_TYPE
{
SamObjectChangeNotificationOperation
} SAM_GENERIC_OPERATION_TYPE, *PSAM_GENERIC_OPERATION_TYPE;
typedef struct _SAM_OPERATION_OBJCHG_INPUT
{
BOOLEAN Register;
ULONG64 EventHandle;
SECURITY_DB_OBJECT_TYPE ObjectType;
ULONG ProcessID;
} SAM_OPERATION_OBJCHG_INPUT, *PSAM_OPERATION_OBJCHG_INPUT;
typedef struct _SAM_OPERATION_OBJCHG_OUTPUT
{
ULONG Reserved;
} SAM_OPERATION_OBJCHG_OUTPUT, *PSAM_OPERATION_OBJCHG_OUTPUT;
typedef union _SAM_GENERIC_OPERATION_INPUT
{
SAM_OPERATION_OBJCHG_INPUT ObjChangeIn;
} SAM_GENERIC_OPERATION_INPUT, *PSAM_GENERIC_OPERATION_INPUT;
typedef union _SAM_GENERIC_OPERATION_OUTPUT
{
SAM_OPERATION_OBJCHG_OUTPUT ObjChangeOut;
} SAM_GENERIC_OPERATION_OUTPUT, *PSAM_GENERIC_OPERATION_OUTPUT;
_Check_return_
NTSTATUS
NTAPI
SamPerformGenericOperation(
_In_opt_ PWSTR ServerName,
_In_ SAM_GENERIC_OPERATION_TYPE OperationType,
_In_ PSAM_GENERIC_OPERATION_INPUT OperationIn,
_Out_ PSAM_GENERIC_OPERATION_OUTPUT *OperationOut
);
// #include <ntmisc.h>
// Filter manager
#define FLT_PORT_CONNECT 0x0001
#define FLT_PORT_ALL_ACCESS (FLT_PORT_CONNECT | STANDARD_RIGHTS_ALL)
// VDM
typedef enum _VDMSERVICECLASS
{
VdmStartExecution,
VdmQueueInterrupt,
VdmDelayInterrupt,
VdmInitialize,
VdmFeatures,
VdmSetInt21Handler,
VdmQueryDir,
VdmPrinterDirectIoOpen,
VdmPrinterDirectIoClose,
VdmPrinterInitialize,
VdmSetLdtEntries,
VdmSetProcessLdtInfo,
VdmAdlibEmulation,
VdmPMCliControl,
VdmQueryVdmProcess
} VDMSERVICECLASS, *PVDMSERVICECLASS;
NTSYSCALLAPI
NTSTATUS
NTAPI
NtVdmControl(
_In_ VDMSERVICECLASS Service,
_Inout_ PVOID ServiceData
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwVdmControl(
_In_ VDMSERVICECLASS Service,
_Inout_ PVOID ServiceData
);
// WMI/ETW
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTraceEvent(
_In_ HANDLE TraceHandle,
_In_ ULONG Flags,
_In_ ULONG FieldSize,
_In_ PVOID Fields
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTraceEvent(
_In_ HANDLE TraceHandle,
_In_ ULONG Flags,
_In_ ULONG FieldSize,
_In_ PVOID Fields
);
#if (NTDDI_VERSION >= NTDDI_VISTA)
// private
NTSYSCALLAPI
NTSTATUS
NTAPI
NtTraceControl(
_In_ ULONG FunctionCode,
_In_reads_bytes_opt_(InBufferLen) PVOID InBuffer,
_In_ ULONG InBufferLen,
_Out_writes_bytes_opt_(OutBufferLen) PVOID OutBuffer,
_In_ ULONG OutBufferLen,
_Out_ PULONG ReturnLength
);
NTSYSCALLAPI
NTSTATUS
NTAPI
ZwTraceControl(
_In_ ULONG FunctionCode,
_In_reads_bytes_opt_(InBufferLen) PVOID InBuffer,
_In_ ULONG InBufferLen,
_Out_writes_bytes_opt_(OutBufferLen) PVOID OutBuffer,
_In_ ULONG OutBufferLen,
_Out_ PULONG ReturnLength
);
#endif
// #include <ntsmss.h>
NTSYSAPI
NTSTATUS
NTAPI
RtlConnectToSm(
_In_ PUNICODE_STRING ApiPortName,
_In_ HANDLE ApiPortHandle,
_In_ DWORD ProcessImageType,
_Out_ PHANDLE SmssConnection
);
NTSYSAPI
NTSTATUS
NTAPI
RtlSendMsgToSm(
_In_ HANDLE ApiPortHandle,
_In_ PPORT_MESSAGE MessageData
);
// #include <subprocesstag.h>
// Subprocess tag information
typedef enum _TAG_INFO_LEVEL
{
eTagInfoLevelNameFromTag = 1, // TAG_INFO_NAME_FROM_TAG
eTagInfoLevelNamesReferencingModule, // TAG_INFO_NAMES_REFERENCING_MODULE
eTagInfoLevelNameTagMapping, // TAG_INFO_NAME_TAG_MAPPING
eTagInfoLevelMax
} TAG_INFO_LEVEL;
typedef enum _TAG_TYPE
{
eTagTypeService = 1,
eTagTypeMax
} TAG_TYPE;
typedef struct _TAG_INFO_NAME_FROM_TAG_IN_PARAMS
{
DWORD dwPid;
DWORD dwTag;
} TAG_INFO_NAME_FROM_TAG_IN_PARAMS, *PTAG_INFO_NAME_FROM_TAG_IN_PARAMS;
typedef struct _TAG_INFO_NAME_FROM_TAG_OUT_PARAMS
{
DWORD eTagType;
LPWSTR pszName;
} TAG_INFO_NAME_FROM_TAG_OUT_PARAMS, *PTAG_INFO_NAME_FROM_TAG_OUT_PARAMS;
typedef struct _TAG_INFO_NAME_FROM_TAG
{
TAG_INFO_NAME_FROM_TAG_IN_PARAMS InParams;
TAG_INFO_NAME_FROM_TAG_OUT_PARAMS OutParams;
} TAG_INFO_NAME_FROM_TAG, *PTAG_INFO_NAME_FROM_TAG;
typedef struct _TAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS
{
DWORD dwPid;
LPWSTR pszModule;
} TAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS, *PTAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS;
typedef struct _TAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS
{
DWORD eTagType;
LPWSTR pmszNames;
} TAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS, *PTAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS;
typedef struct _TAG_INFO_NAMES_REFERENCING_MODULE
{
TAG_INFO_NAMES_REFERENCING_MODULE_IN_PARAMS InParams;
TAG_INFO_NAMES_REFERENCING_MODULE_OUT_PARAMS OutParams;
} TAG_INFO_NAMES_REFERENCING_MODULE, *PTAG_INFO_NAMES_REFERENCING_MODULE;
typedef struct _TAG_INFO_NAME_TAG_MAPPING_IN_PARAMS
{
DWORD dwPid;
} TAG_INFO_NAME_TAG_MAPPING_IN_PARAMS, *PTAG_INFO_NAME_TAG_MAPPING_IN_PARAMS;
typedef struct _TAG_INFO_NAME_TAG_MAPPING_ELEMENT
{
DWORD eTagType;
DWORD dwTag;
LPWSTR pszName;
LPWSTR pszGroupName;
} TAG_INFO_NAME_TAG_MAPPING_ELEMENT, *PTAG_INFO_NAME_TAG_MAPPING_ELEMENT;
typedef struct _TAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS
{
DWORD cElements;
PTAG_INFO_NAME_TAG_MAPPING_ELEMENT pNameTagMappingElements;
} TAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS, *PTAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS;
typedef struct _TAG_INFO_NAME_TAG_MAPPING
{
TAG_INFO_NAME_TAG_MAPPING_IN_PARAMS InParams;
PTAG_INFO_NAME_TAG_MAPPING_OUT_PARAMS pOutParams;
} TAG_INFO_NAME_TAG_MAPPING, *PTAG_INFO_NAME_TAG_MAPPING;
_Must_inspect_result_
DWORD
WINAPI
I_QueryTagInformation(
_In_opt_ LPCWSTR pszMachineName,
_In_ TAG_INFO_LEVEL eInfoLevel,
_Inout_ PVOID pTagInfo
);
typedef DWORD (WINAPI *PQUERY_TAG_INFORMATION)(
_In_opt_ LPCWSTR pszMachineName,
_In_ TAG_INFO_LEVEL eInfoLevel,
_Inout_ PVOID pTagInfo
);
// #include <winsta.h>
// Access rights
#define WINSTATION_QUERY 0x00000001 // WinStationQueryInformation
#define WINSTATION_SET 0x00000002 // WinStationSetInformation
#define WINSTATION_RESET 0x00000004 // WinStationReset
#define WINSTATION_VIRTUAL 0x00000008 //read/write direct data
#define WINSTATION_SHADOW 0x00000010 // WinStationShadow
#define WINSTATION_LOGON 0x00000020 // logon to WinStation
#define WINSTATION_LOGOFF 0x00000040 // WinStationLogoff
#define WINSTATION_MSG 0x00000080 // WinStationMsg
#define WINSTATION_CONNECT 0x00000100 // WinStationConnect
#define WINSTATION_DISCONNECT 0x00000200 // WinStationDisconnect
#define WINSTATION_GUEST_ACCESS WINSTATION_LOGON
#define WINSTATION_CURRENT_GUEST_ACCESS (WINSTATION_VIRTUAL | WINSTATION_LOGOFF)
#define WINSTATION_USER_ACCESS (WINSTATION_GUEST_ACCESS | WINSTATION_QUERY | WINSTATION_CONNECT)
#define WINSTATION_CURRENT_USER_ACCESS \
(WINSTATION_SET | WINSTATION_RESET | WINSTATION_VIRTUAL | \
WINSTATION_LOGOFF | WINSTATION_DISCONNECT)
#define WINSTATION_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | WINSTATION_QUERY | \
WINSTATION_SET | WINSTATION_RESET | WINSTATION_VIRTUAL | \
WINSTATION_SHADOW | WINSTATION_LOGON | WINSTATION_MSG | \
WINSTATION_CONNECT | WINSTATION_DISCONNECT)
#define WDPREFIX_LENGTH 12
#define CALLBACK_LENGTH 50
#define DLLNAME_LENGTH 32
#define CDNAME_LENGTH 32
#define WDNAME_LENGTH 32
#define PDNAME_LENGTH 32
#define DEVICENAME_LENGTH 128
#define MODEMNAME_LENGTH DEVICENAME_LENGTH
#define STACK_ADDRESS_LENGTH 128
#define MAX_BR_NAME 65
#define DIRECTORY_LENGTH 256
#define INITIALPROGRAM_LENGTH 256
#define USERNAME_LENGTH 20
#define DOMAIN_LENGTH 17
#define PASSWORD_LENGTH 14
#define NASISPECIFICNAME_LENGTH 14
#define NASIUSERNAME_LENGTH 47
#define NASIPASSWORD_LENGTH 24
#define NASISESSIONNAME_LENGTH 16
#define NASIFILESERVER_LENGTH 47
#define CLIENTDATANAME_LENGTH 7
#define CLIENTNAME_LENGTH 20
#define CLIENTADDRESS_LENGTH 30
#define IMEFILENAME_LENGTH 32
#define DIRECTORY_LENGTH 256
#define CLIENTLICENSE_LENGTH 32
#define CLIENTMODEM_LENGTH 40
#define CLIENT_PRODUCT_ID_LENGTH 32
#define MAX_COUNTER_EXTENSIONS 2
#define WINSTATIONNAME_LENGTH 32
#define TERMSRV_TOTAL_SESSIONS 1
#define TERMSRV_DISC_SESSIONS 2
#define TERMSRV_RECON_SESSIONS 3
#define TERMSRV_CURRENT_ACTIVE_SESSIONS 4
#define TERMSRV_CURRENT_DISC_SESSIONS 5
#define TERMSRV_PENDING_SESSIONS 6
#define TERMSRV_SUCC_TOTAL_LOGONS 7
#define TERMSRV_SUCC_LOCAL_LOGONS 8
#define TERMSRV_SUCC_REMOTE_LOGONS 9
#define TERMSRV_SUCC_SESSION0_LOGONS 10
#define TERMSRV_CURRENT_TERMINATING_SESSIONS 11
#define TERMSRV_CURRENT_LOGGEDON_SESSIONS 12
typedef RTL_TIME_ZONE_INFORMATION TS_TIME_ZONE_INFORMATION, *PTS_TIME_ZONE_INFORMATION;
typedef WCHAR WINSTATIONNAME[WINSTATIONNAME_LENGTH + 1];
// Variable length data descriptor (not needed)
typedef struct _VARDATA_WIRE
{
USHORT Size;
USHORT Offset;
} VARDATA_WIRE, *PVARDATA_WIRE;
typedef enum _WINSTATIONSTATECLASS
{
State_Active = 0,
State_Connected = 1,
State_ConnectQuery = 2,
State_Shadow = 3,
State_Disconnected = 4,
State_Idle = 5,
State_Listen = 6,
State_Reset = 7,
State_Down = 8,
State_Init = 9
} WINSTATIONSTATECLASS;
typedef struct _SESSIONIDW
{
union
{
ULONG SessionId;
ULONG LogonId;
};
WINSTATIONNAME WinStationName;
WINSTATIONSTATECLASS State;
} SESSIONIDW, *PSESSIONIDW;
// private
typedef enum _WINSTATIONINFOCLASS
{
WinStationCreateData, // WINSTATIONCREATE
WinStationConfiguration, // WINSTACONFIGWIRE + USERCONFIG
WinStationPdParams, // PDPARAMS
WinStationWd, // WDCONFIG
WinStationPd, // PDCONFIG2 + PDPARAMS
WinStationPrinter, // Not supported.
WinStationClient, // WINSTATIONCLIENT
WinStationModules,
WinStationInformation, // WINSTATIONINFORMATION
WinStationTrace,
WinStationBeep,
WinStationEncryptionOff,
WinStationEncryptionPerm,
WinStationNtSecurity,
WinStationUserToken, // WINSTATIONUSERTOKEN
WinStationUnused1,
WinStationVideoData, // WINSTATIONVIDEODATA
WinStationInitialProgram,
WinStationCd, // CDCONFIG
WinStationSystemTrace,
WinStationVirtualData,
WinStationClientData, // WINSTATIONCLIENTDATA
WinStationSecureDesktopEnter,
WinStationSecureDesktopExit,
WinStationLoadBalanceSessionTarget, // ULONG
WinStationLoadIndicator, // WINSTATIONLOADINDICATORDATA
WinStationShadowInfo, // WINSTATIONSHADOW
WinStationDigProductId, // WINSTATIONPRODID
WinStationLockedState, // BOOL
WinStationRemoteAddress, // WINSTATIONREMOTEADDRESS
WinStationIdleTime, // ULONG
WinStationLastReconnectType, // ULONG
WinStationDisallowAutoReconnect, // BOOLEAN
WinStationMprNotifyInfo,
WinStationExecSrvSystemPipe,
WinStationSmartCardAutoLogon,
WinStationIsAdminLoggedOn,
WinStationReconnectedFromId, // ULONG
WinStationEffectsPolicy, // ULONG
WinStationType, // ULONG
WinStationInformationEx, // WINSTATIONINFORMATIONEX
WinStationValidationInfo
} WINSTATIONINFOCLASS;
// Retrieves general information on the type of terminal server session (protocol) to which the session belongs.
typedef struct _WINSTATIONCREATE
{
ULONG fEnableWinStation : 1;
ULONG MaxInstanceCount;
} WINSTATIONCREATE, *PWINSTATIONCREATE;
typedef struct _WINSTACONFIGWIRE
{
WCHAR Comment[61]; // The WinStation descriptive comment.
CHAR OEMId[4]; // Value identifying the OEM implementor of the TermService Listener to which this session (WinStation) belongs. This can be any value defined by the implementer (OEM) of the listener.
VARDATA_WIRE UserConfig; // VARDATA_WIRE structure defining the size and offset of the variable-length user configuration data succeeding it.
VARDATA_WIRE NewFields; // VARDATA_WIRE structure defining the size and offset of the variable-length new data succeeding it. This field is not used and is a placeholder for any new data, if and when added.
} WINSTACONFIGWIRE, *PWINSTACONFIGWIRE;
typedef enum _CALLBACKCLASS
{
Callback_Disable,
Callback_Roving,
Callback_Fixed
} CALLBACKCLASS;
// The SHADOWCLASS enumeration is used to indicate the shadow-related settings for a session running on a terminal server.
typedef enum _SHADOWCLASS
{
Shadow_Disable, // Shadowing is disabled.
Shadow_EnableInputNotify, // Permission is asked first from the session being shadowed. The shadower is also permitted keyboard and mouse input.
Shadow_EnableInputNoNotify, // Permission is not asked first from the session being shadowed. The shadower is also permitted keyboard and mouse input.
Shadow_EnableNoInputNotify, // Permission is asked first from the session being shadowed. The shadower is not permitted keyboard and mouse input and MUST observe the shadowed session.
Shadow_EnableNoInputNoNotify // Permission is not asked first from the session being shadowed. The shadower is not permitted keyboard and mouse input and MUST observe the shadowed session.
} SHADOWCLASS;
// For a specific terminal server session, the USERCONFIG structure indicates the user and session configuration.
// https://msdn.microsoft.com/en-us/library/cc248610.aspx
typedef struct _USERCONFIG
{
ULONG fInheritAutoLogon : 1;
ULONG fInheritResetBroken : 1;
ULONG fInheritReconnectSame : 1;
ULONG fInheritInitialProgram : 1;
ULONG fInheritCallback : 1;
ULONG fInheritCallbackNumber : 1;
ULONG fInheritShadow : 1;
ULONG fInheritMaxSessionTime : 1;
ULONG fInheritMaxDisconnectionTime : 1;
ULONG fInheritMaxIdleTime : 1;
ULONG fInheritAutoClient : 1;
ULONG fInheritSecurity : 1;
ULONG fPromptForPassword : 1;
ULONG fResetBroken : 1;
ULONG fReconnectSame : 1;
ULONG fLogonDisabled : 1;
ULONG fWallPaperDisabled : 1;
ULONG fAutoClientDrives : 1;
ULONG fAutoClientLpts : 1;
ULONG fForceClientLptDef : 1;
ULONG fRequireEncryption : 1;
ULONG fDisableEncryption : 1;
ULONG fUnused1 : 1;
ULONG fHomeDirectoryMapRoot : 1;
ULONG fUseDefaultGina : 1;
ULONG fCursorBlinkDisabled : 1;
ULONG fPublishedApp : 1;
ULONG fHideTitleBar : 1;
ULONG fMaximize : 1;
ULONG fDisableCpm : 1;
ULONG fDisableCdm : 1;
ULONG fDisableCcm : 1;
ULONG fDisableLPT : 1;
ULONG fDisableClip : 1;
ULONG fDisableExe : 1;
ULONG fDisableCam : 1;
ULONG fDisableAutoReconnect : 1;
ULONG ColorDepth : 3;
ULONG fInheritColorDepth : 1;
ULONG fErrorInvalidProfile : 1;
ULONG fPasswordIsScPin : 1;
ULONG fDisablePNPRedir : 1;
WCHAR UserName[USERNAME_LENGTH + 1];
WCHAR Domain[DOMAIN_LENGTH + 1];
WCHAR Password[PASSWORD_LENGTH + 1];
WCHAR WorkDirectory[DIRECTORY_LENGTH + 1];
WCHAR InitialProgram[INITIALPROGRAM_LENGTH + 1];
WCHAR CallbackNumber[CALLBACK_LENGTH + 1];
CALLBACKCLASS Callback;
SHADOWCLASS Shadow;
ULONG MaxConnectionTime;
ULONG MaxDisconnectionTime;
ULONG MaxIdleTime;
ULONG KeyboardLayout;
BYTE MinEncryptionLevel;
WCHAR NWLogonServer[NASIFILESERVER_LENGTH + 1];
WCHAR PublishedName[MAX_BR_NAME];
WCHAR WFProfilePath[DIRECTORY_LENGTH + 1];
WCHAR WFHomeDir[DIRECTORY_LENGTH + 1];
WCHAR WFHomeDirDrive[4];
} USERCONFIG, *PUSERCONFIG;
typedef enum _SDCLASS
{
SdNone = 0,
SdConsole,
SdNetwork,
SdAsync,
SdOemTransport
} SDCLASS;
typedef WCHAR DEVICENAME[DEVICENAME_LENGTH + 1];
typedef WCHAR MODEMNAME[MODEMNAME_LENGTH + 1];
typedef WCHAR NASISPECIFICNAME[NASISPECIFICNAME_LENGTH + 1];
typedef WCHAR NASIUSERNAME[NASIUSERNAME_LENGTH + 1];
typedef WCHAR NASIPASSWORD[NASIPASSWORD_LENGTH + 1];
typedef WCHAR NASISESIONNAME[NASISESSIONNAME_LENGTH + 1];
typedef WCHAR NASIFILESERVER[NASIFILESERVER_LENGTH + 1];
typedef WCHAR WDNAME[WDNAME_LENGTH + 1];
typedef WCHAR WDPREFIX[WDPREFIX_LENGTH + 1];
typedef WCHAR CDNAME[CDNAME_LENGTH + 1];
typedef WCHAR DLLNAME[DLLNAME_LENGTH + 1];
typedef WCHAR PDNAME[PDNAME_LENGTH + 1];
typedef struct _NETWORKCONFIG
{
LONG LanAdapter;
DEVICENAME NetworkName;
ULONG Flags;
} NETWORKCONFIG, *PNETWORKCONFIG;
typedef enum _FLOWCONTROLCLASS
{
FlowControl_None,
FlowControl_Hardware,
FlowControl_Software
} FLOWCONTROLCLASS;
typedef enum _RECEIVEFLOWCONTROLCLASS
{
ReceiveFlowControl_None,
ReceiveFlowControl_RTS,
ReceiveFlowControl_DTR,
} RECEIVEFLOWCONTROLCLASS;
typedef enum _TRANSMITFLOWCONTROLCLASS
{
TransmitFlowControl_None,
TransmitFlowControl_CTS,
TransmitFlowControl_DSR,
} TRANSMITFLOWCONTROLCLASS;
typedef enum _ASYNCCONNECTCLASS
{
Connect_CTS,
Connect_DSR,
Connect_RI,
Connect_DCD,
Connect_FirstChar,
Connect_Perm,
} ASYNCCONNECTCLASS;
typedef struct _FLOWCONTROLCONFIG
{
ULONG fEnableSoftwareTx : 1;
ULONG fEnableSoftwareRx : 1;
ULONG fEnableDTR : 1;
ULONG fEnableRTS : 1;
CHAR XonChar;
CHAR XoffChar;
FLOWCONTROLCLASS Type;
RECEIVEFLOWCONTROLCLASS HardwareReceive;
TRANSMITFLOWCONTROLCLASS HardwareTransmit;
} FLOWCONTROLCONFIG, *PFLOWCONTROLCONFIG;
typedef struct _CONNECTCONFIG
{
ASYNCCONNECTCLASS Type;
ULONG fEnableBreakDisconnect : 1;
} CONNECTCONFIG, *PCONNECTCONFIG;
typedef struct _ASYNCCONFIG
{
DEVICENAME DeviceName;
MODEMNAME ModemName;
ULONG BaudRate;
ULONG Parity;
ULONG StopBits;
ULONG ByteSize;
ULONG fEnableDsrSensitivity : 1;
ULONG fConnectionDriver : 1;
FLOWCONTROLCONFIG FlowControl;
CONNECTCONFIG Connect;
} ASYNCCONFIG, *PASYNCCONFIG;
typedef struct _NASICONFIG
{
NASISPECIFICNAME SpecificName;
NASIUSERNAME UserName;
NASIPASSWORD PassWord;
NASISESIONNAME SessionName;
NASIFILESERVER FileServer;
BOOLEAN GlobalSession;
} NASICONFIG, *PNASICONFIG;
typedef struct _OEMTDCONFIG
{
LONG Adapter;
DEVICENAME DeviceName;
ULONG Flags;
} OEMTDCONFIG, *POEMTDCONFIG;
// Retrieves transport protocol driver parameters.
typedef struct _PDPARAMS
{
SDCLASS SdClass; // Stack driver class. Indicates which one of the union's structures is valid.
union
{
NETWORKCONFIG Network; // Configuration of network drivers. Used if SdClass is SdNetwork.
ASYNCCONFIG Async; // Configuration of async (modem) driver. Used if SdClass is SdAsync.
NASICONFIG Nasi; // Reserved.
OEMTDCONFIG OemTd; // Configuration of OEM transport driver. Used if SdClass is SdOemTransport.
};
} PDPARAMS, *PPDPARAMS;
// The WinStation (session) driver configuration.
typedef struct _WDCONFIG
{
WDNAME WdName; // The descriptive name of the WinStation driver.
DLLNAME WdDLL; // The driver's image name.
DLLNAME WsxDLL; // Used by the Terminal Services service to communicate with the WinStation driver.
ULONG WdFlag; // Driver flags.
ULONG WdInputBufferLength; // Length, in bytes, of the input buffer used by the driver. Defaults to 2048.
DLLNAME CfgDLL; // Configuration DLL used by Terminal Services administrative tools for configuring the driver.
WDPREFIX WdPrefix; // Used as the prefix of the WinStation name generated for the connected sessions with this WinStation driver.
} WDCONFIG, *PWDCONFIG;
// The protocol driver's software configuration.
typedef struct _PDCONFIG2
{
PDNAME PdName;
SDCLASS SdClass;
DLLNAME PdDLL;
ULONG PdFlag;
ULONG OutBufLength;
ULONG OutBufCount;
ULONG OutBufDelay;
ULONG InteractiveDelay;
ULONG PortNumber;
ULONG KeepAliveTimeout;
} PDCONFIG2, *PPDCONFIG2;
// WinStationClient
typedef struct _WINSTATIONCLIENT
{
ULONG fTextOnly : 1;
ULONG fDisableCtrlAltDel : 1;
ULONG fMouse : 1;
ULONG fDoubleClickDetect : 1;
ULONG fINetClient : 1;
ULONG fPromptForPassword : 1;
ULONG fMaximizeShell : 1;
ULONG fEnableWindowsKey : 1;
ULONG fRemoteConsoleAudio : 1;
ULONG fPasswordIsScPin : 1;
ULONG fNoAudioPlayback : 1;
ULONG fUsingSavedCreds : 1;
WCHAR ClientName[CLIENTNAME_LENGTH + 1];
WCHAR Domain[DOMAIN_LENGTH + 1];
WCHAR UserName[USERNAME_LENGTH + 1];
WCHAR Password[PASSWORD_LENGTH + 1];
WCHAR WorkDirectory[DIRECTORY_LENGTH + 1];
WCHAR InitialProgram[INITIALPROGRAM_LENGTH + 1];
ULONG SerialNumber;
BYTE EncryptionLevel;
ULONG ClientAddressFamily;
WCHAR ClientAddress[CLIENTADDRESS_LENGTH + 1];
USHORT HRes;
USHORT VRes;
USHORT ColorDepth;
USHORT ProtocolType;
ULONG KeyboardLayout;
ULONG KeyboardType;
ULONG KeyboardSubType;
ULONG KeyboardFunctionKey;
WCHAR ImeFileName[IMEFILENAME_LENGTH + 1];
WCHAR ClientDirectory[DIRECTORY_LENGTH + 1];
WCHAR ClientLicense[CLIENTLICENSE_LENGTH + 1];
WCHAR ClientModem[CLIENTMODEM_LENGTH + 1];
ULONG ClientBuildNumber;
ULONG ClientHardwareId;
USHORT ClientProductId;
USHORT OutBufCountHost;
USHORT OutBufCountClient;
USHORT OutBufLength;
WCHAR AudioDriverName[9];
TS_TIME_ZONE_INFORMATION ClientTimeZone;
ULONG ClientSessionId;
WCHAR ClientDigProductId[CLIENT_PRODUCT_ID_LENGTH];
ULONG PerformanceFlags;
ULONG ActiveInputLocale;
} WINSTATIONCLIENT, *PWINSTATIONCLIENT;
typedef struct _TSHARE_COUNTERS
{
ULONG Reserved;
} TSHARE_COUNTERS, *PTSHARE_COUNTERS;
typedef struct _PROTOCOLCOUNTERS
{
ULONG WdBytes;
ULONG WdFrames;
ULONG WaitForOutBuf;
ULONG Frames;
ULONG Bytes;
ULONG CompressedBytes;
ULONG CompressFlushes;
ULONG Errors;
ULONG Timeouts;
ULONG AsyncFramingError;
ULONG AsyncOverrunError;
ULONG AsyncOverflowError;
ULONG AsyncParityError;
ULONG TdErrors;
USHORT ProtocolType;
USHORT Length;
union
{
TSHARE_COUNTERS TShareCounters;
ULONG Reserved[100];
} Specific;
} PROTOCOLCOUNTERS, *PPROTOCOLCOUNTERS;
typedef struct _THINWIRECACHE
{
ULONG CacheReads;
ULONG CacheHits;
} THINWIRECACHE, *PTHINWIRECACHE;
#define MAX_THINWIRECACHE 4
typedef struct _RESERVED_CACHE
{
THINWIRECACHE ThinWireCache[MAX_THINWIRECACHE];
} RESERVED_CACHE, *PRESERVED_CACHE;
typedef struct _TSHARE_CACHE
{
ULONG Reserved;
} TSHARE_CACHE, *PTSHARE_CACHE;
typedef struct CACHE_STATISTICS
{
USHORT ProtocolType;
USHORT Length;
union
{
RESERVED_CACHE ReservedCacheStats;
TSHARE_CACHE TShareCacheStats;
ULONG Reserved[20];
} Specific;
} CACHE_STATISTICS, *PCACHE_STATISTICS;
typedef struct _PROTOCOLSTATUS
{
PROTOCOLCOUNTERS Output;
PROTOCOLCOUNTERS Input;
CACHE_STATISTICS Cache;
ULONG AsyncSignal;
ULONG AsyncSignalMask;
} PROTOCOLSTATUS, *PPROTOCOLSTATUS;
// Retrieves information on the session.
typedef struct _WINSTATIONINFORMATION
{
WINSTATIONSTATECLASS ConnectState;
WINSTATIONNAME WinStationName;
ULONG LogonId;
LARGE_INTEGER ConnectTime;
LARGE_INTEGER DisconnectTime;
LARGE_INTEGER LastInputTime;
LARGE_INTEGER LogonTime;
PROTOCOLSTATUS Status;
WCHAR Domain[DOMAIN_LENGTH + 1];
WCHAR UserName[USERNAME_LENGTH + 1];
LARGE_INTEGER CurrentTime;
} WINSTATIONINFORMATION, *PWINSTATIONINFORMATION;
// Retrieves the user's token in the session. Caller requires WINSTATION_ALL_ACCESS permission.
typedef struct _WINSTATIONUSERTOKEN
{
HANDLE ProcessId;
HANDLE ThreadId;
HANDLE UserToken;
} WINSTATIONUSERTOKEN, *PWINSTATIONUSERTOKEN;
// Retrieves resolution and color depth of the session.
typedef struct _WINSTATIONVIDEODATA
{
USHORT HResolution;
USHORT VResolution;
USHORT fColorDepth;
} WINSTATIONVIDEODATA, *PWINSTATIONVIDEODATA;
typedef enum _CDCLASS
{
CdNone, // No connection driver.
CdModem, // Connection driver is a modem.
CdClass_Maximum,
} CDCLASS;
// Connection driver configuration. It is used for connecting via modem to a server.
typedef struct _CDCONFIG
{
CDCLASS CdClass; // Connection driver type.
CDNAME CdName; // Connection driver descriptive name.
DLLNAME CdDLL; // Connection driver image name.
ULONG CdFlag; // Connection driver flags. Connection driver specific.
} CDCONFIG, *PCDCONFIG;
// The name has the following form:
// name syntax : xxxyyyy<null>
typedef CHAR CLIENTDATANAME[CLIENTDATANAME_LENGTH + 1];
typedef CHAR* PCLIENTDATANAME;
typedef struct _WINSTATIONCLIENTDATA
{
CLIENTDATANAME DataName; // Identifies the type of data sent in this WINSTATIONCLIENTDATA structure. The definition is dependent on the caller and on the client receiving it. This MUST be a data name following a format similar to that of the CLIENTDATANAME data type.
BOOLEAN fUnicodeData; // TRUE indicates data is in Unicode format; FALSE otherwise.
} WINSTATIONCLIENTDATA, *PWINSTATIONCLIENTDATA;
typedef enum _LOADFACTORTYPE
{
ErrorConstraint, // An error occurred while obtaining constraint data.
PagedPoolConstraint, // The amount of paged pool is the constraint.
NonPagedPoolConstraint, // The amount of non-paged pool is the constraint.
AvailablePagesConstraint, // The amount of available pages is the constraint.
SystemPtesConstraint, // The number of system page table entries (PTEs) is the constraint.
CPUConstraint // CPU usage is the constraint.
} LOADFACTORTYPE;
// The WINSTATIONLOADINDICATORDATA structure defines data used for the load balancing of a server.
typedef struct _WINSTATIONLOADINDICATORDATA
{
ULONG RemainingSessionCapacity; // The estimated number of additional sessions that can be supported given the CPU constraint.
LOADFACTORTYPE LoadFactor; // Indicates the most constrained current resource.
ULONG TotalSessions; // The total number of sessions.
ULONG DisconnectedSessions; // The number of disconnected sessions.
LARGE_INTEGER IdleCPU; // This is always set to 0.
LARGE_INTEGER TotalCPU; // This is always set to 0.
ULONG RawSessionCapacity; // The raw number of sessions capacity.
ULONG reserved[9]; // Reserved.
} WINSTATIONLOADINDICATORDATA, *PWINSTATIONLOADINDICATORDATA;
typedef enum _SHADOWSTATECLASS
{
State_NoShadow, // No shadow operations are currently being performed on this session.
State_Shadowing, // The session is shadowing a different session. The current session is referred to as a shadow client.
State_Shadowed // The session is being shadowed by a different session. The current session is referred to as a shadow target.
} SHADOWSTATECLASS;
// Retrieves the current shadow state of a session.
typedef struct _WINSTATIONSHADOW
{
SHADOWSTATECLASS ShadowState; // Specifies the current state of shadowing.
SHADOWCLASS ShadowClass; // Specifies the type of shadowing.
ULONG SessionId; // Specifies the session ID of the session.
ULONG ProtocolType; // Specifies the type of protocol on the session. Can be one of the following values.
} WINSTATIONSHADOW, *PWINSTATIONSHADOW;
// Retrieves the client product ID and current product ID of the session.
typedef struct _WINSTATIONPRODID
{
WCHAR DigProductId[CLIENT_PRODUCT_ID_LENGTH];
WCHAR ClientDigProductId[CLIENT_PRODUCT_ID_LENGTH];
WCHAR OuterMostDigProductId[CLIENT_PRODUCT_ID_LENGTH];
ULONG CurrentSessionId;
ULONG ClientSessionId;
ULONG OuterMostSessionId;
} WINSTATIONPRODID, *PWINSTATIONPRODID;
// Retrieves the remote IP address of the terminal server client in the session.
typedef struct _WINSTATIONREMOTEADDRESS
{
USHORT sin_family;
union
{
struct
{
USHORT sin_port;
ULONG sin_addr;
UCHAR sin_zero[8];
} ipv4;
struct
{
USHORT sin6_port;
ULONG sin6_flowinfo;
USHORT sin6_addr[8];
ULONG sin6_scope_id;
} ipv6;
};
} WINSTATIONREMOTEADDRESS, *PWINSTATIONREMOTEADDRESS;
// WinStationInformationEx
// private
typedef struct _WINSTATIONINFORMATIONEX_LEVEL1
{
ULONG SessionId;
WINSTATIONSTATECLASS SessionState;
LONG SessionFlags;
WINSTATIONNAME WinStationName;
WCHAR UserName[USERNAME_LENGTH + 1];
WCHAR DomainName[DOMAIN_LENGTH + 1];
LARGE_INTEGER LogonTime;
LARGE_INTEGER ConnectTime;
LARGE_INTEGER DisconnectTime;
LARGE_INTEGER LastInputTime;
LARGE_INTEGER CurrentTime;
PROTOCOLSTATUS ProtocolStatus;
} WINSTATIONINFORMATIONEX_LEVEL1, *PWINSTATIONINFORMATIONEX_LEVEL1;
// private
typedef struct _WINSTATIONINFORMATIONEX_LEVEL2
{
ULONG SessionId;
WINSTATIONSTATECLASS SessionState;
LONG SessionFlags;
WINSTATIONNAME WinStationName;
WCHAR SamCompatibleUserName[USERNAME_LENGTH + 1];
WCHAR SamCompatibleDomainName[DOMAIN_LENGTH + 1];
LARGE_INTEGER LogonTime;
LARGE_INTEGER ConnectTime;
LARGE_INTEGER DisconnectTime;
LARGE_INTEGER LastInputTime;
LARGE_INTEGER CurrentTime;
PROTOCOLSTATUS ProtocolStatus;
WCHAR UserName[257];
WCHAR DomainName[256];
} WINSTATIONINFORMATIONEX_LEVEL2, *PWINSTATIONINFORMATIONEX_LEVEL2;
// private
typedef union _WINSTATIONINFORMATIONEX_LEVEL
{
WINSTATIONINFORMATIONEX_LEVEL1 WinStationInfoExLevel1;
WINSTATIONINFORMATIONEX_LEVEL2 WinStationInfoExLevel2;
} WINSTATIONINFORMATIONEX_LEVEL, *PWINSTATIONINFORMATIONEX_LEVEL;
// private
typedef struct _WINSTATIONINFORMATIONEX
{
ULONG Level;
WINSTATIONINFORMATIONEX_LEVEL Data;
} WINSTATIONINFORMATIONEX, *PWINSTATIONINFORMATIONEX;
#define TS_PROCESS_INFO_MAGIC_NT4 0x23495452
typedef struct _TS_PROCESS_INFORMATION_NT4
{
ULONG MagicNumber;
ULONG LogonId;
PVOID ProcessSid;
ULONG Pad;
} TS_PROCESS_INFORMATION_NT4, *PTS_PROCESS_INFORMATION_NT4;
#define SIZEOF_TS4_SYSTEM_THREAD_INFORMATION 64
#define SIZEOF_TS4_SYSTEM_PROCESS_INFORMATION 136
typedef struct _TS_SYS_PROCESS_INFORMATION
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER SpareLi1;
LARGE_INTEGER SpareLi2;
LARGE_INTEGER SpareLi3;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
LONG BasePriority;
ULONG UniqueProcessId;
ULONG InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SessionId;
ULONG SpareUl3;
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
ULONG PeakWorkingSetSize;
ULONG WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
} TS_SYS_PROCESS_INFORMATION, *PTS_SYS_PROCESS_INFORMATION;
typedef struct _TS_ALL_PROCESSES_INFO
{
PTS_SYS_PROCESS_INFORMATION pTsProcessInfo;
ULONG SizeOfSid;
PSID pSid;
} TS_ALL_PROCESSES_INFO, *PTS_ALL_PROCESSES_INFO;
typedef struct _TS_COUNTER_HEADER
{
DWORD dwCounterID;
BOOLEAN bResult;
} TS_COUNTER_HEADER, *PTS_COUNTER_HEADER;
typedef struct _TS_COUNTER
{
TS_COUNTER_HEADER CounterHead;
DWORD dwValue;
LARGE_INTEGER StartTime;
} TS_COUNTER, *PTS_COUNTER;
// Flags for WinStationShutdownSystem
#define WSD_LOGOFF 0x1
#define WSD_SHUTDOWN 0x2
#define WSD_REBOOT 0x4
#define WSD_POWEROFF 0x8
// Flags for WinStationWaitSystemEvent
#define WEVENT_NONE 0x0
#define WEVENT_CREATE 0x1
#define WEVENT_DELETE 0x2
#define WEVENT_RENAME 0x4
#define WEVENT_CONNECT 0x8
#define WEVENT_DISCONNECT 0x10
#define WEVENT_LOGON 0x20
#define WEVENT_LOGOFF 0x40
#define WEVENT_STATECHANGE 0x80
#define WEVENT_LICENSE 0x100
#define WEVENT_ALL 0x7fffffff
#define WEVENT_FLUSH 0x80000000
// Hotkey modifiers for WinStationShadow
#define KBDSHIFT 0x1
#define KBDCTRL 0x2
#define KBDALT 0x4
// begin_rev
// Flags for WinStationRegisterConsoleNotification
#define WNOTIFY_ALL_SESSIONS 0x1
// end_rev
// In the functions below, memory returned can be freed using LocalFree. NULL can be specified for
// server handles to indicate the local server. -1 can be specified for session IDs to indicate the
// current session ID.
#define LOGONID_CURRENT (-1)
#define SERVERNAME_CURRENT ((PWSTR)NULL)
// rev
BOOLEAN
WINAPI
WinStationFreeMemory(
_In_ PVOID Buffer
);
// rev
HANDLE
WINAPI
WinStationOpenServerW(
_In_ PWSTR ServerName
);
// rev
BOOLEAN
WINAPI
WinStationCloseServer(
_In_ HANDLE ServerHandle
);
// rev
BOOLEAN
WINAPI
WinStationServerPing(
_In_opt_ HANDLE ServerHandle
);
// rev
BOOLEAN
WINAPI
WinStationGetTermSrvCountersValue(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG Count,
_Inout_ PTS_COUNTER Counters // set counter IDs before calling
);
BOOLEAN
WINAPI
WinStationShutdownSystem(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG ShutdownFlags // WSD_*
);
// rev
BOOLEAN
WINAPI
WinStationWaitSystemEvent(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG EventMask, // WEVENT_*
_Out_ PULONG EventFlags
);
// rev
BOOLEAN
WINAPI
WinStationRegisterConsoleNotification(
_In_opt_ HANDLE ServerHandle,
_In_ HWND WindowHandle,
_In_ ULONG Flags
);
// rev
BOOLEAN
WINAPI
WinStationUnRegisterConsoleNotification(
_In_opt_ HANDLE ServerHandle,
_In_ HWND WindowHandle
);
// Sessions
// rev
BOOLEAN
WINAPI
WinStationEnumerateW(
_In_opt_ HANDLE ServerHandle,
_Out_ PSESSIONIDW *SessionIds,
_Out_ PULONG Count
);
BOOLEAN
WINAPI
WinStationQueryInformationW(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ WINSTATIONINFOCLASS WinStationInformationClass,
_Out_writes_bytes_(WinStationInformationLength) PVOID pWinStationInformation,
_In_ ULONG WinStationInformationLength,
_Out_ PULONG pReturnLength
);
// rev
BOOLEAN
WINAPI
WinStationSetInformationW(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ WINSTATIONINFOCLASS WinStationInformationClass,
_In_reads_bytes_(WinStationInformationLength) PVOID pWinStationInformation,
_In_ ULONG WinStationInformationLength
);
BOOLEAN
WINAPI
WinStationNameFromLogonIdW(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_Out_writes_(WINSTATIONNAME_LENGTH + 1) PWSTR pWinStationName
);
// rev
BOOLEAN
WINAPI
WinStationSendMessageW(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ PWSTR Title,
_In_ ULONG TitleLength,
_In_ PWSTR Message,
_In_ ULONG MessageLength,
_In_ ULONG Style,
_In_ ULONG Timeout,
_Out_ PULONG Response,
_In_ BOOLEAN DoNotWait
);
BOOLEAN
WINAPI
WinStationConnectW(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ ULONG TargetSessionId,
_In_opt_ PWSTR pPassword,
_In_ BOOLEAN bWait
);
BOOLEAN
WINAPI
WinStationDisconnect(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ BOOLEAN bWait
);
// rev
BOOLEAN
WINAPI
WinStationReset(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ BOOLEAN bWait
);
// rev
BOOLEAN
WINAPI
WinStationShadow(
_In_opt_ HANDLE ServerHandle,
_In_ PWSTR TargetServerName,
_In_ ULONG TargetSessionId,
_In_ UCHAR HotKeyVk,
_In_ USHORT HotkeyModifiers // KBD*
);
// rev
BOOLEAN
WINAPI
WinStationShadowStop(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG SessionId,
_In_ BOOLEAN bWait // ignored
);
// Processes
// rev
BOOLEAN
WINAPI
WinStationEnumerateProcesses(
_In_opt_ HANDLE ServerHandle,
_Out_ PVOID *Processes
);
// rev
BOOLEAN
WINAPI
WinStationGetAllProcesses(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG Level,
_Out_ PULONG NumberOfProcesses,
_Out_ PTS_ALL_PROCESSES_INFO *Processes
);
// rev
BOOLEAN
WINAPI
WinStationFreeGAPMemory(
_In_ ULONG Level,
_In_ PTS_ALL_PROCESSES_INFO Processes,
_In_ ULONG NumberOfProcesses
);
// rev
BOOLEAN
WINAPI
WinStationTerminateProcess(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG ProcessId,
_In_ ULONG ExitCode
);
BOOLEAN
WINAPI
WinStationGetProcessSid(
_In_opt_ HANDLE ServerHandle,
_In_ ULONG ProcessId,
_In_ FILETIME ProcessStartTime,
_Out_ PVOID pProcessUserSid,
_Inout_ PULONG dwSidSize
);
// Services isolation
#if (NTDDI_VERSION >= NTDDI_VISTA)
// rev
BOOLEAN
WINAPI
WinStationSwitchToServicesSession(
VOID
);
// rev
BOOLEAN
WINAPI
WinStationRevertFromServicesSession(
VOID
);
#endif
// Misc.
BOOLEAN
WINAPI
_WinStationWaitForConnect(
VOID
);
#ifdef __cplusplus
}
#endif
#if _MSC_VER >= 1200
#pragma warning(pop)
#endif
#ifdef __cplusplus
#ifdef MINT_USE_SEPARATE_NAMESPACE
}
#endif
#endif
#endif // !_MINT_
| 23.818942 | 271 | 0.779488 | [
"object"
] |
96358051401c6a84b734f6d1e5f6b279372833f4 | 1,005 | h | C | L1Trigger/TrackFindingTracklet/interface/CandidateMatchMemory.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | L1Trigger/TrackFindingTracklet/interface/CandidateMatchMemory.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | L1Trigger/TrackFindingTracklet/interface/CandidateMatchMemory.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z | #ifndef L1Trigger_TrackFindingTracklet_interface_CandidateMatchMemory_h
#define L1Trigger_TrackFindingTracklet_interface_CandidateMatchMemory_h
#include "L1Trigger/TrackFindingTracklet/interface/MemoryBase.h"
#include <vector>
#include <string>
#include <utility>
namespace trklet {
class Settings;
class Stub;
class L1TStub;
class Tracklet;
class CandidateMatchMemory : public MemoryBase {
public:
CandidateMatchMemory(std::string name, Settings const& settings, unsigned int iSector);
~CandidateMatchMemory() override = default;
void addMatch(std::pair<Tracklet*, int> tracklet, const Stub* stub);
unsigned int nMatches() const { return matches_.size(); }
std::pair<std::pair<Tracklet*, int>, const Stub*> getMatch(unsigned int i) { return matches_[i]; }
void clean() override { matches_.clear(); }
void writeCM(bool first);
private:
std::vector<std::pair<std::pair<Tracklet*, int>, const Stub*> > matches_;
};
}; // namespace trklet
#endif
| 25.769231 | 102 | 0.736318 | [
"vector"
] |
9640733412a0b6f621cff797d4ccc90dbff1f25c | 2,944 | h | C | Gems/LyShine/Code/Editor/PropertiesWidget.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/LyShine/Code/Editor/PropertiesWidget.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/LyShine/Code/Editor/PropertiesWidget.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#if !defined(Q_MOC_RUN)
#include "EditorCommon.h"
#include <QWidget>
#include <QTimer>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/UI/PropertyEditor/ComponentEditor.hxx>
#endif
class PropertiesWidget
: public QWidget
, public AzToolsFramework::IPropertyEditorNotify
, public AzToolsFramework::ToolsApplicationEvents::Bus::Handler
{
Q_OBJECT
public:
PropertiesWidget(EditorWindow* editorWindow,
QWidget* parent = nullptr);
virtual ~PropertiesWidget();
QSize sizeHint() const override { return QSize(400, -1); }
//IPropertyEditorNotify Interface
void BeforePropertyModified(AzToolsFramework::InstanceDataNode* pNode) override;
void AfterPropertyModified(AzToolsFramework::InstanceDataNode* pNode) override;
void SetPropertyEditingActive(AzToolsFramework::InstanceDataNode* pNode) override;
void SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* pNode) override;
void SealUndoStack() override;
void RequestPropertyContextMenu(AzToolsFramework::InstanceDataNode* node, const QPoint& globalPos) override;
//ToolsApplicationEvents Interface
void InvalidatePropertyDisplay(AzToolsFramework::PropertyModificationRefreshLevel level) override;
void TriggerRefresh(AzToolsFramework::PropertyModificationRefreshLevel refreshLevel = AzToolsFramework::PropertyModificationRefreshLevel::Refresh_EntireTree, const AZ::Uuid* componentType = nullptr);
void TriggerImmediateRefresh(AzToolsFramework::PropertyModificationRefreshLevel refreshLevel = AzToolsFramework::PropertyModificationRefreshLevel::Refresh_EntireTree, const AZ::Uuid* componentType = nullptr);
// Notify the properties pane when a selected entity has been recreated
void SelectedEntityPointersChanged();
void SetSelectedEntityDisplayNameWidget(QLineEdit* selectedEntityDisplayNameWidget);
void SetEditorOnlyCheckbox(QCheckBox* editorOnlyCheckbox);
float GetScrollValue();
void SetScrollValue(float scrollValue);
AZ::Entity::ComponentArrayType GetSelectedComponents();
public slots:
void UserSelectionChanged(HierarchyItemRawPtrList* items);
private slots:
void Refresh(AzToolsFramework::PropertyModificationRefreshLevel refreshLevel = AzToolsFramework::PropertyModificationRefreshLevel::Refresh_EntireTree, const AZ::Uuid* componentType = nullptr);
private:
EditorWindow* m_editorWindow;
QTimer m_refreshTimer;
SerializeHelpers::SerializedEntryList m_preValueChanges;
PropertiesContainer* m_propertiesContainer;
AZStd::string m_canvasUndoXml;
AZ::Uuid m_componentTypeToRefresh;
AzToolsFramework::PropertyModificationRefreshLevel m_refreshLevel;
};
| 36.345679 | 212 | 0.800951 | [
"3d"
] |
96536ab27f768bd0581fc7bb94f53f9dceea398b | 3,047 | h | C | src/MacVim/MMTextViewHelper.h | raidurgesh/macvim-dev-macvim | e7f312f4ac8b21dccb0223b48aba091a53554fad | [
"Vim"
] | 76 | 2015-01-04T17:54:33.000Z | 2021-12-16T07:18:57.000Z | src/MacVim/MMTextViewHelper.h | raidurgesh/macvim-dev-macvim | e7f312f4ac8b21dccb0223b48aba091a53554fad | [
"Vim"
] | 17 | 2015-01-28T08:51:07.000Z | 2022-01-18T20:39:40.000Z | src/MacVim/MMTextViewHelper.h | raidurgesh/macvim-dev-macvim | e7f312f4ac8b21dccb0223b48aba091a53554fad | [
"Vim"
] | 6 | 2015-01-28T09:33:39.000Z | 2016-09-14T06:43:11.000Z | /* vi:set ts=8 sts=4 sw=4 ft=objc:
*
* VIM - Vi IMproved by Bram Moolenaar
* MacVim GUI port by Bjorn Winckler
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
#import <Cocoa/Cocoa.h>
// Need Carbon for TIS...() functions
#import <Carbon/Carbon.h>
#define BLUE(argb) ((argb & 0xff)/255.0f)
#define GREEN(argb) (((argb>>8) & 0xff)/255.0f)
#define RED(argb) (((argb>>16) & 0xff)/255.0f)
#define ALPHA(argb) (((argb>>24) & 0xff)/255.0f)
@interface MMTextViewHelper : NSObject {
id textView;
BOOL isDragging;
int dragRow;
int dragColumn;
int dragFlags;
NSPoint dragPoint;
BOOL isAutoscrolling;
int mouseShape;
NSColor *insertionPointColor;
BOOL interpretKeyEventsSwallowedKey;
NSEvent *currentEvent;
NSMutableDictionary *signImages;
BOOL useMouseTime;
NSDate *mouseDownTime;
// Input Manager
NSRange imRange;
NSRange markedRange;
NSDictionary *markedTextAttributes;
NSMutableAttributedString *markedText;
int preEditRow;
int preEditColumn;
BOOL imControl;
BOOL imState;
TISInputSourceRef lastImSource;
TISInputSourceRef asciiImSource;
}
- (id)init;
- (void)setTextView:(id)view;
- (void)setInsertionPointColor:(NSColor *)color;
- (NSColor *)insertionPointColor;
- (void)keyDown:(NSEvent *)event;
- (void)insertText:(id)string;
- (void)doCommandBySelector:(SEL)selector;
- (void)scrollWheel:(NSEvent *)event;
- (void)mouseDown:(NSEvent *)event;
- (void)mouseUp:(NSEvent *)event;
- (void)mouseDragged:(NSEvent *)event;
- (void)mouseMoved:(NSEvent *)event;
- (void)swipeWithEvent:(NSEvent *)event;
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender;
- (void)setMouseShape:(int)shape;
- (void)changeFont:(id)sender;
- (NSImage *)signImageForName:(NSString *)imgName;
- (void)deleteImage:(NSString *)imgName;
// Input Manager
- (BOOL)hasMarkedText;
- (NSRange)markedRange;
- (NSDictionary *)markedTextAttributes;
- (void)setMarkedTextAttributes:(NSDictionary *)attr;
- (void)setMarkedText:(id)text selectedRange:(NSRange)range;
- (void)unmarkText;
- (NSMutableAttributedString *)markedText;
- (void)setPreEditRow:(int)row column:(int)col;
- (int)preEditRow;
- (int)preEditColumn;
- (void)setImRange:(NSRange)range;
- (NSRange)imRange;
- (void)setMarkedRange:(NSRange)range;
- (NSRect)firstRectForCharacterRange:(NSRange)range;
- (void)setImControl:(BOOL)enable;
- (void)activateIm:(BOOL)enable;
- (BOOL)useInlineIm;
- (void)checkImState;
@end
| 32.073684 | 69 | 0.64785 | [
"shape"
] |
9653b73de393f740c5f490fc5eb665d2a0751f64 | 531 | h | C | include/melo/zone.h | itamar244/melolang | b2ff4f8aaef95f9a2d9a7fbcb1db8c07620d6fde | [
"MIT"
] | null | null | null | include/melo/zone.h | itamar244/melolang | b2ff4f8aaef95f9a2d9a7fbcb1db8c07620d6fde | [
"MIT"
] | null | null | null | include/melo/zone.h | itamar244/melolang | b2ff4f8aaef95f9a2d9a7fbcb1db8c07620d6fde | [
"MIT"
] | null | null | null | #pragma once
#include <cstdlib>
#include <atic/stack.h>
namespace melo {
class ZoneObject;
class Zone {
public:
~Zone();
void* New(std::size_t size);
inline void Add(ZoneObject* object) {
ptrs_.push(object);
}
private:
atic::Stack<ZoneObject*> ptrs_;
};
class ZoneObject {
public:
virtual ~ZoneObject() {}
inline void* operator new(std::size_t size, Zone* zone) {
return zone->New(size);
}
inline void* operator new(std::size_t size) {
return ::operator new(size);
}
};
} // namespace melo
| 14.75 | 59 | 0.655367 | [
"object"
] |
9655da02f04710d221fd0aa18492dcbbe29b1184 | 2,228 | h | C | ash/system/chromeos/network/tray_vpn.h | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | ash/system/chromeos/network/tray_vpn.h | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/system/chromeos/network/tray_vpn.h | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:31.000Z | 2020-11-04T07:19:31.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SYSTEM_CHROMEOS_NETWORK_TRAY_VPN_H
#define ASH_SYSTEM_CHROMEOS_NETWORK_TRAY_VPN_H
#include "ash/system/chromeos/network/network_observer.h"
#include "ash/system/tray/system_tray_item.h"
#include "base/memory/scoped_ptr.h"
namespace ash {
namespace internal {
namespace tray {
class NetworkDetailedView;
class VpnDefaultView;
class VpnDetailedView;
}
class TrayVPN : public SystemTrayItem,
public NetworkObserver {
public:
explicit TrayVPN(SystemTray* system_tray);
virtual ~TrayVPN();
// Overridden from SystemTrayItem.
virtual views::View* CreateTrayView(user::LoginStatus status) OVERRIDE;
virtual views::View* CreateDefaultView(user::LoginStatus status) OVERRIDE;
virtual views::View* CreateDetailedView(user::LoginStatus status) OVERRIDE;
virtual views::View* CreateNotificationView(
user::LoginStatus status) OVERRIDE;
virtual void DestroyTrayView() OVERRIDE;
virtual void DestroyDefaultView() OVERRIDE;
virtual void DestroyDetailedView() OVERRIDE;
virtual void DestroyNotificationView() OVERRIDE;
virtual void UpdateAfterLoginStatusChange(user::LoginStatus status) OVERRIDE;
virtual void UpdateAfterShelfAlignmentChange(
ShelfAlignment alignment) OVERRIDE;
// Overridden from NetworkObserver.
virtual void OnNetworkRefresh(const NetworkIconInfo& info) OVERRIDE;
virtual void SetNetworkMessage(NetworkTrayDelegate* delegate,
MessageType message_type,
NetworkType network_type,
const string16& title,
const string16& message,
const std::vector<string16>& links) OVERRIDE;
virtual void ClearNetworkMessage(MessageType message_type) OVERRIDE;
virtual void OnWillToggleWifi() OVERRIDE;
private:
tray::VpnDefaultView* default_;
tray::NetworkDetailedView* detailed_;
DISALLOW_COPY_AND_ASSIGN(TrayVPN);
};
} // namespace internal
} // namespace ash
#endif // ASH_SYSTEM_CHROMEOS_NETWORK_TRAY_VPN_H
| 35.365079 | 79 | 0.735189 | [
"vector"
] |
96594e6f2f284e82f038ed5bc188cf94ec532b84 | 12,951 | h | C | src/LuaTypes.h | ORB-HD/Puppeteer | 6b9cea9e74987932ff8ed3bcb562eaa4abd39355 | [
"MIT"
] | 10 | 2016-06-17T10:41:32.000Z | 2021-06-10T13:14:21.000Z | src/LuaTypes.h | ORB-HD/Puppeteer | 6b9cea9e74987932ff8ed3bcb562eaa4abd39355 | [
"MIT"
] | 2 | 2016-05-20T09:56:45.000Z | 2017-01-13T12:29:25.000Z | src/LuaTypes.h | ORB-HD/Puppeteer | 6b9cea9e74987932ff8ed3bcb562eaa4abd39355 | [
"MIT"
] | 3 | 2018-03-31T01:29:13.000Z | 2020-10-21T14:27:15.000Z | /*
* Puppeteer - A Motion Capture Mapping Tool
* Copyright (c) 2013-2016 Martin Felis <martin.felis@iwr.uni-heidelberg.de>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE*
*/
#ifndef MARKER_MODEL_LUA_TYPES
#define MARKER_MODEL_LUA_TYPES
#include "Model.h"
#include <rbdl/rbdl_math.h>
#include <rbdl/addons/luamodel/luatables.h>
// SimpleMath Vector3f
template<> Vector3f LuaTableNode::getDefault<Vector3f>(const Vector3f &default_value) {
Vector3f result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
if (vector_table.length() != 3) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 3d vector!" << std::endl;
abort();
}
result[0] = static_cast<float>(vector_table[1].get<double>());
result[1] = static_cast<float>(vector_table[2].get<double>());
result[2] = static_cast<float>(vector_table[3].get<double>());
}
stackRestore();
return result;
}
template<>
void LuaTableNode::set<Vector3f>(const Vector3f &value) {
LuaTable custom_table = stackCreateLuaTable();
custom_table[1] = static_cast<double>(value[0]);
custom_table[2] = static_cast<double>(value[1]);
custom_table[3] = static_cast<double>(value[2]);
stackRestore();
}
// SimpleMath Vector4f
template<> Vector4f LuaTableNode::getDefault<Vector4f>(const Vector4f &default_value) {
Vector4f result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
if (vector_table.length() != 4) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 4d vector!" << std::endl;
abort();
}
result[0] = static_cast<float>(vector_table[1].get<double>());
result[1] = static_cast<float>(vector_table[2].get<double>());
result[2] = static_cast<float>(vector_table[3].get<double>());
result[3] = static_cast<float>(vector_table[4].get<double>());
}
stackRestore();
return result;
}
// SimpleMath Matrix33f
template<> SimpleMath::Fixed::Matrix<float, 3, 3> LuaTableNode::getDefault<SimpleMath::Fixed::Matrix<float, 3, 3> >(const SimpleMath::Fixed::Matrix<float, 3, 3> &default_value) {
SimpleMath::Fixed::Matrix<float, 3, 3> result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
if (vector_table.length() != 3) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 3d matrix!" << std::endl;
abort();
}
if (vector_table[1].length() != 3
|| vector_table[2].length() != 3
|| vector_table[3].length() != 3) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 3d matrix!" << std::endl;
abort();
}
result(0,0) = static_cast<float>(vector_table[1][1].get<double>());
result(0,1) = static_cast<float>(vector_table[1][2].get<double>());
result(0,2) = static_cast<float>(vector_table[1][3].get<double>());
result(1,0) = static_cast<float>(vector_table[2][1].get<double>());
result(1,1) = static_cast<float>(vector_table[2][2].get<double>());
result(1,2) = static_cast<float>(vector_table[2][3].get<double>());
result(2,0) = static_cast<float>(vector_table[3][1].get<double>());
result(2,1) = static_cast<float>(vector_table[3][2].get<double>());
result(2,2) = static_cast<float>(vector_table[3][3].get<double>());
}
stackRestore();
return result;
}
template<>
void LuaTableNode::set<SimpleMath::Fixed::Matrix<float, 3, 3> >(const SimpleMath::Fixed::Matrix<float, 3, 3> &value) {
LuaTable custom_table = stackCreateLuaTable();
custom_table[1][1] = static_cast<double>(value(0,0));
custom_table[1][2] = static_cast<double>(value(0,1));
custom_table[1][3] = static_cast<double>(value(0,2));
custom_table[2][1] = static_cast<double>(value(1,0));
custom_table[2][2] = static_cast<double>(value(1,1));
custom_table[2][3] = static_cast<double>(value(1,2));
custom_table[3][1] = static_cast<double>(value(2,0));
custom_table[3][2] = static_cast<double>(value(2,1));
custom_table[3][3] = static_cast<double>(value(2,2));
stackRestore();
}
template<> RigidBodyDynamics::Math::Vector3d LuaTableNode::getDefault<RigidBodyDynamics::Math::Vector3d>(const RigidBodyDynamics::Math::Vector3d &default_value) {
RigidBodyDynamics::Math::Vector3d result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
if (vector_table.length() != 3) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 3d vector!" << std::endl;
abort();
}
result[0] = vector_table[1];
result[1] = vector_table[2];
result[2] = vector_table[3];
}
stackRestore();
return result;
}
template<> RigidBodyDynamics::Math::SpatialVector LuaTableNode::getDefault<RigidBodyDynamics::Math::SpatialVector>(const RigidBodyDynamics::Math::SpatialVector &default_value) {
RigidBodyDynamics::Math::SpatialVector result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
if (vector_table.length() != 6) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 6d vector!" << std::endl;
abort();
}
result[0] = vector_table[1];
result[1] = vector_table[2];
result[2] = vector_table[3];
result[3] = vector_table[4];
result[4] = vector_table[5];
result[5] = vector_table[6];
}
stackRestore();
return result;
}
template<> RigidBodyDynamics::Math::Matrix3d LuaTableNode::getDefault<RigidBodyDynamics::Math::Matrix3d>(const RigidBodyDynamics::Math::Matrix3d &default_value) {
RigidBodyDynamics::Math::Matrix3d result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
if (vector_table.length() != 3) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 3d matrix!" << std::endl;
abort();
}
if (vector_table[1].length() != 3
|| vector_table[2].length() != 3
|| vector_table[3].length() != 3) {
std::cerr << "LuaModel Error at " << keyStackToString() << " : invalid 3d matrix!" << std::endl;
abort();
}
result(0,0) = vector_table[1][1];
result(0,1) = vector_table[1][2];
result(0,2) = vector_table[1][3];
result(1,0) = vector_table[2][1];
result(1,1) = vector_table[2][2];
result(1,2) = vector_table[2][3];
result(2,0) = vector_table[3][1];
result(2,1) = vector_table[3][2];
result(2,2) = vector_table[3][3];
}
stackRestore();
return result;
}
template<> RigidBodyDynamics::Math::SpatialTransform LuaTableNode::getDefault<RigidBodyDynamics::Math::SpatialTransform>(const RigidBodyDynamics::Math::SpatialTransform &default_value) {
RigidBodyDynamics::Math::SpatialTransform result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
result.r = vector_table["r"].getDefault<RigidBodyDynamics::Math::Vector3d>(RigidBodyDynamics::Math::Vector3d::Zero(3));
result.E = vector_table["E"].getDefault<RigidBodyDynamics::Math::Matrix3d>(RigidBodyDynamics::Math::Matrix3d::Identity (3,3));
}
stackRestore();
return result;
}
template<> RigidBodyDynamics::Joint LuaTableNode::getDefault<RigidBodyDynamics::Joint>(const RigidBodyDynamics::Joint &default_value) {
using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;
Joint result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
int joint_dofs = vector_table.length();
if (joint_dofs == 1) {
std::string dof_string = vector_table[1].getDefault<std::string>("");
if (dof_string == "JointTypeSpherical") {
stackRestore();
return Joint(JointTypeSpherical);
} else if (dof_string == "JointTypeEulerZYX") {
stackRestore();
return Joint(JointTypeEulerZYX);
}
if (dof_string == "JointTypeEulerXYZ") {
stackRestore();
return Joint(JointTypeEulerXYZ);
}
if (dof_string == "JointTypeEulerYXZ") {
stackRestore();
return Joint(JointTypeEulerYXZ);
}
if (dof_string == "JointTypeTranslationXYZ") {
stackRestore();
return Joint(JointTypeTranslationXYZ);
}
}
if (joint_dofs > 0) {
if (vector_table[1].length() != 6) {
std::cerr << "LuaModel Error: invalid joint motion subspace description at " << this->keyStackToString() << std::endl;
abort();
}
}
switch (joint_dofs) {
case 0: result = Joint(JointTypeFixed);
break;
case 1: result = Joint (vector_table[1].get<SpatialVector>());
break;
case 2: result = Joint(
vector_table[1].get<SpatialVector>(),
vector_table[2].get<SpatialVector>()
);
break;
case 3: result = Joint(
vector_table[1].get<SpatialVector>(),
vector_table[2].get<SpatialVector>(),
vector_table[3].get<SpatialVector>()
);
break;
case 4: result = Joint(
vector_table[1].get<SpatialVector>(),
vector_table[2].get<SpatialVector>(),
vector_table[3].get<SpatialVector>(),
vector_table[4].get<SpatialVector>()
);
break;
case 5: result = Joint(
vector_table[1].get<SpatialVector>(),
vector_table[2].get<SpatialVector>(),
vector_table[3].get<SpatialVector>(),
vector_table[4].get<SpatialVector>(),
vector_table[5].get<SpatialVector>()
);
break;
case 6: result = Joint(
vector_table[1].get<SpatialVector>(),
vector_table[2].get<SpatialVector>(),
vector_table[3].get<SpatialVector>(),
vector_table[4].get<SpatialVector>(),
vector_table[5].get<SpatialVector>(),
vector_table[6].get<SpatialVector>()
);
break;
default:
std::cerr << "Invalid number of DOFs for joint." << std::endl;
abort();
}
}
stackRestore();
return result;
}
template<> RigidBodyDynamics::Body LuaTableNode::getDefault<RigidBodyDynamics::Body>(const RigidBodyDynamics::Body &default_value) {
RigidBodyDynamics::Body result = default_value;
if (stackQueryValue()) {
LuaTable vector_table = LuaTable::fromLuaState (luaTable->L);
double mass = 0.;
RigidBodyDynamics::Math::Vector3d com (RigidBodyDynamics::Math::Vector3d::Zero(3));
RigidBodyDynamics::Math::Matrix3d inertia (RigidBodyDynamics::Math::Matrix3d::Identity(3,3));
mass = vector_table["mass"];
com = vector_table["com"].getDefault<RigidBodyDynamics::Math::Vector3d>(com);
inertia = vector_table["inertia"].getDefault<RigidBodyDynamics::Math::Matrix3d>(inertia);
result = RigidBodyDynamics::Body (mass, com, inertia);
}
stackRestore();
return result;
}
template<> VisualsData LuaTableNode::getDefault<VisualsData>(const VisualsData &default_value) {
VisualsData result = default_value;
if (stackQueryValue()) {
LuaTable visuals_table = LuaTable::fromLuaState (luaTable->L);
result.scale = visuals_table["scale"].getDefault(Vector3f (1.f, 1.f, 1.f));
result.dimensions = visuals_table["dimensions"].getDefault(Vector3f (0.f, 0.f, 0.f));
if (visuals_table["color"].length() == 4)
result.color = visuals_table["color"].getDefault(Vector4f (-1.f, -1.f, -1.f, 1.f));
else {
Vector3f vec3_color = visuals_table["color"].getDefault(Vector3f (-1.f, -1.f, -1.f));
result.color = Vector4f (vec3_color[0], vec3_color[1], vec3_color[2], 1.f);
}
result.mesh_center = visuals_table["mesh_center"].getDefault(Vector3f (-1.f, -1.f, -1.f));
result.translate = visuals_table["translate"].getDefault(Vector3f (-1.f, -1.f, -1.f));
if (visuals_table["rotate"].exists()) {
Vector3f axis = visuals_table["rotate"]["axis"];
double angle = visuals_table["rotate"]["angle"];
result.orientation = SimpleMath::GL::Quaternion::fromGLRotate (angle, axis[0], axis[1], axis[2]);
}
result.src = visuals_table["src"].getDefault<std::string>("");
}
stackRestore();
return result;
}
/* MARKER_MODEL_LUA_TYPES */
#endif
| 33.378866 | 186 | 0.684658 | [
"vector",
"model",
"3d"
] |
965d1900bc8474b0101fa0b4bfe6f961867beece | 23,710 | h | C | GameBoyAdvance/spew/Output.h | subatomicglue/ankh | 12ad73af4168dbb87a05773b73fba029f1d105b7 | [
"MIT"
] | null | null | null | GameBoyAdvance/spew/Output.h | subatomicglue/ankh | 12ad73af4168dbb87a05773b73fba029f1d105b7 | [
"MIT"
] | null | null | null | GameBoyAdvance/spew/Output.h | subatomicglue/ankh | 12ad73af4168dbb87a05773b73fba029f1d105b7 | [
"MIT"
] | null | null | null | /*
spew - semi-powerful trace logger, debug output, stderr/stdout
Copyright (c) 2006 kevin meinert all rights reserved
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
#ifndef OUTPUT_SYSTEM
#define OUTPUT_SYSTEM
#include <vector>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdarg.h> // varargs
#include <assert.h>
#include <cstdio> // vsnprinf
#include "OstreamTemplate.h"
# include "OutputDebugStringOstream.h" //< compiler trace window output
#include "the.h" //< singleton generator
#ifdef ERROR // wingdi.h has this :(
#undef ERROR
#endif
/// SPEW!
/// The 'spew' output system is contained inside the spew namespace.
/// If you'd like to change the namespace, just #define SPEWNAMESPACE to your own name...
/// Most users of spew will use the following features:
/// @see OutputBase, (also Log, Trace, StdErr, StdOut) below for code examples and usage.
#ifndef SPEWNAMESPACE
namespace spew // default namespace to use is "spew".
#define SPEWNAMESPACE spew
#else
namespace SPEWNAMESPACE // otherwise, use user-supplied namespace name if provided
#endif
{
/// list of filters available,
/// use these enums when outputting, and when
/// setting Output::SetFilter
/// modify this to add new ones.
/// --> hey!!! keep this in sync with gTagDescriptions below
enum Filter
{
FILTERDEFAULT = 0xffffffff, //< FILTERALL
FILTERALL = 0xffffffff, //< always output
FILTERNONE = 0x00000000, //< never output
GFX = 0x00000001,
SCRIPT = 0x00000002,
SOUND = 0x00000004,
PHYSICS = 0x00000008,
IO = 0x00000010,
ANIM = 0x00000020,
LUA = 0x00000040,
ERROR = 0x00000080,
ACTOR = 0x00000100,
APP = 0x00000200,
};
/// use these enums when outputting
/// --> hey!!! keep this in sync with gTagDescriptions below
enum Level
{
// use these in both SetLevel and when Outputing
LEVEL1 = 0x00000001,
LEVEL2 = 0x00000002,
LEVEL3 = 0x00000004,
LEVEL4 = 0x00000008,
LEVEL5 = 0x00000010,
// use these in SetLevel (not when outputing)
LEVELNONE = 0x00000000, //< never output
LEVEL1ANDLOWER = 0x00000001,
LEVEL2ANDLOWER = 0x00000003,
LEVEL3ANDLOWER = 0x00000007,
LEVEL4ANDLOWER = 0x0000000f,
LEVEL5ANDLOWER = 0x0000001f,
LEVELALL = 0xffffffff, //< output any level
// just a constant, don't use this
_LEVELHIGHEST = 5,
_LEVELDEFAULT = 0x00000001, //< L1 is default
};
// used for command line parsing (keep this in sync with the above)
// also, keep parseCommandLine(..) below in sync...
struct TagDescription
{
const char* mName;
int mTag;
};
const TagDescription gTagDescriptions[] =
{
{ "GFX", GFX },
{ "SCRIPT", SCRIPT },
{ "SOUND", SOUND },
{ "PHYSICS", PHYSICS },
{ "IO", IO },
{ "ANIM", ANIM },
{ "LUA", LUA },
{ "ERROR", ERROR },
{ "ACTOR", ACTOR },
{ "APP", APP },
{ "Off", LEVELNONE },
{ "1", LEVEL1ANDLOWER },
{ "2", LEVEL2ANDLOWER },
{ "3", LEVEL3ANDLOWER },
{ "4", LEVEL4ANDLOWER },
{ "5", LEVEL5ANDLOWER },
{ "1only", LEVEL1 },
{ "2only", LEVEL2 },
{ "3only", LEVEL3 },
{ "4only", LEVEL4 },
{ "5only", LEVEL5 },
{ "Max", LEVELALL },
{ "", 0 } // keep this last...
};
/// converter between integers and LevelType
struct Level_
{
inline Level_( const int number )
{
assert( 1 <= number && number <= _LEVELHIGHEST && "error: level exceeded" );
const Level lt[] = { LEVEL1, LEVEL2, LEVEL3, LEVEL4, LEVEL5 };
mType = lt[number-1];
}
inline Level_( const Level level ) { mType = level; }
inline operator const Level() const { return mType; }
Level mType;
};
/// converter between integers and LevelType
struct LevelSelect_
{
inline LevelSelect_( const int number )
{
assert( 1 <= number && number <= _LEVELHIGHEST && "error: level exceeded" );
const Level lt[] = { LEVEL1ANDLOWER, LEVEL2ANDLOWER, LEVEL3ANDLOWER, LEVEL4ANDLOWER, LEVEL5ANDLOWER };
mType = lt[number-1];
}
inline LevelSelect_( const Level level ) { mType = level; }
inline operator const Level() const { return mType; }
Level mType;
};
/// output base type
/// all text output goes through this for logging, trace messages, command line output, etc...
/// see output types (under '@see' below) for examples of how to extend.
/// catagory filters are available.
///
/// for usage:
/// - ignore this class
/// - refer to StdOut, StdErr, Log, and Trace types below
///
/// examples:
/// @code
/// Log( "hi %s", steve );
/// Log( GFX, "hi %s", steve );
/// Log << "default category, default level" << std::endl;
/// Log( GFX, 0 ) << "render category, level 0!" << std::endl;
/// @endcode
/// @see Log, StdErr, StdOut, Trace
template <typename OUTPUTBASE_INIT, unsigned INCLUDE_IN_RELEASE_MODE = 0>
class OutputBase
{
/// some compile-time constants to query if we're in debug mode...
enum
{
MAX_BUF_SIZE = 256,
#ifdef _DEBUG
IN_DEBUG_MODE = 1
#else
IN_DEBUG_MODE = 0
#endif
};
public:
/// constructor
OutputBase()
{
mStreamOut.out.mParent = this;
mGlobalFilter = FILTERDEFAULT;
mGlobalLevel = _LEVELDEFAULT;
mOutputBaseInit.init( *this );
}
/// set the logging filter.
/// all messages that aren't inluded in this
/// filter are filtered out before outputting...
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut.SetFilter( GFX );
/// @endcode
inline void SetFilter( int filter ) { mGlobalFilter = filter; }
inline void AddFilter( int filter ) { mGlobalFilter |= filter; }
inline void RemoveFilter( int filter ) { mGlobalFilter &= ~filter; }
/// reset to default filter and default level...
inline void SetDefaults() { mOutputBaseInit.reset( *this ); }
/// set the logging level.
/// messages not included in this level are filtered out before outputting...
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut.SetLevel( LEVEL4ANDLOWER );
/// @endcode
inline void SetLevel( LevelSelect_ level ) { mGlobalLevel = level; }
/// send formatted text to the output, similar to printf in the C stdlib
/// uses default filter and level
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut( "hi %s", steve );
/// @endcode
inline void operator()( const char fmtstr[], ... )
{
if (INCLUDE_IN_RELEASE_MODE || IN_DEBUG_MODE)
{
va_list arg_ptr;
va_start( arg_ptr, fmtstr );
operator()( FILTERDEFAULT, fmtstr, arg_ptr );
va_end( arg_ptr );
}
}
/// send formatted text to the output, similar to printf in the C stdlib
/// specify a filter, uses default level.
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut( GFX, "hi %s", steve );
/// @endcode
inline void operator()( Filter filter, const char fmtstr[], ... )
{
if (INCLUDE_IN_RELEASE_MODE || IN_DEBUG_MODE)
{
va_list arg_ptr;
va_start( arg_ptr, fmtstr );
operator()( filter, fmtstr, arg_ptr );
va_end( arg_ptr );
}
}
/// send formatted text to the output, similar to printf in the C stdlib
/// specify a filter and level.
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut( GFX, 1, "hi %s", steve );
/// @endcode
inline void operator()( Filter filter, Level_ level, const char fmtstr[], ... )
{
if (INCLUDE_IN_RELEASE_MODE || IN_DEBUG_MODE)
{
va_list arg_ptr;
va_start( arg_ptr, fmtstr );
operator()( filter, level, fmtstr, arg_ptr );
va_end( arg_ptr );
}
}
/// vararg compatible implementation of print, most users wont need this.
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// void myprintf( const char* str, ... )
/// {
/// va_list arg_ptr;
/// va_start( arg_ptr, fmtstr );
/// StdOut( GFX, 2, arg_ptr );
/// va_end( arg_ptr );
/// }
/// @endcode
void operator()( Filter filter, Level_ level, const char fmtstr[], va_list& arg_ptr )
{
if (INCLUDE_IN_RELEASE_MODE || IN_DEBUG_MODE)
{
static char buf[MAX_BUF_SIZE] = "\0";
#ifdef WIN32
_vsnprintf( buf, MAX_BUF_SIZE, fmtstr, arg_ptr );
#else
vsprintf( buf, fmtstr, arg_ptr );
assert( strlen( buf ) <= MAX_BUF_SIZE && "overflow" );
#endif
// ensure nul termination
buf[MAX_BUF_SIZE-1] = '\0';
// output to every output stream if the filter matches.
if (0 != (filter & mGlobalFilter) && 0 != (level.mType & mGlobalLevel))
for (size_t x = 0; x < mOutStreams.size(); ++x)
(*mOutStreams[x]) << buf << std::flush;
}
}
/// vararg compatible implementation of print (+ level), most users wont need this.
inline void operator()( Filter filter, const char fmtstr[], va_list& arg_ptr )
{
operator()( filter, _LEVELDEFAULT, fmtstr, arg_ptr );
}
/// ostream with filter and level specified
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut( GFX, 2 ) << "this is a test" << std::endl;
/// @endcode
inline std::ostream& operator()( Filter filter, Level_ level = _LEVELDEFAULT )
{
mStreamOut.out.mFilter = filter;
mStreamOut.out.mLevel = level;
return mStreamOut;
}
/// ostream with no args (default filter and level)
/// usage:
/// @code
/// #define StdOut OutputBase<StdOutInit>::instance()
/// StdOut << "this is a test" << std::endl;
/// @endcode
template <typename T>
inline std::ostream& operator<<( T& blah )
{
if (INCLUDE_IN_RELEASE_MODE || IN_DEBUG_MODE)
{
mStreamOut << blah;
}
return mStreamOut;
}
/// get output object as an o-stream
inline operator std::ostream&() { return mStreamOut; }
/// holds the singleton object for each output type.
static OutputBase& instance() { static OutputBase blah; return blah; }
/// list of output streams available.
std::vector<std::ostream*> mOutStreams;
//unsigned int mOutputFilter, mOutputLevel;
unsigned int mGlobalFilter, mGlobalLevel; //< global filter setting
OUTPUTBASE_INIT mOutputBaseInit; //< used to initialize this outputter.
private:
/// output functor for the OstreamTemplate (mStreamOut)...
struct OutputAdaptor
{
OutputAdaptor() : mParent( NULL ), mFilter( FILTERDEFAULT ), mLevel( _LEVELDEFAULT ) {}
inline void printf( const char* const str )
{
if (INCLUDE_IN_RELEASE_MODE || IN_DEBUG_MODE)
{
mParent->operator()( mFilter, mLevel, str );
}
}
OutputBase* mParent;
Filter mFilter;
Level mLevel;
};
/// a stream for this output class...
OstreamTemplate<char, OutputAdaptor> mStreamOut;
};
/////////////////////////////////////////////////////////////////////////
// --- Define some common output types ---
/////////////////////////////////////////////////////////////////////////
/// Log (see OutputBase for docs)
/// use this silent logger for debug and trace output, logs messages to a file.
/// output is on by default, call Log::SetFilter to change the filter level...
struct InitLog
{
void init( OutputBase<InitLog>& l )
{
reset( l );
outstr.open( "log.txt" );
l.mOutStreams.clear();
//l.mOutStreams.push_back( &std::cout );
//l.mOutStreams.push_back( &the<DebuggerTraceWindowOstream>() );
l.mOutStreams.push_back( &outstr );
}
~InitLog()
{
outstr.close();
}
inline void reset( OutputBase<InitLog>& l )
{
l.SetFilter( spew::FILTERALL );
l.SetLevel( spew::LEVEL1ANDLOWER );
}
std::ofstream outstr;
};
//extern OutputBase<InitLog> Log;
#define Log OutputBase<SPEWNAMESPACE::InitLog>::instance()
/// Trace (see OutputBase for docs)
/// use Trace for debug output.
/// output is off by default, call Trace::SetFilter to set your filter level...
struct InitTrace
{
void init( OutputBase<InitTrace>& l )
{
reset( l );
l.mOutStreams.push_back( &std::cout );
l.mOutStreams.push_back( &the<DebuggerTraceWindowOstream>() );
}
inline void reset( OutputBase<InitTrace>& l )
{
l.SetFilter( spew::FILTERNONE );
l.SetLevel( spew::LEVEL1ANDLOWER );
}
};
#if defined(SPEW_USE_TRACE) || defined(_DEBUG)
// Trace exists only in debug mode
//extern OutputBase<InitTrace> Trace;
#define Trace OutputBase<SPEWNAMESPACE::InitTrace>::instance()
#else
// Trace statements are compiled out in Release
#define Trace FILTERNONE; if (0) SPEWNAMESPACE::StdErr
#endif
/// StdOut (see OutputBase for docs)
/// for when you're writing a console app that
/// needs to output on the command line in release
/// modes for the user to see
/// NOTE: stdout on by default, set to FILTERNONE to hide disable output...
struct InitStdOut
{
void init( OutputBase<InitStdOut, true>& l )
{
reset( l );
l.mOutStreams.push_back( &std::cout );
}
inline void reset( OutputBase<InitStdOut, true>& l )
{
l.SetFilter( spew::FILTERALL ); // most people wouldn't use filters with stdout... :)
l.SetLevel( spew::LEVEL1ANDLOWER );
}
};
//extern OutputBase<InitStdOut, true> StdOut;
#define StdOut OutputBase<SPEWNAMESPACE::InitStdOut, true>::instance()
/// StdErr (see OutputBase for docs)
/// for when you're writing a console app that
/// needs to output on the command line in release
/// modes for the user to see
/// NOTE: stderr off by default, set to FILTERALL to see stderr output...
struct InitStdErr
{
void init( OutputBase<InitStdErr, true>& l )
{
reset( l );
l.mOutStreams.push_back( &std::cerr );
}
inline void reset( OutputBase<InitStdErr, true>& l )
{
l.SetFilter( spew::FILTERNONE );
l.SetLevel( spew::LEVEL1ANDLOWER );
}
};
//extern OutputBase<InitStdErr, true> StdErr;
#define StdErr OutputBase<SPEWNAMESPACE::InitStdErr, true>::instance()
/// empty policy, use when making custom type where
/// you want to add your own ostreams manually.
struct InitEmpty
{
void init( OutputBase<InitEmpty, true>& l )
{
reset( l );
}
inline void reset( OutputBase<InitEmpty, true>& l )
{
l.SetFilter( spew::FILTERALL );
l.SetLevel( spew::LEVEL1ANDLOWER );
}
};
/// helper to set up the outputs via commandline
/// commad line syntax:
/// -[trace|log|stderr|stdout][on|off|level][filter|level]
/// examples:
/// myapp.exe -TraceOnGFX -LogLevel3 -StdErrNone
/// note: in release mode Trace will be compiled out, so cmd line args will have no effect.
inline static void parseCommandLine( int argc, char* argv[] )
{
// add new output types here... (and below in the switch)
const int num_types = 4;
char* types[num_types] = { "Trace", "Log", "StdErr", "StdOut" };
const int num_functions = 3;
char* function[num_functions] = { "Off", "On", "Level" };
// for each command line arg
for (int x = 0; x < argc; ++x)
{
const int notfound = 123456;
int pos = 1;
int type = notfound;
for (int typesIt = 0; typesIt < num_types; ++typesIt)
{
if (strnicmp( types[typesIt], &argv[x][pos], strlen( types[typesIt] ) ) == 0)
{
type = typesIt;
pos += (int)strlen( types[typesIt] );
}
}
int func = notfound;
for (int functionIt = 0; functionIt < num_functions; ++functionIt)
{
if (strnicmp( function[functionIt], &argv[x][pos], strlen( function[functionIt] ) ) == 0)
{
func = functionIt;
pos += (int)strlen( function[functionIt] );
}
}
int tag = notfound;
if (argv[x][pos] == '\0')
{
// support simple on/off case i.e. -TraceOff, -LogOn ("" for 3rd param)
tag = FILTERALL; // add or remove "ALL"
}
else
{
int filterStringPairsIt = 0;
while ('\0' != gTagDescriptions[filterStringPairsIt].mName[0])
{
if (strnicmp( gTagDescriptions[filterStringPairsIt].mName, &argv[x][pos], strlen( gTagDescriptions[filterStringPairsIt].mName ) ) == 0)
{
tag = gTagDescriptions[filterStringPairsIt].mTag;
pos += (int)strlen( gTagDescriptions[filterStringPairsIt].mName );
}
++filterStringPairsIt;
}
}
// found one, set the flag...
if (notfound != type && notfound != func && notfound != tag)
{
switch (type)
{
// add new output types here...
case 0:
switch (func)
{
case 0: Trace.RemoveFilter( tag ); break;
case 1: Trace.AddFilter( tag ); break;
case 2: Trace.SetLevel( (Level)tag ); break;
}
break;
case 1:
switch (func)
{
case 0: Log.RemoveFilter( tag ); break;
case 1: Log.AddFilter( tag ); break;
case 2: Log.SetLevel( (Level)tag ); break;
}
break;
case 2:
switch (func)
{
case 0: StdErr.RemoveFilter( tag ); break;
case 1: StdErr.AddFilter( tag ); break;
case 2: StdErr.SetLevel( (Level)tag ); break;
}
break;
case 3:
switch (func)
{
case 0: StdOut.RemoveFilter( tag ); break;
case 1: StdOut.AddFilter( tag ); break;
case 2: StdOut.SetLevel( (Level)tag ); break;
}
break;
} // switch
}
} // for argv...
}
/// Unit test for Outputs.
struct OutputUnitTest
{
static void test()
{
/// some common examples
Log.SetDefaults();
Log << "Log] default filter, default level" << std::endl;
Log( GFX ) << "Log] GFX filter, default level" << std::endl;
Log( SCRIPT, 4 ) << "Log] SCRIPT filter, level 4" << std::endl;
Log( "Log] default '%s', default '%s'\n", "filter", "level" );
Log( GFX, "Log] GFX filter, default '%s'\n", "level" );
Log( SCRIPT, 3, "Log] SCRIPT filter, '%s' '%d'\n", "level", 3 );
Trace.SetDefaults();
Trace << "Trace] default filter, default level" << std::endl;
Trace( GFX ) << "Trace] GFX filter, default level" << std::endl;
Trace( SCRIPT, 4 ) << "Trace] SCRIPT filter, level 4" << std::endl;
Trace( "Trace] default '%s', default '%s'\n", "filter", "level" );
Trace( GFX, "Trace] GFX filter, default '%s'\n", "level" );
Trace( SCRIPT, 3, "Trace] SCRIPT filter, '%s' '%d'\n", "level", 3 );
StdErr.SetDefaults();
StdErr << "StdErr] default filter, default level" << std::endl;
StdErr( GFX ) << "StdErr] GFX filter, default level" << std::endl;
StdErr( SCRIPT, 4 ) << "StdErr] SCRIPT filter, level 4" << std::endl;
StdErr( "StdErr] default '%s', default '%s'\n", "filter", "level" );
StdErr( GFX, "StdErr] GFX filter, default '%s'\n", "level" );
StdErr( SCRIPT, 3, "StdErr] SCRIPT filter, '%s' '%d'\n", "level", 3 );
StdOut.SetDefaults();
StdOut << "StdOut] default filter, default level" << std::endl;
StdOut( GFX ) << "StdOut] GFX filter, default level" << std::endl;
StdOut( SCRIPT, 4 ) << "StdOut] SCRIPT filter, level 4" << std::endl;
StdOut( "StdOut] default '%s', default '%s'\n", "filter", "level" );
StdOut( GFX, "StdOut] GFX filter, default '%s'\n", "level" );
StdOut( SCRIPT, 3, "StdOut] SCRIPT filter, '%s' '%d'\n", "level", 3 );
OutputBase<InitEmpty, true> mycustomoutput;
mycustomoutput.SetFilter( FILTERALL );
mycustomoutput.SetLevel( LEVELALL );
std::stringstream str;
mycustomoutput.mOutStreams.push_back( &str );
StdOut( "testing custom output [" );
mycustomoutput << "bok" << std::flush;
if (str.str() == "bok")
{
StdOut( "'bok' written successfully", str.str().c_str() );
}
StdOut( "]\n" );
// test filters and levels.
StdOut( "running filter tests on custom output... [" );
mycustomoutput.mOutStreams.push_back( &std::cerr );
mycustomoutput.SetFilter( IO );
mycustomoutput( GFX, "F" );
mycustomoutput.SetFilter( GFX );
mycustomoutput( GFX, "." );
mycustomoutput.SetFilter( GFX | IO | SCRIPT );
mycustomoutput( GFX, "." );
mycustomoutput.SetFilter( GFX | IO | SCRIPT );
mycustomoutput( ANIM, "F" );
mycustomoutput.SetFilter( FILTERALL );
mycustomoutput( PHYSICS, "." );
mycustomoutput.SetFilter( FILTERALL );
mycustomoutput.SetLevel( LEVELALL );
mycustomoutput( PHYSICS, LEVEL1, "." );
mycustomoutput( PHYSICS, LEVEL2, "." );
mycustomoutput( PHYSICS, LEVEL3, "." );
mycustomoutput( PHYSICS, LEVEL4, "." );
mycustomoutput( PHYSICS, LEVEL5, "." );
mycustomoutput.SetLevel( LEVEL1ANDLOWER );
mycustomoutput( PHYSICS, LEVEL1, "." );
mycustomoutput( PHYSICS, LEVEL2, "F" );
mycustomoutput( PHYSICS, LEVEL3, "F" );
mycustomoutput( PHYSICS, LEVEL4, "F" );
mycustomoutput( PHYSICS, LEVEL5, "F" );
mycustomoutput.SetLevel( LEVEL2ANDLOWER );
mycustomoutput( PHYSICS, LEVEL1, "." );
mycustomoutput( PHYSICS, LEVEL2, "." );
mycustomoutput( PHYSICS, LEVEL3, "F" );
mycustomoutput( PHYSICS, LEVEL4, "F" );
mycustomoutput( PHYSICS, LEVEL5, "F" );
mycustomoutput.SetLevel( LEVEL5ANDLOWER );
mycustomoutput( PHYSICS, LEVEL1, "." );
mycustomoutput( PHYSICS, LEVEL2, "." );
mycustomoutput( PHYSICS, LEVEL3, "." );
mycustomoutput( PHYSICS, LEVEL4, "." );
mycustomoutput( PHYSICS, LEVEL5, "." );
mycustomoutput.SetFilter( PHYSICS );
mycustomoutput.SetLevel( LEVEL3 );
mycustomoutput( PHYSICS, LEVEL1, "F" );
mycustomoutput( PHYSICS, LEVEL2, "F" );
mycustomoutput( PHYSICS, LEVEL3, "." );
mycustomoutput( PHYSICS, LEVEL4, "F" );
mycustomoutput( PHYSICS, LEVEL5, "F" );
StdOut( "]\n" );
}
}; // Unit Test
}; // namespace spew
#endif
| 33.441467 | 148 | 0.589245 | [
"render",
"object",
"vector"
] |
96631e4c1e06e0288e779e6829e6a835dab8e054 | 18,684 | c | C | lib/xspublic/xstypes/xsfile.c | rickyrickc137/xsens_ros_mti_driver | 76f252d28e4d80390872e9561aef1eb6516e3da4 | [
"BSD-3-Clause"
] | null | null | null | lib/xspublic/xstypes/xsfile.c | rickyrickc137/xsens_ros_mti_driver | 76f252d28e4d80390872e9561aef1eb6516e3da4 | [
"BSD-3-Clause"
] | null | null | null | lib/xspublic/xstypes/xsfile.c | rickyrickc137/xsens_ros_mti_driver | 76f252d28e4d80390872e9561aef1eb6516e3da4 | [
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2003-2021 Xsens Technologies B.V. or subsidiaries worldwide.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions, and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions, and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the names of the copyright holders nor the names of their contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
// SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
// OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
// ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
//
// Copyright (c) 2003-2021 Xsens Technologies B.V. or subsidiaries worldwide.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions, and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions, and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the names of the copyright holders nor the names of their contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
// SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
// OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
// ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
//
#include "xsfile.h"
#include "xsstring.h"
#include <errno.h>
#ifndef _WIN32
# include <unistd.h> // close
# include <sys/ioctl.h> // ioctl
# include <fcntl.h> // open, O_RDWR
# include <string.h> // strcpy
# include <sys/param.h>
# include <sys/stat.h>
# include <stdarg.h>
# include <stdlib.h>
#else
# include <winbase.h>
# include <sys/stat.h>
# include <io.h>
#endif
// helper
static FILE* openFile(const struct XsString* filename, const struct XsString* mode);
/*! \class XsFile
\brief Encapsulates a file, providing a platform independent interface
*/
/*! \addtogroup cinterface C Interface
@{
*/
/*! \relates XsFile
\brief Frees the resources of this object by closing the file if it is open.
*/
void XsFile_destruct(struct XsFile* thisPtr)
{
if (thisPtr->m_handle != NULL)
{
(void)XsFile_close(thisPtr);
}
}
/*! \relates XsFile
\brief Creates a new binary file with name \a filename, contents of existing files will be discarded
\param filename name of the file to create
\param writeOnly passing 0 will create the file using "w+b", any other value will create it using "wb"
\returns XRV_OK if the file was opened, an error otherwise
*/
XsResultValue XsFile_create(struct XsFile *thisPtr, const struct XsString* filename, int writeOnly)
{
XsString mode;
XsString_construct(&mode);
XsString_resize(&mode, 16);
if (thisPtr->m_handle != NULL)
return XRV_ALREADYOPEN;
#ifdef _WIN32
wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
// actively delete the file first to ensure that the file creation time is properly set
XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
(void) _wunlink(filenameW); // don't care about return value
#else
unlink(filename->m_data);
#endif
if (writeOnly)
{
XsString_assign(&mode, 3, "wb");
thisPtr->m_handle = openFile(filename, &mode);
}
else
{
XsString_assign(&mode, 4, "w+b");
thisPtr->m_handle = openFile(filename, &mode);
}
XsString_destruct(&mode);
if (thisPtr->m_handle == NULL)
return XRV_OUTPUTCANNOTBEOPENED;
else
return XRV_OK;
}
/*! \relates XsFile
\brief Creates a new text file with name \a filename, contents of existing files will be discarded
\param filename name of the file to create
\param writeOnly passing 0 will create the file using "w+t", any other value will create it using "wt"
\returns XRV_OK if the file was opened, an error otherwise
*/
XsResultValue XsFile_createText(struct XsFile *thisPtr, const struct XsString* filename, int writeOnly)
{
XsString mode;
XsString_construct(&mode);
XsString_resize(&mode, 16);
if (thisPtr->m_handle != NULL)
return XRV_ALREADYOPEN;
if (writeOnly)
{
XsString_assign(&mode, 3, "wt");
thisPtr->m_handle = openFile(filename, &mode);
}
else
{
XsString_assign(&mode, 4, "w+t");
thisPtr->m_handle = openFile(filename, &mode);
}
XsString_destruct(&mode);
if (thisPtr->m_handle == NULL)
return XRV_OUTPUTCANNOTBEOPENED;
else
return XRV_OK;
}
/*! \relates XsFile
\brief Opens an existing binary file with name \a filename
\param filename name of the file to open
\param readOnly passing 0 will open the file "r+b" (read/update), any other value will create it using "rb" (read)
\returns XRV_OK if the file was opened, an error otherwise
*/
XsResultValue XsFile_open(struct XsFile *thisPtr, const struct XsString* filename, int readOnly)
{
XsString mode;
XsString_construct(&mode);
XsString_resize(&mode, 16);
if (thisPtr->m_handle != NULL)
return XRV_ALREADYOPEN;
if (readOnly)
XsString_assign(&mode, 3, "rb");
else
XsString_assign(&mode, 4, "r+b");
thisPtr->m_handle = openFile(filename, &mode);
XsString_destruct(&mode);
if (thisPtr->m_handle == NULL)
return XRV_OUTPUTCANNOTBEOPENED;
else
return XRV_OK;
}
/*! \relates XsFile
\brief Opens an existing binary file with name \a filename
\param filename name of the file to open
\param readOnly passing 0 will open the file "r+t" (read/update), any other value will create it using "rt" (read)
\returns XRV_OK if the file was opened, an error otherwise
*/
XsResultValue XsFile_openText(struct XsFile *thisPtr, const struct XsString* filename, int readOnly)
{
XsString mode;
XsString_construct(&mode);
XsString_resize(&mode, 16);
if (thisPtr->m_handle != NULL)
return XRV_ALREADYOPEN;
if (readOnly)
{
XsString_assign(&mode, 3, "rt");
thisPtr->m_handle = openFile(filename, &mode);
}
else
{
XsString_assign(&mode, 4, "r+t");
thisPtr->m_handle = openFile(filename, &mode);
}
XsString_destruct(&mode);
if (thisPtr->m_handle == NULL)
return XRV_OUTPUTCANNOTBEOPENED;
else
return XRV_OK;
}
/*! \brief Helper for file opening */
static FILE* openFile(const struct XsString* filename, const struct XsString* mode)
{
#ifdef _WIN32
wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
wchar_t modeW[16];
(void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
(void)XsString_copyToWCharArray(mode, modeW, 16);
__try
{
return _wfopen(filenameW, modeW);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return NULL;
}
#else
return fopen(filename->m_data, mode->m_data);
#endif
}
/*! \relates XsFile
\brief Reopens a file
\param filename Name of the file to open after the current one has been closed
\param mode Mode to reopen the file with
\returns 0 if a file is open, another value otherwise
*/
XsResultValue XsFile_reopen(struct XsFile *thisPtr, const struct XsString* filename, const struct XsString* mode)
{
#ifdef _WIN32
wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
wchar_t modeW[16];
(void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
(void)XsString_copyToWCharArray(mode, modeW, 16);
thisPtr->m_handle = _wfreopen(filenameW, modeW, thisPtr->m_handle);
#else
thisPtr->m_handle = freopen(filename->m_data, mode->m_data, thisPtr->m_handle);
#endif
if (thisPtr->m_handle == NULL)
return XRV_OUTPUTCANNOTBEOPENED;
else
return XRV_OK;
}
/*! \relates XsFile
\brief Checks if a file is open
\returns 0 if a file is open, another value otherwise
*/
int XsFile_isOpen(const struct XsFile *thisPtr)
{
return (thisPtr->m_handle != NULL) ? 0 : 1;
}
/*! \relates XsFile
\brief Checks if the file exists (can be accessed)
\param filename Name of the file to check for existence
\returns 0 if the file exists, another value otherwise
*/
int XsFile_exists(const struct XsString* filename)
{
#ifdef _WIN32
wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
struct _stat buffer;
(void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
return _wstat(filenameW, &buffer);
#else
struct stat buffer;
return stat(filename->m_data, &buffer);
#endif
}
/*! \relates XsFile
\brief Closes the file
\returns XRV_OK if the file was closed properly, XRV_ENDOFFILE otherwise
*/
XsResultValue XsFile_close(struct XsFile *thisPtr)
{
int rv;
if (thisPtr->m_handle == NULL)
return XRV_NOFILEOPEN;
fflush(thisPtr->m_handle); // always try to flush first, result is irrelevant
rv = fclose(thisPtr->m_handle);
// Or keep the handle in case of failure?
thisPtr->m_handle = NULL;
if (rv == EOF)
return XRV_ENDOFFILE;
else
return XRV_OK;
}
/*! \relates XsFile
\brief Writes unwritten data to the file
\returns XRV_OK if the flushing was successful, an XRV_ERROR otherwise
*/
XsResultValue XsFile_flush(struct XsFile *thisPtr)
{
return fflush(thisPtr->m_handle) ? XRV_ERROR : XRV_OK;
}
/*! \relates XsFile
\brief Reduces the file to a maximum size of \a fileSize bytes
\param fileSize The new size for the file
\returns XRV_OK if the file was truncated, an error otherwise
*/
XsResultValue XsFile_truncate(struct XsFile *thisPtr, XsFilePos fileSize)
{
return XsFile_resize(thisPtr, fileSize);
}
/*! \relates XsFile
\brief Resizes the file to \a fileSize bytes
\param fileSize The new size for the file
\returns XRV_OK if the file was resized, an error otherwise
*/
XsResultValue XsFile_resize(struct XsFile *thisPtr, XsFilePos fileSize)
{
#ifdef _WIN32
int rv = _chsize_s(_fileno(thisPtr->m_handle), fileSize);
#else
int rv = ftruncate(fileno(thisPtr->m_handle), fileSize);
#endif
if (rv != 0)
{
switch(errno)
{
case EACCES:
return XRV_BUSY;
case EBADF:
return XRV_ACCESSDENIED;
case ENOSPC:
return XRV_OUTOFMEMORY;
case EINVAL:
return XRV_INVALIDPARAM;
default:
return XRV_ERROR;
}
}
else
return XRV_OK;
}
/*! \relates XsFile
\brief Deletes a file with name \a filename
\param filename Name of the file to delete
\returns XRV_OK if the file was erased, an error otherwise
*/
XsResultValue XsFile_erase(const struct XsString* filename)
{
#ifdef _WIN32
wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
(void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
if (_wunlink(filenameW) != 0)
#else
if (unlink(filename->m_data) != 0)
#endif
{
switch (errno)
{
case EACCES:
return XRV_READONLY;
case ENOENT:
return XRV_NOTFOUND;
default:
return XRV_ERROR;
}
}
else
return XRV_OK;
}
/*! \relates XsFile
\brief Reads a number of elements from a file
\param destination Buffer to store the read data in
\param size Size of each individual element to read
\param count Number of elements to read
\returns Total number of elements successfully read
*/
XsFilePos XsFile_read(struct XsFile *thisPtr, void *destination, XsFilePos size, XsFilePos count)
{
return (XsFilePos) fread(destination, (size_t) size, (size_t) count, thisPtr->m_handle);
}
/*! \relates XsFile
\brief Writes a number of elements to a file
\param source Buffer that contains the elements to be written
\param size Size of each individual element to write
\param count Number of elements to write
\returns Total number of elements successfully written
*/
XsFilePos XsFile_write(struct XsFile *thisPtr, const void *source, XsFilePos size, XsFilePos count)
{
return (XsFilePos) fwrite(source, (size_t) size, (size_t) count, thisPtr->m_handle);
}
/*! \relates XsFile
\brief Gets and returns the next byte from a file
\returns The byte read from the stream or -1 in case of failure
*/
int XsFile_getc(struct XsFile *thisPtr)
{
return fgetc(thisPtr->m_handle);
}
/*! \relates XsFile
\brief Writes a character to the file
\param character The caharacter to write
\returns XRV_OK on success, XRV_ERROR otehrwise
*/
XsResultValue XsFile_putc(struct XsFile *thisPtr, int character)
{
return fputc(character, thisPtr->m_handle) == EOF ? XRV_ERROR : XRV_OK;
}
/*! \relates XsFile
\brief Reads characters from this file and stores them into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
\param str The destination for the read string
\param num The size of the destination buffer
\returns A pointer to the read string on success, NULL on failure
*/
char* XsFile_gets(struct XsFile *thisPtr, char *str, int num)
{
return fgets(str, num, thisPtr->m_handle);
}
/*! \relates XsFile
\brief Writes a null terminated c-string to the file
\param str The null terminated c-string to write
\returns XRV_OK on success, XRV_ERROR otehrwise
*/
XsResultValue XsFile_puts(struct XsFile *thisPtr, const char *str)
{
return fputs(str, thisPtr->m_handle) != EOF ? XRV_OK : XRV_ERROR;
}
/*! \relates XsFile
\brief Moves the current file position relative to the start of the file
\param offset Position in the file to move to, relative to the start of the file
\returns XRV_OK if the seek was successful
*/
XsResultValue XsFile_seek(struct XsFile *thisPtr, XsFilePos offset)
{
#ifdef _WIN32
return _fseeki64(thisPtr->m_handle, offset, SEEK_SET) ? XRV_ERROR : XRV_OK;
#else
return fseeko(thisPtr->m_handle, offset, SEEK_SET) ? XRV_ERROR : XRV_OK;
#endif
}
/*! \relates XsFile
\brief Moves the current file position relative to the end of the file
\param offset Position in the file to move to, relative to the end of the file
\returns XRV_OK if the seek was successful
*/
XsResultValue XsFile_seek_r(struct XsFile *thisPtr, XsFilePos offset)
{
#ifdef _WIN32
return _fseeki64(thisPtr->m_handle, offset, SEEK_END) ? XRV_ERROR : XRV_OK;
#else
return fseeko(thisPtr->m_handle, offset, SEEK_END) ? XRV_ERROR : XRV_OK;
#endif
}
/*! \relates XsFile
\brief Returns the current position in the file
\returns Current position in the current file
*/
XsFilePos XsFile_tell(struct XsFile const* thisPtr)
{
#ifdef _WIN32
return _ftelli64(thisPtr->m_handle);
#else
return ftello(thisPtr->m_handle);
#endif
}
/*! \relates XsFile
\returns Returns 0 if the current file position is not 'end of file', non 0 if the position is 'end of file'
*/
int XsFile_eof(struct XsFile const* thisPtr)
{
return feof(thisPtr->m_handle);
}
/*! \relates XsFile
\returns Returns XRV_ERROR if the error flag for the file has been set, XRV_OK otherwise
*/
XsResultValue XsFile_error(struct XsFile const* thisPtr)
{
return ferror(thisPtr->m_handle) ? XRV_ERROR : XRV_OK;
}
/*! \relates XsFile
\brief Retrieves the full path for a filename
\param[in] filename The filename to expand
\param[out] fullPath The filename with a fully expanded path is returned in this parameter. This parameter must be allocated by the caller.
\returns XRV_OK if the fullpath could be retrieved, XRV_NULLPTR if fullPath is NULL, XRV_ERROR otherwise
*/
XsResultValue XsFile_fullPath(const struct XsString* filename, struct XsString* fullPath)
{
XsResultValue result = XRV_OK;
if (fullPath == NULL)
{
result = XRV_NULLPTR;
}
else
{
#ifdef _WIN32
wchar_t filenamew[XS_MAX_FILENAME_LENGTH];
wchar_t fullpath[XS_MAX_FILENAME_LENGTH];
(void)XsString_copyToWCharArray(filename, filenamew, XS_MAX_FILENAME_LENGTH);
if (_wfullpath(fullpath, filenamew, XS_MAX_FILENAME_LENGTH) == NULL)
result = XRV_ERROR;
else
XsString_assignWCharArray(fullPath, fullpath);
#else
// based on the assumption that this doesn't concern the serial port, handle
// it the same way using realpath(). Apparently realpath() doesn't require a
// maximum length. One would possibly want to write a wrapper for it.
char fullpath[XS_MAX_FILENAME_LENGTH*2];
if (realpath(filename->m_data, fullpath) == NULL)
result = XRV_ERROR;
else
XsString_assignCharArray(fullPath, fullpath);
#endif
}
return result;
}
/*! \relates XsFile
\brief Reads a full line from the file
\param line The result of the read
\returns XRV_OK if a line could be read
*/
XsResultValue XsFile_getline(struct XsFile *thisPtr, struct XsString *line)
{
int b;
XsResultValue ok = XRV_ENDOFFILE;
XsString_erase(line, 0, line->m_size);
XsArray_reserve(line, 256);
b = fgetc(thisPtr->m_handle);
if (b != -1)
ok = XRV_OK;
while (b != -1)
{
XsString_push_back(line, (char)b);
if (b == '\n')
break;
b = fgetc(thisPtr->m_handle);
}
return ok;
}
/*! \relates XsFile
\returns The file handle
*/
FILE* XsFile_handle(struct XsFile *thisPtr)
{
return thisPtr->m_handle;
}
/*! @} */
| 30.331169 | 180 | 0.747377 | [
"object"
] |
96672f847f43185e52305b25d36575c9880c6404 | 16,879 | h | C | program/lib/mavlink/mavlink_helpers.h | ming6842/firmware-new | 8212044ea391fb597f21bfdf2155e1e488743795 | [
"MIT"
] | 51 | 2015-01-24T22:07:17.000Z | 2022-02-04T13:29:07.000Z | program/lib/mavlink/mavlink_helpers.h | ming6842/firmware-new | 8212044ea391fb597f21bfdf2155e1e488743795 | [
"MIT"
] | 32 | 2015-01-13T22:31:23.000Z | 2017-05-02T07:42:56.000Z | program/lib/mavlink/mavlink_helpers.h | ming6842/firmware-new | 8212044ea391fb597f21bfdf2155e1e488743795 | [
"MIT"
] | 34 | 2015-01-20T09:52:59.000Z | 2020-12-26T17:41:07.000Z | #ifndef _MAVLINK_HELPERS_H_
#define _MAVLINK_HELPERS_H_
#include "string.h"
#include "checksum.h"
#include "mavlink_types.h"
#include "mavlink_conversions.h"
#ifndef MAVLINK_HELPER
#define MAVLINK_HELPER
#endif
/*
* Internal function to give access to the channel status for each channel
*/
#ifndef MAVLINK_GET_CHANNEL_STATUS
MAVLINK_HELPER mavlink_status_t* mavlink_get_channel_status(uint8_t chan)
{
#if MAVLINK_EXTERNAL_RX_STATUS
// No m_mavlink_status array defined in function,
// has to be defined externally
#else
static mavlink_status_t m_mavlink_status[MAVLINK_COMM_NUM_BUFFERS];
#endif
return &m_mavlink_status[chan];
}
#endif
/*
* Internal function to give access to the channel buffer for each channel
*/
#ifndef MAVLINK_GET_CHANNEL_BUFFER
MAVLINK_HELPER mavlink_message_t* mavlink_get_channel_buffer(uint8_t chan)
{
#if MAVLINK_EXTERNAL_RX_BUFFER
// No m_mavlink_buffer array defined in function,
// has to be defined externally
#else
static mavlink_message_t m_mavlink_buffer[MAVLINK_COMM_NUM_BUFFERS];
#endif
return &m_mavlink_buffer[chan];
}
#endif
/**
* @brief Reset the status of a channel.
*/
MAVLINK_HELPER void mavlink_reset_channel_status(uint8_t chan)
{
mavlink_status_t *status = mavlink_get_channel_status(chan);
status->parse_state = MAVLINK_PARSE_STATE_IDLE;
}
/**
* @brief Finalize a MAVLink message with channel assignment
*
* This function calculates the checksum and sets length and aircraft id correctly.
* It assumes that the message id and the payload are already correctly set. This function
* can also be used if the message header has already been written before (as in mavlink_msg_xxx_pack
* instead of mavlink_msg_xxx_pack_headerless), it just introduces little extra overhead.
*
* @param msg Message to finalize
* @param system_id Id of the sending (this) system, 1-127
* @param length Message length
*/
#if MAVLINK_CRC_EXTRA
MAVLINK_HELPER uint16_t mavlink_finalize_message_chan(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id,
uint8_t chan, uint8_t length, uint8_t crc_extra)
#else
MAVLINK_HELPER uint16_t mavlink_finalize_message_chan(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id,
uint8_t chan, uint8_t length)
#endif
{
// This code part is the same for all messages;
uint16_t checksum;
msg->magic = MAVLINK_STX;
msg->len = length;
msg->sysid = system_id;
msg->compid = component_id;
// One sequence number per component
msg->seq = mavlink_get_channel_status(chan)->current_tx_seq;
mavlink_get_channel_status(chan)->current_tx_seq = mavlink_get_channel_status(chan)->current_tx_seq+1;
checksum = crc_calculate((uint8_t*)&msg->len, length + MAVLINK_CORE_HEADER_LEN);
#if MAVLINK_CRC_EXTRA
crc_accumulate(crc_extra, &checksum);
#endif
mavlink_ck_a(msg) = (uint8_t)(checksum & 0xFF);
mavlink_ck_b(msg) = (uint8_t)(checksum >> 8);
return length + MAVLINK_NUM_NON_PAYLOAD_BYTES;
}
/**
* @brief Finalize a MAVLink message with MAVLINK_COMM_0 as default channel
*/
#if MAVLINK_CRC_EXTRA
MAVLINK_HELPER uint16_t mavlink_finalize_message(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id,
uint8_t length, uint8_t crc_extra)
{
return mavlink_finalize_message_chan(msg, system_id, component_id, MAVLINK_COMM_0, length, crc_extra);
}
#else
MAVLINK_HELPER uint16_t mavlink_finalize_message(mavlink_message_t* msg, uint8_t system_id, uint8_t component_id,
uint8_t length)
{
return mavlink_finalize_message_chan(msg, system_id, component_id, MAVLINK_COMM_0, length);
}
#endif
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
MAVLINK_HELPER void _mavlink_send_uart(mavlink_channel_t chan, const char *buf, uint16_t len);
/**
* @brief Finalize a MAVLink message with channel assignment and send
*/
#if MAVLINK_CRC_EXTRA
MAVLINK_HELPER void _mav_finalize_message_chan_send(mavlink_channel_t chan, uint8_t msgid, const char *packet,
uint8_t length, uint8_t crc_extra)
#else
MAVLINK_HELPER void _mav_finalize_message_chan_send(mavlink_channel_t chan, uint8_t msgid, const char *packet, uint8_t length)
#endif
{
uint16_t checksum;
uint8_t buf[MAVLINK_NUM_HEADER_BYTES];
uint8_t ck[2];
mavlink_status_t *status = mavlink_get_channel_status(chan);
buf[0] = MAVLINK_STX;
buf[1] = length;
buf[2] = status->current_tx_seq;
buf[3] = mavlink_system.sysid;
buf[4] = mavlink_system.compid;
buf[5] = msgid;
status->current_tx_seq++;
checksum = crc_calculate((uint8_t*)&buf[1], MAVLINK_CORE_HEADER_LEN);
crc_accumulate_buffer(&checksum, packet, length);
#if MAVLINK_CRC_EXTRA
crc_accumulate(crc_extra, &checksum);
#endif
ck[0] = (uint8_t)(checksum & 0xFF);
ck[1] = (uint8_t)(checksum >> 8);
MAVLINK_START_UART_SEND(chan, MAVLINK_NUM_NON_PAYLOAD_BYTES + (uint16_t)length);
_mavlink_send_uart(chan, (const char *)buf, MAVLINK_NUM_HEADER_BYTES);
_mavlink_send_uart(chan, packet, length);
_mavlink_send_uart(chan, (const char *)ck, 2);
MAVLINK_END_UART_SEND(chan, MAVLINK_NUM_NON_PAYLOAD_BYTES + (uint16_t)length);
}
/**
* @brief re-send a message over a uart channel
* this is more stack efficient than re-marshalling the message
*/
MAVLINK_HELPER void _mavlink_resend_uart(mavlink_channel_t chan, const mavlink_message_t *msg)
{
uint8_t ck[2];
ck[0] = (uint8_t)(msg->checksum & 0xFF);
ck[1] = (uint8_t)(msg->checksum >> 8);
MAVLINK_START_UART_SEND(chan, MAVLINK_NUM_NON_PAYLOAD_BYTES + msg->len);
_mavlink_send_uart(chan, (const char *)&msg->magic, MAVLINK_NUM_HEADER_BYTES);
_mavlink_send_uart(chan, _MAV_PAYLOAD(msg), msg->len);
_mavlink_send_uart(chan, (const char *)ck, 2);
MAVLINK_END_UART_SEND(chan, MAVLINK_NUM_NON_PAYLOAD_BYTES + msg->len);
}
#endif // MAVLINK_USE_CONVENIENCE_FUNCTIONS
/**
* @brief Pack a message to send it over a serial byte stream
*/
MAVLINK_HELPER uint16_t mavlink_msg_to_send_buffer(uint8_t *buffer, const mavlink_message_t *msg)
{
memcpy(buffer, (const uint8_t *)&msg->magic, MAVLINK_NUM_NON_PAYLOAD_BYTES + (uint16_t)msg->len);
return MAVLINK_NUM_NON_PAYLOAD_BYTES + (uint16_t)msg->len;
}
union __mavlink_bitfield {
uint8_t uint8;
int8_t int8;
uint16_t uint16;
int16_t int16;
uint32_t uint32;
int32_t int32;
};
MAVLINK_HELPER void mavlink_start_checksum(mavlink_message_t* msg)
{
crc_init(&msg->checksum);
}
MAVLINK_HELPER void mavlink_update_checksum(mavlink_message_t* msg, uint8_t c)
{
crc_accumulate(c, &msg->checksum);
}
/**
* This is a convenience function which handles the complete MAVLink parsing.
* the function will parse one byte at a time and return the complete packet once
* it could be successfully decoded. Checksum and other failures will be silently
* ignored.
*
* @param chan ID of the current channel. This allows to parse different channels with this function.
* a channel is not a physical message channel like a serial port, but a logic partition of
* the communication streams in this case. COMM_NB is the limit for the number of channels
* on MCU (e.g. ARM7), while COMM_NB_HIGH is the limit for the number of channels in Linux/Windows
* @param c The char to barse
*
* @param returnMsg NULL if no message could be decoded, the message data else
* @return 0 if no message could be decoded, 1 else
*
* A typical use scenario of this function call is:
*
* @code
* #include <inttypes.h> // For fixed-width uint8_t type
*
* mavlink_message_t msg;
* int chan = 0;
*
*
* while(serial.bytesAvailable > 0)
* {
* uint8_t byte = serial.getNextByte();
* if (mavlink_parse_char(chan, byte, &msg))
* {
* printf("Received message with ID %d, sequence: %d from component %d of system %d", msg.msgid, msg.seq, msg.compid, msg.sysid);
* }
* }
*
*
* @endcode
*/
MAVLINK_HELPER uint8_t mavlink_parse_char(uint8_t chan, uint8_t c, mavlink_message_t* r_message, mavlink_status_t* r_mavlink_status)
{
/*
default message crc function. You can override this per-system to
put this data in a different memory segment
*/
#if MAVLINK_CRC_EXTRA
#ifndef MAVLINK_MESSAGE_CRC
static const uint8_t mavlink_message_crcs[256] = MAVLINK_MESSAGE_CRCS;
#define MAVLINK_MESSAGE_CRC(msgid) mavlink_message_crcs[msgid]
#endif
#endif
/* Enable this option to check the length of each message.
This allows invalid messages to be caught much sooner. Use if the transmission
medium is prone to missing (or extra) characters (e.g. a radio that fades in
and out). Only use if the channel will only contain messages types listed in
the headers.
*/
#if MAVLINK_CHECK_MESSAGE_LENGTH
#ifndef MAVLINK_MESSAGE_LENGTH
static const uint8_t mavlink_message_lengths[256] = MAVLINK_MESSAGE_LENGTHS;
#define MAVLINK_MESSAGE_LENGTH(msgid) mavlink_message_lengths[msgid]
#endif
#endif
mavlink_message_t* rxmsg = mavlink_get_channel_buffer(chan); ///< The currently decoded message
mavlink_status_t* status = mavlink_get_channel_status(chan); ///< The current decode status
int bufferIndex = 0;
status->msg_received = 0;
switch (status->parse_state)
{
case MAVLINK_PARSE_STATE_UNINIT:
case MAVLINK_PARSE_STATE_IDLE:
if (c == MAVLINK_STX)
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_STX;
rxmsg->len = 0;
rxmsg->magic = c;
mavlink_start_checksum(rxmsg);
}
break;
case MAVLINK_PARSE_STATE_GOT_STX:
if (status->msg_received
/* Support shorter buffers than the
default maximum packet size */
#if (MAVLINK_MAX_PAYLOAD_LEN < 255)
|| c > MAVLINK_MAX_PAYLOAD_LEN
#endif
)
{
status->buffer_overrun++;
status->parse_error++;
status->msg_received = 0;
status->parse_state = MAVLINK_PARSE_STATE_IDLE;
}
else
{
// NOT counting STX, LENGTH, SEQ, SYSID, COMPID, MSGID, CRC1 and CRC2
rxmsg->len = c;
status->packet_idx = 0;
mavlink_update_checksum(rxmsg, c);
status->parse_state = MAVLINK_PARSE_STATE_GOT_LENGTH;
}
break;
case MAVLINK_PARSE_STATE_GOT_LENGTH:
rxmsg->seq = c;
mavlink_update_checksum(rxmsg, c);
status->parse_state = MAVLINK_PARSE_STATE_GOT_SEQ;
break;
case MAVLINK_PARSE_STATE_GOT_SEQ:
rxmsg->sysid = c;
mavlink_update_checksum(rxmsg, c);
status->parse_state = MAVLINK_PARSE_STATE_GOT_SYSID;
break;
case MAVLINK_PARSE_STATE_GOT_SYSID:
rxmsg->compid = c;
mavlink_update_checksum(rxmsg, c);
status->parse_state = MAVLINK_PARSE_STATE_GOT_COMPID;
break;
case MAVLINK_PARSE_STATE_GOT_COMPID:
#if MAVLINK_CHECK_MESSAGE_LENGTH
if (rxmsg->len != MAVLINK_MESSAGE_LENGTH(c))
{
status->parse_error++;
status->parse_state = MAVLINK_PARSE_STATE_IDLE;
break;
if (c == MAVLINK_STX)
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_STX;
mavlink_start_checksum(rxmsg);
}
}
#endif
rxmsg->msgid = c;
mavlink_update_checksum(rxmsg, c);
if (rxmsg->len == 0)
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_PAYLOAD;
}
else
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_MSGID;
}
break;
case MAVLINK_PARSE_STATE_GOT_MSGID:
_MAV_PAYLOAD_NON_CONST(rxmsg)[status->packet_idx++] = (char)c;
mavlink_update_checksum(rxmsg, c);
if (status->packet_idx == rxmsg->len)
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_PAYLOAD;
}
break;
case MAVLINK_PARSE_STATE_GOT_PAYLOAD:
#if MAVLINK_CRC_EXTRA
mavlink_update_checksum(rxmsg, MAVLINK_MESSAGE_CRC(rxmsg->msgid));
#endif
if (c != (rxmsg->checksum & 0xFF)) {
// Check first checksum byte
status->parse_error++;
status->msg_received = 0;
status->parse_state = MAVLINK_PARSE_STATE_IDLE;
if (c == MAVLINK_STX)
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_STX;
rxmsg->len = 0;
mavlink_start_checksum(rxmsg);
}
}
else
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_CRC1;
_MAV_PAYLOAD_NON_CONST(rxmsg)[status->packet_idx] = (char)c;
}
break;
case MAVLINK_PARSE_STATE_GOT_CRC1:
if (c != (rxmsg->checksum >> 8)) {
// Check second checksum byte
status->parse_error++;
status->msg_received = 0;
status->parse_state = MAVLINK_PARSE_STATE_IDLE;
if (c == MAVLINK_STX)
{
status->parse_state = MAVLINK_PARSE_STATE_GOT_STX;
rxmsg->len = 0;
mavlink_start_checksum(rxmsg);
}
}
else
{
// Successfully got message
status->msg_received = 1;
status->parse_state = MAVLINK_PARSE_STATE_IDLE;
_MAV_PAYLOAD_NON_CONST(rxmsg)[status->packet_idx+1] = (char)c;
memcpy(r_message, rxmsg, sizeof(mavlink_message_t));
}
break;
}
bufferIndex++;
// If a message has been sucessfully decoded, check index
if (status->msg_received == 1)
{
//while(status->current_seq != rxmsg->seq)
//{
// status->packet_rx_drop_count++;
// status->current_seq++;
//}
status->current_rx_seq = rxmsg->seq;
// Initial condition: If no packet has been received so far, drop count is undefined
if (status->packet_rx_success_count == 0) status->packet_rx_drop_count = 0;
// Count this packet as received
status->packet_rx_success_count++;
}
r_mavlink_status->current_rx_seq = status->current_rx_seq+1;
r_mavlink_status->packet_rx_success_count = status->packet_rx_success_count;
r_mavlink_status->packet_rx_drop_count = status->parse_error;
status->parse_error = 0;
return status->msg_received;
}
/**
* @brief Put a bitfield of length 1-32 bit into the buffer
*
* @param b the value to add, will be encoded in the bitfield
* @param bits number of bits to use to encode b, e.g. 1 for boolean, 2, 3, etc.
* @param packet_index the position in the packet (the index of the first byte to use)
* @param bit_index the position in the byte (the index of the first bit to use)
* @param buffer packet buffer to write into
* @return new position of the last used byte in the buffer
*/
MAVLINK_HELPER uint8_t put_bitfield_n_by_index(int32_t b, uint8_t bits, uint8_t packet_index, uint8_t bit_index, uint8_t* r_bit_index, uint8_t* buffer)
{
uint16_t bits_remain = bits;
// Transform number into network order
int32_t v;
uint8_t i_bit_index, i_byte_index, curr_bits_n;
#if MAVLINK_NEED_BYTE_SWAP
union {
int32_t i;
uint8_t b[4];
} bin, bout;
bin.i = b;
bout.b[0] = bin.b[3];
bout.b[1] = bin.b[2];
bout.b[2] = bin.b[1];
bout.b[3] = bin.b[0];
v = bout.i;
#else
v = b;
#endif
// buffer in
// 01100000 01000000 00000000 11110001
// buffer out
// 11110001 00000000 01000000 01100000
// Existing partly filled byte (four free slots)
// 0111xxxx
// Mask n free bits
// 00001111 = 2^0 + 2^1 + 2^2 + 2^3 = 2^n - 1
// = ((uint32_t)(1 << n)) - 1; // = 2^n - 1
// Shift n bits into the right position
// out = in >> n;
// Mask and shift bytes
i_bit_index = bit_index;
i_byte_index = packet_index;
if (bit_index > 0)
{
// If bits were available at start, they were available
// in the byte before the current index
i_byte_index--;
}
// While bits have not been packed yet
while (bits_remain > 0)
{
// Bits still have to be packed
// there can be more than 8 bits, so
// we might have to pack them into more than one byte
// First pack everything we can into the current 'open' byte
//curr_bits_n = bits_remain << 3; // Equals bits_remain mod 8
//FIXME
if (bits_remain <= (uint8_t)(8 - i_bit_index))
{
// Enough space
curr_bits_n = (uint8_t)bits_remain;
}
else
{
curr_bits_n = (8 - i_bit_index);
}
// Pack these n bits into the current byte
// Mask out whatever was at that position with ones (xxx11111)
buffer[i_byte_index] &= (0xFF >> (8 - curr_bits_n));
// Put content to this position, by masking out the non-used part
buffer[i_byte_index] |= ((0x00 << curr_bits_n) & v);
// Increment the bit index
i_bit_index += curr_bits_n;
// Now proceed to the next byte, if necessary
bits_remain -= curr_bits_n;
if (bits_remain > 0)
{
// Offer another 8 bits / one byte
i_byte_index++;
i_bit_index = 0;
}
}
*r_bit_index = i_bit_index;
// If a partly filled byte is present, mark this as consumed
if (i_bit_index != 7) i_byte_index++;
return i_byte_index - packet_index;
}
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
// To make MAVLink work on your MCU, define comm_send_ch() if you wish
// to send 1 byte at a time, or MAVLINK_SEND_UART_BYTES() to send a
// whole packet at a time
/*
#include "mavlink_types.h"
void comm_send_ch(mavlink_channel_t chan, uint8_t ch)
{
if (chan == MAVLINK_COMM_0)
{
uart0_transmit(ch);
}
if (chan == MAVLINK_COMM_1)
{
uart1_transmit(ch);
}
}
*/
MAVLINK_HELPER void _mavlink_send_uart(mavlink_channel_t chan, const char *buf, uint16_t len)
{
#ifdef MAVLINK_SEND_UART_BYTES
/* this is the more efficient approach, if the platform
defines it */
MAVLINK_SEND_UART_BYTES(chan, (const uint8_t *)buf, len);
#else
/* fallback to one byte at a time */
uint16_t i;
for (i = 0; i < len; i++) {
comm_send_ch(chan, (uint8_t)buf[i]);
}
#endif
}
#endif // MAVLINK_USE_CONVENIENCE_FUNCTIONS
#endif /* _MAVLINK_HELPERS_H_ */
| 29.716549 | 151 | 0.735944 | [
"transform"
] |
9667a10cc9418c8123f60b46497638a774b822e4 | 20,351 | h | C | src/Star.h | timriley-io/COMPAS | 3ae82eecd261aedcf63af6d936d0aac87a7c964e | [
"MIT"
] | 1 | 2020-04-06T01:53:36.000Z | 2020-04-06T01:53:36.000Z | src/Star.h | timriley-io/COMPAS | 3ae82eecd261aedcf63af6d936d0aac87a7c964e | [
"MIT"
] | null | null | null | src/Star.h | timriley-io/COMPAS | 3ae82eecd261aedcf63af6d936d0aac87a7c964e | [
"MIT"
] | null | null | null | #ifndef __Star_h__
#define __Star_h__
#include <fstream>
#include "constants.h"
#include "typedefs.h"
#include "utils.h"
#include "BaseStar.h"
#include "MS_lte_07.h"
#include "MS_gt_07.h"
#include "CH.h"
#include "HG.h"
#include "FGB.h"
#include "CHeB.h"
#include "EAGB.h"
#include "TPAGB.h"
#include "HeMS.h"
#include "HeHG.h"
#include "HeGB.h"
#include "HeWD.h"
#include "COWD.h"
#include "ONeWD.h"
#include "NS.h"
#include "BH.h"
#include "MR.h"
class BaseStar;
class MS_lte_07;
class MS_gt_07;
class CH;
class HG;
class FGB;
class CHeB;
class EAGB;
class TPAGB;
class HeMS;
class HeHG;
class HeGB;
class HeWD;
class COWD;
class ONeWD;
class NS;
class BH;
class MR;
class Star {
public:
Star();
Star(const unsigned long int p_RandomSeed,
const double p_MZAMS,
const double p_Metallicity,
const KickParameters p_KickParameters = {},
const double p_LBVfactor = 0.0,
const double p_WolfRayetFactor = 0.0);
Star(const Star& p_Star);
Star& operator = (const Star& p_Star);
virtual ~Star() { delete m_Star; delete m_SaveStar; }
// object identifiers - all classes have these
OBJECT_ID ObjectId() const { return m_ObjectId; }
OBJECT_TYPE ObjectType() const { return m_ObjectType; }
STELLAR_TYPE InitialStellarType() const { return m_Star->InitialStellarType(); }
STELLAR_TYPE StellarType() const { return m_Star->StellarType(); }
// getters - alphabetically
double Age() const { return m_Star->Age(); }
double BindingEnergy_Fixed() const { return m_Star->BindingEnergy_Fixed(); }
double BindingEnergy_Loveridge() const { return m_Star->BindingEnergy_Loveridge(); }
double BindingEnergy_Nanjing() const { return m_Star->BindingEnergy_Nanjing(); }
double BindingEnergy_Kruckow() const { return m_Star->BindingEnergy_Kruckow(); }
double COCoreMass() const { return m_Star->COCoreMass(); }
double CoreMass() const { return m_Star->CoreMass(); }
double DynamicalTimescale() const { return m_Star->DynamicalTimescale(); }
double EnvMass() const { return m_Star->EnvMass(); }
bool ExperiencedCCSN() const { return m_Star->ExperiencedCCSN(); }
bool ExperiencedECSN() const { return m_Star->ExperiencedECSN(); }
bool ExperiencedPISN() const { return m_Star->ExperiencedPISN() ; }
bool ExperiencedPPISN() const { return m_Star->ExperiencedPPISN(); }
bool ExperiencedRunaway() const { return m_Star->ExperiencedRunaway(); }
bool ExperiencedUSSN() const { return m_Star->ExperiencedUSSN(); }
double HeCoreMass() const { return m_Star->HeCoreMass(); }
bool IsCCSN() const { return m_Star->IsCCSN(); }
bool IsDegenerate() const { return m_Star->IsDegenerate(); }
bool IsECSN() const { return m_Star->IsECSN(); }
bool IsMassRatioUnstable(const double p_AccretorMass, const double p_IsAccretorDegenerate) const { return m_Star->IsMassRatioUnstable(p_AccretorMass, p_IsAccretorDegenerate); }
bool IsOneOf(STELLAR_TYPE_LIST p_List) const { return m_Star->IsOneOf(p_List); }
bool IsPISN() const { return m_Star->IsPISN(); }
bool IsPPISN() const { return m_Star->IsPPISN(); }
bool IsUSSN() const { return m_Star->IsUSSN(); }
double Lambda_Fixed() const { return m_Star->Lambda_Fixed(); }
double Lambda_Loveridge() const { return m_Star->Lambda_Loveridge(); }
double Lambda_Nanjing() const { return m_Star->Lambda_Nanjing(); }
double Lambda_Kruckow() const { return m_Star->Lambda_Kruckow(); }
double Luminosity() const { return m_Star->Luminosity(); }
double Mass() const { return m_Star->Mass(); }
double Mass0() const { return m_Star->Mass0(); }
double MassPrev() const { return m_Star->MassPrev(); }
double Metallicity() const { return m_Star->Metallicity(); }
double MZAMS() const { return m_Star->MZAMS(); }
double NuclearTimescale() const { return m_Star->NuclearTimescale(); }
double Omega() const { return m_Star->Omega(); }
double OmegaCHE() const { return m_Star->OmegaCHE(); }
double OmegaPrev() const { return m_Star->OmegaPrev(); }
double RadialExpansionTimescale() const { return m_Star->RadialExpansionTimescale(); }
double Radius() const { return m_Star->Radius(); }
double RadiusPrev() const { return m_Star->RadiusPrev(); }
double RZAMS() const { return m_Star->RZAMS(); }
SupernovaDetailsT SN_Details() const { return m_Star->SN_Details(); }
double SN_Phi() const { return m_Star->SN_Phi(); }
double SN_Theta() const { return m_Star->SN_Theta(); }
double SN_TrueAnomaly() const { return m_Star->SN_TrueAnomaly(); }
SN_EVENT SN_Type() const { return m_Star->SN_Type(); }
COMPAS_VARIABLE StellarPropertyValue(const T_ANY_PROPERTY p_Property) const { return m_Star->StellarPropertyValue(p_Property); }
double Temperature() const { return m_Star->Temperature(); }
double ThermalTimescale() const { return m_Star->ThermalTimescale(); }
double Timescale(TIMESCALE p_Timescale) const { return m_Star->Timescale(p_Timescale); }
double XExponent() const { return m_Star->XExponent(); }
// setters (JR: I don't really like this, but I think unavoidable - at least for now)
void SetOmega(double p_vRot) { m_Star->SetOmega(p_vRot); }
// member functions - alphabetically
STELLAR_TYPE AgeOneTimestep(const double p_Dt, bool p_Switch = true);
void ApplyMassTransferRejuvenationFactor() { m_Star->ApplyMassTransferRejuvenationFactor(); }
void CalculateAngularMomentum() { m_Star->CalculateAngularMomentum(); }
void CalculateBindingEnergies(const double p_CoreMass,
const double p_EnvMass,
const double p_Radius) { m_Star->CalculateBindingEnergies(p_CoreMass, p_EnvMass, p_Radius); }
double CalculateDynamicalMassLossRate() { return m_Star->CalculateDynamicalMassLossRate(); }
double CalculateDynamicalTimescale() const { return m_Star->CalculateDynamicalTimescale(); }
double CalculateEddyTurnoverTimescale() { return m_Star->CalculateEddyTurnoverTimescale(); }
double CalculateGyrationRadius() { return m_Star->CalculateGyrationRadius(); }
void CalculateLambdas() { m_Star->CalculateLambdas(); }
void CalculateLambdas(const double p_EnvMass) { m_Star->CalculateLambdas(p_EnvMass); }
DBL_DBL CalculateMassAcceptanceRate(const double p_DonorMassRate,
const double p_FractionAccreted,
const double p_AccretorMassRate) { return m_Star->CalculateMassAcceptanceRate(p_DonorMassRate,
p_FractionAccreted,
p_AccretorMassRate); }
DBL_DBL CalculateMassAcceptanceRate(const double p_DonorMassRate,
const double p_FractionAccreted) { return m_Star->CalculateMassAcceptanceRate(p_DonorMassRate,
p_FractionAccreted,
CalculateThermalMassLossRate()); }
double CalculateMassLossValues(const bool p_UpdateMDot = false, const bool p_UpdateMDt = false) { return m_Star->CalculateMassLossValues(p_UpdateMDot, p_UpdateMDt); }
double CalculateMomentOfInertia(const double p_RemnantRadius = 0.0) { return m_Star->CalculateMomentOfInertia(p_RemnantRadius); }
double CalculateMomentOfInertiaAU(const double p_RemnantRadius = 0.0) { return m_Star->CalculateMomentOfInertiaAU(p_RemnantRadius); }
void CalculateSNAnomalies(const double p_Eccentricity) { m_Star->CalculateSNAnomalies(p_Eccentricity); }
double CalculateSNKickVelocity(const double p_RemnantMass, const double p_EjectaMass) { return m_Star->CalculateSNKickVelocity(p_RemnantMass, p_EjectaMass); }
double CalculateThermalMassLossRate() { return m_Star->CalculateThermalMassLossRate(); }
double CalculateThermalTimescale() const { return m_Star->CalculateThermalTimescale(); }
double CalculateThermalTimescale(const double p_Mass,
const double p_Radius,
const double p_Luminosity,
const double p_EnvMass = 1.0) { return m_Star->CalculateThermalTimescale(p_Mass, p_Radius, p_Luminosity, p_EnvMass); }
double CalculateTimestep() { return m_Star->CalculateTimestep(); }
double CalculateZeta(CE_ZETA_PRESCRIPTION p_CEZetaPrescription) { return m_Star->CalculateZeta(p_CEZetaPrescription); }
void CalculateZetas() { m_Star->CalculateZetas(); }
void CheckRunaway(const bool p_Unbound) { m_Star->CheckRunaway(p_Unbound); }
void ClearCurrentSNEvent() { m_Star->ClearCurrentSNEvent(); }
BaseStar* Clone(const BaseStar& p_Star);
ENVELOPE DetermineEnvelopeType() const { return m_Star->DetermineEnvelopeType(); }
ENVELOPE DetermineEnvelopeTypeHurley2002() const { return m_Star->DetermineEnvelopeTypeHurley2002(); }
MT_CASE DetermineMassTransferCase() { return m_Star->DetermineMassTransferCase(); }
void Evolve(const int p_StepNum);
double EvolveOneTimestep(const double p_Dt);
void IncrementOmega(const double p_OmegaDelta) { m_Star->IncrementOmega(p_OmegaDelta); }
void ResolveAccretion(const double p_AccretionMass) { m_Star->ResolveAccretion(p_AccretionMass); }
void ResolveEnvelopeLossAndSwitch() { SwitchTo(m_Star->ResolveEnvelopeLoss(true)); }
void ResolveRemnantAfterEnvelopeLossAndSwitch() { SwitchTo(m_Star->ResolveRemnantAfterEnvelopeLoss()); }
STELLAR_TYPE ResolveRemnantAfterEnvelopeLoss() { return m_Star->ResolveRemnantAfterEnvelopeLoss(); }
bool RevertState();
void SaveState();
void SetSNCurrentEvent(const SN_EVENT p_SNEvent) { m_Star->SetSNCurrentEvent(p_SNEvent); }
void SetSNPastEvent(const SN_EVENT p_SNEvent) { m_Star->SetSNPastEvent(p_SNEvent); }
void SwitchTo(const STELLAR_TYPE p_StellarType, bool p_SetInitialType = false);
void UpdateAgeAfterMassLoss() { m_Star->UpdateAgeAfterMassLoss(); }
void UpdateAttributes() { (void)UpdateAttributes(0.0, 0.0, true); }
STELLAR_TYPE UpdateAttributes(const double p_DeltaMass,
const double p_DeltaMass0,
const bool p_ForceRecalculate = false);
STELLAR_TYPE UpdateAttributesAndAgeOneTimestep(const double p_DeltaMass,
const double p_DeltaMass0,
const double p_DeltaTime,
const bool p_Switch = true,
const bool p_ForceRecalculate = false);
void UpdateInitialMass() { m_Star->UpdateInitialMass(); }
void UpdateMagneticFieldAndSpin(const bool p_CommonEnvelope,
const double p_Stepsize,
const double p_MassGainPerTimeStep,
const double p_Epsilon) { m_Star->UpdateMagneticFieldAndSpin(p_CommonEnvelope,
p_Stepsize,
p_MassGainPerTimeStep,
p_Epsilon);}
private:
OBJECT_ID m_ObjectId; // instantiated object's unique object id
OBJECT_TYPE m_ObjectType; // instantiated object's object type
BaseStar *m_Star; // pointer to current star
BaseStar *m_SaveStar; // pointer to saved star
};
#endif // __Star_h__
| 77.380228 | 203 | 0.386418 | [
"object"
] |
966a0288e8f51fd573ab30f58e7f2692118b40ad | 5,061 | h | C | matchinglib_poselib/source/matchinglib/include/matchinglib/matchinglib_matchers.h | josefmaierfl/matchinglib_poselib | 3bd7125a1ddfea68dfa95c8b3f978cba4a678348 | [
"MIT"
] | 1 | 2021-12-30T14:58:18.000Z | 2021-12-30T14:58:18.000Z | matchinglib_poselib/source/matchinglib/include/matchinglib/matchinglib_matchers.h | josefmaierfl/matchinglib_poselib | 3bd7125a1ddfea68dfa95c8b3f978cba4a678348 | [
"MIT"
] | 1 | 2020-08-19T16:11:15.000Z | 2020-08-19T16:11:15.000Z | matchinglib_poselib/source/matchinglib/include/matchinglib/matchinglib_matchers.h | josefmaierfl/matchinglib_poselib | 3bd7125a1ddfea68dfa95c8b3f978cba4a678348 | [
"MIT"
] | 2 | 2020-09-28T13:20:59.000Z | 2022-01-04T10:56:02.000Z | //Released under the MIT License - https://opensource.org/licenses/MIT
//
//Copyright (c) 2019 AIT Austrian Institute of Technology GmbH
//
//Permission is hereby granted, free of charge, to any person obtaining
//a copy of this software and associated documentation files (the "Software"),
//to deal in the Software without restriction, including without limitation
//the rights to use, copy, modify, merge, publish, distribute, sublicense,
//and/or sell copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included
//in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
//OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
//USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//Author: Josef Maier (josefjohann-dot-maier-at-gmail-dot-at)
/**********************************************************************************************************
FILE: match_statOptFlow.h
PLATFORM: Windows 7, MS Visual Studio 2010, OpenCV 2.4.9
CODE: C++
AUTOR: Josef Maier, AIT Austrian Institute of Technology
DATE: April 2016
LOCATION: TechGate Vienna, Donau-City-Strasse 1, 1220 Vienna
VERSION: 1.0
DISCRIPTION: This file provides functionalities for matching features
**********************************************************************************************************/
#pragma once
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "matchinglib/matchinglib_api.h"
#include <memory>
#include <string>
namespace matchinglib
{
/* --------------------------- Defines --------------------------- */
/* --------------------- Function prototypes --------------------- */
//Matches 2 feature sets with an user selectable matching algorithm.
int MATCHINGLIB_API getMatches(const std::vector<cv::KeyPoint> &keypoints1, const std::vector<cv::KeyPoint> &keypoints2,
cv::Mat const &descriptors1, cv::Mat const &descriptors2, cv::Size imgSi, std::vector<cv::DMatch> &finalMatches,
std::string const &matcher_name = "GMBSOF", bool VFCrefine = false, bool ratioTest = true,
std::string const &descriptor_name = "", std::string idxPars_NMSLIB = "", std::string queryPars_NMSLIB = "", const size_t nr_threads = 0);
int MATCHINGLIB_API getMatches_OpticalFlow(const std::vector<cv::KeyPoint> &keypoints_prev, const std::vector<cv::KeyPoint> &keypoints_next,
cv::Mat &img_prev, cv::Mat const& img_next, std::vector<cv::DMatch> & finalMatches,
bool const buildpyr = false, bool drawRes = true, cv::Size winSize = cv::Size(31,31), float searchRadius_px = 10.0f);
int MATCHINGLIB_API getMatches_OpticalFlowAdvanced(const std::vector<cv::KeyPoint> &keypoints_prev,
const std::vector<cv::KeyPoint> &keypoints_next,
cv::Mat const& descriptors1, cv::Mat const& descriptors2,
cv::Mat &img_prev, cv::Mat const& img_next, std::vector<cv::DMatch> & finalMatches, std::string const& matcher_name = "ALKOF",
bool const buildpyr = false, bool drawRes = true, cv::Size winSize = cv::Size(31,31), float searchRadius_px = 10.0f,
unsigned const numNeighbors = 3, const float maxHammDist = 50.0f);
int MATCHINGLIB_API getMatches_OpticalFlowTracker(std::vector<cv::KeyPoint> & keypoints_prev,
std::vector<cv::KeyPoint> & keypoints_predicted,
cv::Mat const& descriptors1,
cv::Mat &img_prev, cv::Mat &img_next,
std::vector<cv::DMatch> & finalMatches,
std::string const& matcher_name = "LKOFT", std::string const& desciptor_type = "ORB",
bool const buildpyr = false, bool drawRes = true, cv::Size winSize = cv::Size(31,31), const float maxHammDist = 50.0f);
//This function calculates the subpixel-position of matched keypoints by template matching
int MATCHINGLIB_API getSubPixMatches(cv::Mat& img1, cv::Mat& img2, std::vector<cv::KeyPoint> *keypoints1,
std::vector<cv::KeyPoint> *keypoints2, std::vector<bool> *inliers = NULL);
//This function calculates the subpixel-position of matched keypoints by using the OpenCV function cv::cornerSubPix()
int MATCHINGLIB_API getSubPixMatches_seperate_Imgs(cv::Mat &img1, cv::Mat &img2, std::vector<cv::KeyPoint> *keypoints1, std::vector<cv::KeyPoint> *keypoints2,
std::vector<bool> *inliers);
bool MATCHINGLIB_API IsMatcherSupported(std::string const& type);
std::vector<std::string> MATCHINGLIB_API GetSupportedMatcher();
}
| 51.121212 | 172 | 0.665284 | [
"vector"
] |
9671497a69da9efee01a4549b32d08f8ae48781d | 10,681 | c | C | d/laerad/mon/faith_warrior.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/laerad/mon/faith_warrior.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/laerad/mon/faith_warrior.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
#define ASDIR "/d/laerad/parnelli/asgard/"
#define NOGOROOM ({ASDIR+"as56", ASDIR+"as57","/d/laerad/parnelli/forest/for081"})
#define FAITHS ({"kreysneothosies","lord shadow"})
#define CLASSES ({"fighter","paladin","ranger"})
#define EYES ({"%^RESET%^%^ORANGE%^brown","%^RESET%^%^ORANGE%^ha%^GREEN%^z%^ORANGE%^el","%^BOLD%^%^BLUE%^blue","%^RESET%^%^GREEN%^green"})
#define HAIR ({"%^RESET%^%^ORANGE%^brown","%^YELLOW%^blond","%^RESET%^%^RED%^red","%^BOLD%^%^BLACK%^black","%^RESET%^gray"})
#define HAIRTYPE ({"short","long","curly","chin-length"})
inherit MONSTER;
string theclass,faith;
void kill_em(object targ);
void create(){
string poss,subj;
object obj;
theclass = CLASSES[random(sizeof(CLASSES))];
faith = FAITHS[random(sizeof(FAITHS))];
::create();
set_id(({"warrior","faith warrior",""+theclass+" of "+faith+"",""+theclass+" of "+capitalize(faith)+"",""+theclass+""}));
set_name("A steadfast "+theclass+" of "+capitalize(faith)+"");
set_short("%^RESET%^%^CYAN%^A steadfast %^RED%^"+theclass+" of %^ORANGE%^"+capitalize(faith)+"%^RESET%^");
set_gender(!random(2)?"male":"female");
switch(random(2)){
case 0: set_gender("male");
poss = "his";
subj = "he";
break;
case 1: set_gender("female");
poss = "her";
subj = "she";
break;
}
set_long("%^RESET%^%^CYAN%^This sharp-eyed warrior surveys "+poss+" "
"surroundings with an air of wariness and confidence. Dressed in "
"well-crafted armor, "+subj+" wears a cloak embroidered with the "
"holy symbol of "+capitalize(faith)+", professing "+poss+" faith "
"proudly. "+capitalize(poss)+" "+HAIRTYPE[random(sizeof(HAIRTYPE))]+" "
""+HAIR[random(sizeof(HAIR))]+" hair %^RESET%^%^CYAN%^is clean and well-groomed, "
"making it clear that appearance is important to this soldier, while "
""+poss+" "+EYES[random(sizeof(EYES))]+" eyes %^RESET%^%^CYAN%^reveal "
""+poss+" intelligence and sense of duty. "+capitalize(subj)+" spends "
""+poss+" time patrolling the ruins of Asgard, working to chase away "
"intruders and opportunists.%^RESET%^");
set_body_type("human");
set_race("human");
set_size(2);
set_hd(20+(random(9)),6);
set_max_hp(166+(random(72)));
set_hp(TO->query_max_hp());
set_max_level(27);
set_overall_ac(-5);
set_new_exp(24,"normal");
set_alignment(1);
switch(theclass){
case "fighter": set_guild_level("fighter",24);
add_search_path("/cmds/fighter/");
obj = new("/d/common/obj/armour/chain");
obj->set_property("enchantment",3);
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
obj = new("/d/common/obj/armour/helm");
if(random(5)) obj->set_property("monsterweapon",1);
obj = new("/d/antioch/valley/obj/sunblade");
obj->set_property("monsterweapon",1);
obj->move(TO);
command("wield sword");
break;
case "paladin": set_guild_level("paladin",24);
set_guild_level("cleric",24);
add_search_path("/cmds/paladin/");
add_search_path("/cmds/cavalier/");
add_search_path("/cmds/spells/");
set_spells(({"call lightning","cause blindness","dispel magic"}));
set_spell_chance(20);
obj = new("/d/common/obj/armour/fullplate");
obj->set_property("enchantment",3);
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
obj = new("/d/common/obj/armour/helm");
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
obj = new("/d/common/obj/armour/shield");
obj->set_property("enchantment",3);
obj->set_long("This shield is crafted from a thin sheet "
"of %^BOLD%^metal %^RESET%^shaped into an oval and "
"gently curved to deflect blows. The front has been "
"enameled with the holy symbol of %^BOLD%^"+capitalize(faith)+", "
"while the back has been fitted with a metal bar and %^ORANGE%^"
"straps %^RESET%^for ease of wearing.");
obj->set_short("%^RESET%^%^CYAN%^a shield embossed with the symbol of "+capitalize(faith)+"%^RESET%^");
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
call_out("horse_me",2);
break;
case "ranger": set_guild_level("ranger",24);
set_guild_level("cleric",24);
add_search_path("/cmds/ranger/");
add_search_path("/cmds/spells/");
set_spells(({"cause blindness","dispel magic","orders oath","seeking sword"}));
set_spell_chance(20);
obj = new("/d/common/obj/armour/hide");
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
obj = new("/d/common/obj/armour/coif_leather");
obj->set_property("enchantment",1);
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
obj = new("/d/common/obj/armour/bracers");
obj->set_property("enchantment",3);
if(random(5)) obj->set_property("monsterweapon",1);
obj->move(TO);
obj = new("/d/antioch/valley/obj/sunblade");
obj->set_property("monsterweapon",1);
obj->move(TO);
command("wield sword");
obj = new("/d/antioch/valley/obj/shining_sword");
obj->set_property("monsterweapon",1);
obj->move(TO);
command("wield sword");
break;
}
set_class(theclass);
set_guild_level(theclass,24);
set_stats("strength",22);
set_stats("dexterity",20);
set_stats("constitution",19);
set_stats("charisma",18);
set_mob_magic_resistance("average");
set_property("add kits",20);
if(!random(5)) new("/d/deku/armours/ring_p")->move(TO);
obj = new("/d/shadow/obj/clothing/silkcloak");
if(random(3)) obj->set_property("monsterweapon",1);
obj->move(TO);
command("wearall");
set_property("swarm",1);
set_property("full attacks",1);
set("aggressive", "kill_em");
set_emotes(5,({
"%^RESET%^%^MAGENTA%^The "+theclass+" says:%^RESET%^ This land is no longer secure. Return to the mainland if you are concerned with your safety.",
"The "+theclass+" patrols the ruins with an air of purpose.",
"With a concerned frown, the "+theclass+" leans down to examine something on the ground.",
"The "+theclass+" touches "+poss+" holy symbol of "+capitalize(faith)+" and whispers a brief prayer."
}),0);
set_emotes(2,({
"%^BOLD%^%^MAGENTA%^The "+theclass+" yells:%^RESET%^ You dare to attack a "+theclass+" of "+capitalize(faith)+"?!",
"%^YELLOW%^The "+theclass+" spins "+poss+" sword and readies for another attack!%^RESET%^",
"%^BOLD%^The "+theclass+" calls out a prayer to "+capitalize(faith)+" and attacks!%^RESET%^"
}),1);
// set_funcs(({"headlock","kick"}));
// set_func_chance(30);
set_moving(1);
set_speed(10);
}
void kill_em(object targ) {
if(member_array("forestmon",TP->query_id()) != -1) {
force_me("say %^BOLD%^Asgard will rise again! Be gone, foul creature!");
force_me("kill "+TPQN);
}
return;
}
int cast_check(object obj)
{
if(!objectp(obj)) { return 0; }
if(obj->query_property("spell_casting")) { return 0; }
return 1;
}
void headlock(object targ){
if(!"daemon/saving_d"->saving_throw(targ,"paralyzation_poison_death")){
tell_object(targ,"%^BOLD%^GREEN%^The Commando slips in behind you and puts you in a painful headlock!");
tell_room(ETO,"%^BOLD%^GREEN%^The Commando slips in behind "+targ->query_cap_name()+" and puts "+targ->query_objective()+" in a headlock!",targ);
targ->set_paralyzed(30,"You are in a headlock.");
return 1;
}
tell_object(targ,"%^BOLD%^GREEN%^The Commando attempts to slip in behind you but you cut him off!");
tell_room(ETO,"%^BOLD%^GREEN%^The Commando attempts to slip in behind "+targ->query_cap_name()+" but "+targ->query_subjective()+" cuts him off!",targ);
return 1;
}
void kick(object targ){
if(!"daemon/saving_d"->saving_throw(targ,"rod_staff_wand")){
tell_object(targ,"%^BOLD%^RED%^The Commando sends a bone crunching karate kick right to your throat!");
tell_room(ETO,"%^BOLD%^RED%^The Commando sends a bone crunching karate kick right to "+targ->query_cap_name()+"'s throat!",targ);
targ->do_damage(targ->return_target_limb(),roll_dice(5,10)+10);
return 1;
}
tell_object(targ,"%^BOLD%^RED%^The Commando sends a karate kick towards you but you dodge out of the way!");
tell_room(ETO,"%^BOLD%^RED%^The Commando sends a karate kick at "+targ->query_cap_name()+" but "+targ->query_subjective()+" dodges out of the way!",targ);
return 1;
}
void init(){
::init();
if((string)TP->query_race() == "troll"){
force_me("say You will not profit from the destruction of civilization!");
force_me("kill troll");
}
if(member_array("forestmon",TP->query_id()) != -1) {
force_me("say %^BOLD%^Asgard will rise again! Be gone, foul creature!");
force_me("kill forestmon");
}
}
//horse code stolen from shifters
void horse_me(){
object ob;
set_nwp("riding",50);
ob = new("/d/common/mounts/war_horse");
ob->set_owner(TO);
ob->set_property("water breather",1);
ob->set_level((int)TO->query_level());
ob->move(ETO);
TO->force_me("mount horse");
if(objectp(ob) && objectp(TO)) { ob->add_protector(TO); }
ob = new("/d/common/obj/weapon/lance");
ob->set_property("enchantment",3);
ob->set_property("monsterweapon",1);
ob->move(TO);
TO->force_me("wield lance");
return;
}
| 47.261062 | 158 | 0.561558 | [
"object"
] |
9671bd5eeba00e0fb5520ff5f307fb43cfac24d6 | 406 | h | C | include/lang/type/closure.h | zellio/zlisp | d40b8c30a100a3f0ce85fb962ce3dba3f35869f8 | [
"MIT"
] | 2 | 2015-03-09T12:34:43.000Z | 2017-05-03T07:41:47.000Z | include/lang/type/closure.h | zellio/zlisp | d40b8c30a100a3f0ce85fb962ce3dba3f35869f8 | [
"MIT"
] | null | null | null | include/lang/type/closure.h | zellio/zlisp | d40b8c30a100a3f0ce85fb962ce3dba3f35869f8 | [
"MIT"
] | null | null | null | #ifndef __ZL_LANG_TYPE_CLOSURE_H__
#define __ZL_LANG_TYPE_CLOSURE_H__ 1
#include "lang/type/object.h"
#ifdef __cplusplus
extern "C" {
#endif
#if 0
}
#endif
object_t *closure_create(object_t *params, object_t *body, object_t *env);
#define is_closure(x) (IS_TYPE((x), TYPE_CLOSURE))
int closure_destructor(object_t *self);
char *closure_to_string(object_t *self);
#ifdef __cplusplus
};
#endif
#endif
| 16.24 | 74 | 0.76601 | [
"object"
] |
9677aa4de0219391d6c3f59cd6a7a5c2085e41c2 | 21,557 | h | C | src/wasm-delegations-fields.h | ospencer/binaryen | a74bc72dbe6fa5f3edacfba160dc4e5d630b99b6 | [
"Apache-2.0"
] | null | null | null | src/wasm-delegations-fields.h | ospencer/binaryen | a74bc72dbe6fa5f3edacfba160dc4e5d630b99b6 | [
"Apache-2.0"
] | null | null | null | src/wasm-delegations-fields.h | ospencer/binaryen | a74bc72dbe6fa5f3edacfba160dc4e5d630b99b6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Implements a switch on an expression class ID, and has a case for each id
// in which it runs delegates on the fields and immediates. You should include
// this file after defining the relevant DELEGATE_* macros.
//
// All defines used here are undefed automatically at the end for you.
//
// Most of the defines are necessary, and you will get an error if you forget
// them, but some are optional and some imply others, see below.
//
// The defines are as follows:
//
// DELEGATE_START(id) - called at the start of a case for an expression class.
//
// DELEGATE_END(id) - called at the end of a case.
//
// DELEGATE_GET_FIELD(id, name) - called to get a field by its name. This must
// know the object on which to get it, so it is just useful for the case
// where you operate on a single such object, but in that case it is nice
// because then other things can be defined automatically for you, see later.
//
// DELEGATE_FIELD_CHILD(id, name) - called for each child field (note: children
// are visited in reverse order, which is convenient for walking by pushing
// them to a stack first).
//
// DELEGATE_FIELD_OPTIONAL_CHILD(id, name) - called for a child that may not be
// present (like a Return's value). If you do not define this then
// DELEGATE_FIELD_CHILD is called.
//
// DELEGATE_FIELD_CHILD_VECTOR(id, name) - called for a variable-sized vector of
// child pointers. If this is not defined, and DELEGATE_GET_FIELD is, then
// DELEGATE_FIELD_CHILD is called on them.
//
// DELEGATE_FIELD_INT(id, name) - called for an integer field (bool, enum,
// Index, int32, or int64).
//
// DELEGATE_FIELD_INT_ARRAY(id, name) - called for a std::array of fixed size of
// integer values (like a SIMD mask). If this is not defined, and
// DELEGATE_GET_FIELD is, then DELEGATE_FIELD_INT is called on them.
//
// DELEGATE_FIELD_LITERAL(id, name) - called for a Literal.
//
// DELEGATE_FIELD_NAME(id, name) - called for a Name.
//
// DELEGATE_FIELD_NAME_VECTOR(id, name) - called for a variable-sized vector of
// names (like try's catch event names). If this is not defined, and
// DELEGATE_GET_FIELD is, then DELEGATE_FIELD_CHILD is called on them.
//
// DELEGATE_FIELD_SCOPE_NAME_DEF(id, name) - called for a scope name definition
// (like a block's name).
//
// DELEGATE_FIELD_SCOPE_NAME_USE(id, name) - called for a scope name use (like
// a break's target).
//
// DELEGATE_FIELD_SCOPE_NAME_USE_VECTOR(id, name) - called for a variable-sized
// vector of scope names (like a switch's targets). If this is not defined,
// and DELEGATE_GET_FIELD is, then DELEGATE_FIELD_SCOPE_NAME_USE is called on
// them.
//
// DELEGATE_FIELD_SIGNATURE(id, name) - called for a Signature.
//
// DELEGATE_FIELD_TYPE(id, name) - called for a Type.
//
// DELEGATE_FIELD_ADDRESS(id, name) - called for an Address.
#ifndef DELEGATE_START
#define DELEGATE_START(id)
#endif
#ifndef DELEGATE_END
#define DELEGATE_END(id)
#endif
#ifndef DELEGATE_FIELD_CHILD
#error please define DELEGATE_FIELD_CHILD(id, name)
#endif
#ifndef DELEGATE_FIELD_OPTIONAL_CHILD
#define DELEGATE_FIELD_OPTIONAL_CHILD(id, name) DELEGATE_FIELD_CHILD(id, name)
#endif
#ifndef DELEGATE_FIELD_CHILD_VECTOR
#ifdef DELEGATE_GET_FIELD
#define DELEGATE_FIELD_CHILD_VECTOR(id, name) \
for (int i = int((DELEGATE_GET_FIELD(id, name)).size()) - 1; i >= 0; i--) { \
DELEGATE_FIELD_CHILD(id, name[i]); \
}
#else
#error please define DELEGATE_FIELD_CHILD_VECTOR(id, name)
#endif
#endif
#ifndef DELEGATE_FIELD_INT
#error please define DELEGATE_FIELD_INT(id, name)
#endif
#ifndef DELEGATE_FIELD_INT_ARRAY
#ifdef DELEGATE_GET_FIELD
#define DELEGATE_FIELD_INT_ARRAY(id, name) \
for (Index i = 0; i < (DELEGATE_GET_FIELD(id, name)).size(); i++) { \
DELEGATE_FIELD_INT(id, name[i]); \
}
#else
#error please define DELEGATE_FIELD_INT_ARRAY(id, name)
#endif
#endif
#ifndef DELEGATE_FIELD_LITERAL
#error please define DELEGATE_FIELD_LITERAL(id, name)
#endif
#ifndef DELEGATE_FIELD_NAME
#error please define DELEGATE_FIELD_NAME(id, name)
#endif
#ifndef DELEGATE_FIELD_NAME_VECTOR
#ifdef DELEGATE_GET_FIELD
#define DELEGATE_FIELD_NAME_VECTOR(id, name) \
for (Index i = 0; i < (DELEGATE_GET_FIELD(id, name)).size(); i++) { \
DELEGATE_FIELD_NAME(id, name[i]); \
}
#else
#error please define DELEGATE_FIELD_NAME_VECTOR(id, name)
#endif
#endif
#ifndef DELEGATE_FIELD_SCOPE_NAME_DEF
#error please define DELEGATE_FIELD_SCOPE_NAME_DEF(id, name)
#endif
#ifndef DELEGATE_FIELD_SCOPE_NAME_USE
#error please define DELEGATE_FIELD_SCOPE_NAME_USE(id, name)
#endif
#ifndef DELEGATE_FIELD_SCOPE_NAME_USE_VECTOR
#ifdef DELEGATE_GET_FIELD
#define DELEGATE_FIELD_SCOPE_NAME_USE_VECTOR(id, name) \
for (Index i = 0; i < (DELEGATE_GET_FIELD(id, name)).size(); i++) { \
DELEGATE_FIELD_SCOPE_NAME_USE(id, name[i]); \
}
#else
#error please define DELEGATE_FIELD_SCOPE_NAME_USE_VECTOR(id, name)
#endif
#endif
#ifndef DELEGATE_FIELD_SIGNATURE
#error please define DELEGATE_FIELD_SIGNATURE(id, name)
#endif
#ifndef DELEGATE_FIELD_TYPE
#error please define DELEGATE_FIELD_TYPE(id, name)
#endif
#ifndef DELEGATE_FIELD_ADDRESS
#error please define DELEGATE_FIELD_ADDRESS(id, name)
#endif
switch (DELEGATE_ID) {
case Expression::Id::InvalidId:
case Expression::Id::NumExpressionIds: {
WASM_UNREACHABLE("unexpected expression type");
}
case Expression::Id::BlockId: {
DELEGATE_START(Block);
DELEGATE_FIELD_CHILD_VECTOR(Block, list);
DELEGATE_FIELD_SCOPE_NAME_DEF(Block, name);
DELEGATE_END(Block);
break;
}
case Expression::Id::IfId: {
DELEGATE_START(If);
DELEGATE_FIELD_OPTIONAL_CHILD(If, ifFalse);
DELEGATE_FIELD_CHILD(If, ifTrue);
DELEGATE_FIELD_CHILD(If, condition);
DELEGATE_END(If);
break;
}
case Expression::Id::LoopId: {
DELEGATE_START(Loop);
DELEGATE_FIELD_CHILD(Loop, body);
DELEGATE_FIELD_SCOPE_NAME_DEF(Loop, name);
DELEGATE_END(Loop);
break;
}
case Expression::Id::BreakId: {
DELEGATE_START(Break);
DELEGATE_FIELD_OPTIONAL_CHILD(Break, condition);
DELEGATE_FIELD_OPTIONAL_CHILD(Break, value);
DELEGATE_FIELD_SCOPE_NAME_USE(Break, name);
DELEGATE_END(Break);
break;
}
case Expression::Id::SwitchId: {
DELEGATE_START(Switch);
DELEGATE_FIELD_CHILD(Switch, condition);
DELEGATE_FIELD_OPTIONAL_CHILD(Switch, value);
DELEGATE_FIELD_SCOPE_NAME_USE(Switch, default_);
DELEGATE_FIELD_SCOPE_NAME_USE_VECTOR(Switch, targets);
DELEGATE_END(Switch);
break;
}
case Expression::Id::CallId: {
DELEGATE_START(Call);
DELEGATE_FIELD_CHILD_VECTOR(Call, operands);
DELEGATE_FIELD_NAME(Call, target);
DELEGATE_FIELD_INT(Call, isReturn);
DELEGATE_END(Call);
break;
}
case Expression::Id::CallIndirectId: {
DELEGATE_START(CallIndirect);
DELEGATE_FIELD_CHILD(CallIndirect, target);
DELEGATE_FIELD_NAME(CallIndirect, table);
DELEGATE_FIELD_CHILD_VECTOR(CallIndirect, operands);
DELEGATE_FIELD_SIGNATURE(CallIndirect, sig);
DELEGATE_FIELD_INT(CallIndirect, isReturn);
DELEGATE_END(CallIndirect);
break;
}
case Expression::Id::LocalGetId: {
DELEGATE_START(LocalGet);
DELEGATE_FIELD_INT(LocalGet, index);
DELEGATE_END(LocalGet);
break;
}
case Expression::Id::LocalSetId: {
DELEGATE_START(LocalSet);
DELEGATE_FIELD_CHILD(LocalSet, value);
DELEGATE_FIELD_INT(LocalSet, index);
DELEGATE_END(LocalSet);
break;
}
case Expression::Id::GlobalGetId: {
DELEGATE_START(GlobalGet);
DELEGATE_FIELD_INT(GlobalGet, name);
DELEGATE_END(GlobalGet);
break;
}
case Expression::Id::GlobalSetId: {
DELEGATE_START(GlobalSet);
DELEGATE_FIELD_CHILD(GlobalSet, value);
DELEGATE_FIELD_INT(GlobalSet, name);
DELEGATE_END(GlobalSet);
break;
}
case Expression::Id::LoadId: {
DELEGATE_START(Load);
DELEGATE_FIELD_CHILD(Load, ptr);
DELEGATE_FIELD_INT(Load, bytes);
DELEGATE_FIELD_INT(Load, signed_);
DELEGATE_FIELD_ADDRESS(Load, offset);
DELEGATE_FIELD_ADDRESS(Load, align);
DELEGATE_FIELD_INT(Load, isAtomic);
DELEGATE_END(Load);
break;
}
case Expression::Id::StoreId: {
DELEGATE_START(Store);
DELEGATE_FIELD_CHILD(Store, value);
DELEGATE_FIELD_CHILD(Store, ptr);
DELEGATE_FIELD_INT(Store, bytes);
DELEGATE_FIELD_ADDRESS(Store, offset);
DELEGATE_FIELD_ADDRESS(Store, align);
DELEGATE_FIELD_INT(Store, isAtomic);
DELEGATE_FIELD_TYPE(Store, valueType);
DELEGATE_END(Store);
break;
}
case Expression::Id::AtomicRMWId: {
DELEGATE_START(AtomicRMW);
DELEGATE_FIELD_CHILD(AtomicRMW, value);
DELEGATE_FIELD_CHILD(AtomicRMW, ptr);
DELEGATE_FIELD_INT(AtomicRMW, op);
DELEGATE_FIELD_INT(AtomicRMW, bytes);
DELEGATE_FIELD_ADDRESS(AtomicRMW, offset);
DELEGATE_END(AtomicRMW);
break;
}
case Expression::Id::AtomicCmpxchgId: {
DELEGATE_START(AtomicCmpxchg);
DELEGATE_FIELD_CHILD(AtomicCmpxchg, replacement);
DELEGATE_FIELD_CHILD(AtomicCmpxchg, expected);
DELEGATE_FIELD_CHILD(AtomicCmpxchg, ptr);
DELEGATE_FIELD_INT(AtomicCmpxchg, bytes);
DELEGATE_FIELD_ADDRESS(AtomicCmpxchg, offset);
DELEGATE_END(AtomicCmpxchgId);
break;
}
case Expression::Id::AtomicWaitId: {
DELEGATE_START(AtomicWait);
DELEGATE_FIELD_CHILD(AtomicWait, timeout);
DELEGATE_FIELD_CHILD(AtomicWait, expected);
DELEGATE_FIELD_CHILD(AtomicWait, ptr);
DELEGATE_FIELD_ADDRESS(AtomicWait, offset);
DELEGATE_FIELD_TYPE(AtomicWait, expectedType);
DELEGATE_END(AtomicWait);
break;
}
case Expression::Id::AtomicNotifyId: {
DELEGATE_START(AtomicNotify);
DELEGATE_FIELD_CHILD(AtomicNotify, notifyCount);
DELEGATE_FIELD_CHILD(AtomicNotify, ptr);
DELEGATE_FIELD_ADDRESS(AtomicNotify, offset);
DELEGATE_END(AtomicNotify);
break;
}
case Expression::Id::AtomicFenceId: {
DELEGATE_START(AtomicFence);
DELEGATE_FIELD_INT(AtomicFence, order);
DELEGATE_END(AtomicFence);
break;
}
case Expression::Id::SIMDExtractId: {
DELEGATE_START(SIMDExtract);
DELEGATE_FIELD_CHILD(SIMDExtract, vec);
DELEGATE_FIELD_INT(SIMDExtract, op);
DELEGATE_FIELD_INT(SIMDExtract, index);
DELEGATE_END(SIMDExtract);
break;
}
case Expression::Id::SIMDReplaceId: {
DELEGATE_START(SIMDReplace);
DELEGATE_FIELD_CHILD(SIMDReplace, value);
DELEGATE_FIELD_CHILD(SIMDReplace, vec);
DELEGATE_FIELD_INT(SIMDReplace, op);
DELEGATE_FIELD_INT(SIMDReplace, index);
DELEGATE_END(SIMDReplace);
break;
}
case Expression::Id::SIMDShuffleId: {
DELEGATE_START(SIMDShuffle);
DELEGATE_FIELD_CHILD(SIMDShuffle, right);
DELEGATE_FIELD_CHILD(SIMDShuffle, left);
DELEGATE_FIELD_INT_ARRAY(SIMDShuffle, mask);
DELEGATE_END(SIMDShuffle);
break;
}
case Expression::Id::SIMDTernaryId: {
DELEGATE_START(SIMDTernary);
DELEGATE_FIELD_CHILD(SIMDTernary, c);
DELEGATE_FIELD_CHILD(SIMDTernary, b);
DELEGATE_FIELD_CHILD(SIMDTernary, a);
DELEGATE_FIELD_INT(SIMDTernary, op);
DELEGATE_END(SIMDTernary);
break;
}
case Expression::Id::SIMDShiftId: {
DELEGATE_START(SIMDShift);
DELEGATE_FIELD_CHILD(SIMDShift, shift);
DELEGATE_FIELD_CHILD(SIMDShift, vec);
DELEGATE_FIELD_INT(SIMDShift, op);
DELEGATE_END(SIMDShift);
break;
}
case Expression::Id::SIMDLoadId: {
DELEGATE_START(SIMDLoad);
DELEGATE_FIELD_CHILD(SIMDLoad, ptr);
DELEGATE_FIELD_INT(SIMDLoad, op);
DELEGATE_FIELD_ADDRESS(SIMDLoad, offset);
DELEGATE_FIELD_ADDRESS(SIMDLoad, align);
DELEGATE_END(SIMDLoad);
break;
}
case Expression::Id::SIMDLoadStoreLaneId: {
DELEGATE_START(SIMDLoadStoreLane);
DELEGATE_FIELD_CHILD(SIMDLoadStoreLane, vec);
DELEGATE_FIELD_CHILD(SIMDLoadStoreLane, ptr);
DELEGATE_FIELD_INT(SIMDLoadStoreLane, op);
DELEGATE_FIELD_ADDRESS(SIMDLoadStoreLane, offset);
DELEGATE_FIELD_ADDRESS(SIMDLoadStoreLane, align);
DELEGATE_FIELD_INT(SIMDLoadStoreLane, index);
DELEGATE_END(SIMDLoadStoreLane);
break;
}
case Expression::Id::SIMDWidenId: {
DELEGATE_START(SIMDWiden);
DELEGATE_FIELD_CHILD(SIMDWiden, vec);
DELEGATE_FIELD_INT(SIMDWiden, op);
DELEGATE_FIELD_INT(SIMDWiden, index);
DELEGATE_END(SIMDWiden);
break;
}
case Expression::Id::PrefetchId: {
DELEGATE_START(Prefetch);
DELEGATE_FIELD_CHILD(Prefetch, ptr);
DELEGATE_FIELD_INT(Prefetch, op);
DELEGATE_FIELD_ADDRESS(Prefetch, offset);
DELEGATE_FIELD_ADDRESS(Prefetch, align);
DELEGATE_END(Prefetch);
break;
}
case Expression::Id::MemoryInitId: {
DELEGATE_START(MemoryInit);
DELEGATE_FIELD_CHILD(MemoryInit, size);
DELEGATE_FIELD_CHILD(MemoryInit, offset);
DELEGATE_FIELD_CHILD(MemoryInit, dest);
DELEGATE_FIELD_INT(MemoryInit, segment);
DELEGATE_END(MemoryInit);
break;
}
case Expression::Id::DataDropId: {
DELEGATE_START(DataDrop);
DELEGATE_FIELD_INT(DataDrop, segment);
DELEGATE_END(DataDrop);
break;
}
case Expression::Id::MemoryCopyId: {
DELEGATE_START(MemoryCopy);
DELEGATE_FIELD_CHILD(MemoryCopy, size);
DELEGATE_FIELD_CHILD(MemoryCopy, source);
DELEGATE_FIELD_CHILD(MemoryCopy, dest);
DELEGATE_END(MemoryCopy);
break;
}
case Expression::Id::MemoryFillId: {
DELEGATE_START(MemoryFill);
DELEGATE_FIELD_CHILD(MemoryFill, size);
DELEGATE_FIELD_CHILD(MemoryFill, value);
DELEGATE_FIELD_CHILD(MemoryFill, dest);
DELEGATE_END(MemoryFill);
break;
}
case Expression::Id::ConstId: {
DELEGATE_START(Const);
DELEGATE_FIELD_LITERAL(Const, value);
DELEGATE_END(Const);
break;
}
case Expression::Id::UnaryId: {
DELEGATE_START(Unary);
DELEGATE_FIELD_CHILD(Unary, value);
DELEGATE_FIELD_INT(Unary, op);
DELEGATE_END(Unary);
break;
}
case Expression::Id::BinaryId: {
DELEGATE_START(Binary);
DELEGATE_FIELD_CHILD(Binary, right);
DELEGATE_FIELD_CHILD(Binary, left);
DELEGATE_FIELD_INT(Binary, op);
DELEGATE_END(Binary);
break;
}
case Expression::Id::SelectId: {
DELEGATE_START(Select);
DELEGATE_FIELD_CHILD(Select, condition);
DELEGATE_FIELD_CHILD(Select, ifFalse);
DELEGATE_FIELD_CHILD(Select, ifTrue);
DELEGATE_END(Select);
break;
}
case Expression::Id::DropId: {
DELEGATE_START(Drop);
DELEGATE_FIELD_CHILD(Drop, value);
DELEGATE_END(Drop);
break;
}
case Expression::Id::ReturnId: {
DELEGATE_START(Return);
DELEGATE_FIELD_OPTIONAL_CHILD(Return, value);
DELEGATE_END(Return);
break;
}
case Expression::Id::MemorySizeId: {
DELEGATE_START(MemorySize);
DELEGATE_END(MemorySize);
break;
}
case Expression::Id::MemoryGrowId: {
DELEGATE_START(MemoryGrow);
DELEGATE_FIELD_CHILD(MemoryGrow, delta);
DELEGATE_END(MemoryGrow);
break;
}
case Expression::Id::RefNullId: {
DELEGATE_START(RefNull);
DELEGATE_FIELD_TYPE(RefNull, type);
DELEGATE_END(RefNull);
break;
}
case Expression::Id::RefIsId: {
DELEGATE_START(RefIs);
DELEGATE_FIELD_INT(RefIs, op);
DELEGATE_FIELD_CHILD(RefIs, value);
DELEGATE_END(RefIs);
break;
}
case Expression::Id::RefFuncId: {
DELEGATE_START(RefFunc);
DELEGATE_FIELD_NAME(RefFunc, func);
DELEGATE_END(RefFunc);
break;
}
case Expression::Id::RefEqId: {
DELEGATE_START(RefEq);
DELEGATE_FIELD_CHILD(RefEq, right);
DELEGATE_FIELD_CHILD(RefEq, left);
DELEGATE_END(RefEq);
break;
}
case Expression::Id::TryId: {
DELEGATE_START(Try);
DELEGATE_FIELD_SCOPE_NAME_USE(Try, delegateTarget);
DELEGATE_FIELD_CHILD_VECTOR(Try, catchBodies);
DELEGATE_FIELD_NAME_VECTOR(Try, catchEvents);
DELEGATE_FIELD_SCOPE_NAME_DEF(Try, name);
DELEGATE_FIELD_CHILD(Try, body);
DELEGATE_END(Try);
break;
}
case Expression::Id::ThrowId: {
DELEGATE_START(Throw);
DELEGATE_FIELD_CHILD_VECTOR(Throw, operands);
DELEGATE_FIELD_NAME(Throw, event);
DELEGATE_END(Throw);
break;
}
case Expression::Id::RethrowId: {
DELEGATE_START(Rethrow);
DELEGATE_FIELD_INT(Rethrow, depth);
DELEGATE_END(Rethrow);
break;
}
case Expression::Id::NopId: {
DELEGATE_START(Nop);
DELEGATE_END(Nop);
break;
}
case Expression::Id::UnreachableId: {
DELEGATE_START(Unreachable);
DELEGATE_END(Unreachable);
break;
}
case Expression::Id::PopId: {
DELEGATE_START(Pop);
DELEGATE_END(Pop);
break;
}
case Expression::Id::TupleMakeId: {
DELEGATE_START(TupleMake);
DELEGATE_FIELD_CHILD_VECTOR(Tuple, operands);
DELEGATE_END(TupleMake);
break;
}
case Expression::Id::TupleExtractId: {
DELEGATE_START(TupleExtract);
DELEGATE_FIELD_CHILD(TupleExtract, tuple);
DELEGATE_FIELD_INT(TupleExtract, index);
DELEGATE_END(TupleExtract);
break;
}
case Expression::Id::I31NewId: {
DELEGATE_START(I31New);
DELEGATE_FIELD_CHILD(I31New, value);
DELEGATE_END(I31New);
break;
}
case Expression::Id::I31GetId: {
DELEGATE_START(I31Get);
DELEGATE_FIELD_CHILD(I31Get, i31);
DELEGATE_FIELD_INT(I31Get, signed_);
DELEGATE_END(I31Get);
break;
}
case Expression::Id::CallRefId: {
DELEGATE_START(CallRef);
DELEGATE_FIELD_CHILD(CallRef, target);
DELEGATE_FIELD_CHILD_VECTOR(CallRef, operands);
DELEGATE_FIELD_INT(CallRef, isReturn);
DELEGATE_END(CallRef);
break;
}
case Expression::Id::RefTestId: {
DELEGATE_START(RefTest);
DELEGATE_FIELD_CHILD(RefTest, rtt);
DELEGATE_FIELD_CHILD(RefTest, ref);
DELEGATE_END(RefTest);
break;
}
case Expression::Id::RefCastId: {
DELEGATE_START(RefCast);
DELEGATE_FIELD_CHILD(RefCast, rtt);
DELEGATE_FIELD_CHILD(RefCast, ref);
DELEGATE_END(RefCast);
break;
}
case Expression::Id::BrOnId: {
DELEGATE_START(BrOn);
DELEGATE_FIELD_INT(BrOn, op);
DELEGATE_FIELD_SCOPE_NAME_USE(BrOn, name);
DELEGATE_FIELD_OPTIONAL_CHILD(BrOn, rtt);
DELEGATE_FIELD_CHILD(BrOn, ref);
DELEGATE_END(BrOn);
break;
}
case Expression::Id::RttCanonId: {
DELEGATE_START(RttCanon);
DELEGATE_END(RttCanon);
break;
}
case Expression::Id::RttSubId: {
DELEGATE_START(RttSub);
DELEGATE_FIELD_CHILD(RttSub, parent);
DELEGATE_END(RttSub);
break;
}
case Expression::Id::StructNewId: {
DELEGATE_START(StructNew);
DELEGATE_FIELD_CHILD(StructNew, rtt);
DELEGATE_FIELD_CHILD_VECTOR(StructNew, operands);
DELEGATE_END(StructNew);
break;
}
case Expression::Id::StructGetId: {
DELEGATE_START(StructGet);
DELEGATE_FIELD_INT(StructGet, index);
DELEGATE_FIELD_CHILD(StructGet, ref);
DELEGATE_FIELD_INT(StructGet, signed_);
DELEGATE_END(StructGet);
break;
}
case Expression::Id::StructSetId: {
DELEGATE_START(StructSet);
DELEGATE_FIELD_INT(StructSet, index);
DELEGATE_FIELD_CHILD(StructSet, value);
DELEGATE_FIELD_CHILD(StructSet, ref);
DELEGATE_END(StructSet);
break;
}
case Expression::Id::ArrayNewId: {
DELEGATE_START(ArrayNew);
DELEGATE_FIELD_CHILD(ArrayNew, rtt);
DELEGATE_FIELD_CHILD(ArrayNew, size);
DELEGATE_FIELD_OPTIONAL_CHILD(ArrayNew, init);
DELEGATE_END(ArrayNew);
break;
}
case Expression::Id::ArrayGetId: {
DELEGATE_START(ArrayGet);
DELEGATE_FIELD_CHILD(ArrayGet, index);
DELEGATE_FIELD_CHILD(ArrayGet, ref);
DELEGATE_FIELD_INT(ArrayGet, signed_);
DELEGATE_END(ArrayGet);
break;
}
case Expression::Id::ArraySetId: {
DELEGATE_START(ArraySet);
DELEGATE_FIELD_CHILD(ArrayGet, value);
DELEGATE_FIELD_CHILD(ArrayGet, index);
DELEGATE_FIELD_CHILD(ArrayGet, ref);
DELEGATE_END(ArraySet);
break;
}
case Expression::Id::ArrayLenId: {
DELEGATE_START(ArrayLen);
DELEGATE_FIELD_CHILD(ArrayLen, ref);
DELEGATE_END(ArrayLen);
break;
}
case Expression::Id::RefAsId: {
DELEGATE_START(RefAs);
DELEGATE_FIELD_INT(RefAs, op);
DELEGATE_FIELD_CHILD(RefAs, value);
DELEGATE_END(RefAs);
break;
}
}
#undef DELEGATE_ID
#undef DELEGATE_START
#undef DELEGATE_END
#undef DELEGATE_FIELD_CHILD
#undef DELEGATE_FIELD_OPTIONAL_CHILD
#undef DELEGATE_FIELD_CHILD_VECTOR
#undef DELEGATE_FIELD_INT
#undef DELEGATE_FIELD_INT_ARRAY
#undef DELEGATE_FIELD_LITERAL
#undef DELEGATE_FIELD_NAME
#undef DELEGATE_FIELD_NAME_VECTOR
#undef DELEGATE_FIELD_SCOPE_NAME_DEF
#undef DELEGATE_FIELD_SCOPE_NAME_USE
#undef DELEGATE_FIELD_SCOPE_NAME_USE_VECTOR
#undef DELEGATE_FIELD_SIGNATURE
#undef DELEGATE_FIELD_TYPE
#undef DELEGATE_FIELD_ADDRESS
#undef DELEGATE_GET_FIELD
| 30.707977 | 80 | 0.720323 | [
"object",
"vector"
] |
3234d9840092643a0a667b47f816806af81df01e | 34,005 | h | C | externals/optix-7.0.0/include/optix_7_host.h | blaine141/NVISII | 1675bb9bb74a1fe441bbb10ca98ea5cc4b0e4e24 | [
"Apache-2.0"
] | 149 | 2021-02-09T11:35:23.000Z | 2022-03-29T10:06:22.000Z | externals/optix-7.0.0/include/optix_7_host.h | blaine141/NVISII | 1675bb9bb74a1fe441bbb10ca98ea5cc4b0e4e24 | [
"Apache-2.0"
] | 66 | 2020-05-28T18:53:21.000Z | 2021-02-07T05:34:14.000Z | lib/OptiX7/include/optix_7_host.h | maxstoll94/lighthouse2 | c32cba1088fa790a339355ed5c3c45daaecfcaab | [
"Apache-2.0"
] | 14 | 2021-02-09T08:51:44.000Z | 2022-03-11T00:39:21.000Z | /*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES
*/
/// @file
/// @author NVIDIA Corporation
/// @brief OptiX public API header
///
/// OptiX host include file -- includes the host api if compiling host code.
/// For the math library routines include optix_math.h
#if !defined( __OPTIX_INCLUDE_INTERNAL_HEADERS__ )
#error("optix_7_host.h is an internal header file and must not be used directly. Please use optix_host.h or optix.h instead.")
#endif
#ifndef __optix_optix_7_host_h__
#define __optix_optix_7_host_h__
#include "optix_7_types.h"
#if !defined( OPTIX_DONT_INCLUDE_CUDA )
// If OPTIX_DONT_INCLUDE_CUDA is defined, cuda driver types must be defined through other
// means before including optix headers.
#include <cuda.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/// \name Error handling
//@ {
/// Returns a string containing the name of an error code in the enum.
///
/// If the error code is not recognized, "Unrecognized OptixResult code" is returned.
const char* optixGetErrorName( OptixResult result );
/// Returns the description string for an error code.
///
/// If the error code is not recognized, "Unrecognized OptixResult code" is returned.
const char* optixGetErrorString( OptixResult result );
//@ }
/// \name Device contexts
//@ {
/// Create a device context associated with the CUDA context specified with 'fromContext'.
///
/// If zero is specified for 'fromContext', OptiX will use the current CUDA context. The
/// CUDA context should be initialized before calling optixDeviceContextCreate.
///
/// \param[in] fromContext
/// \param[in] options
/// \param[out] context
/// \return
/// - OPTIX_ERROR_CUDA_NOT_INITIALIZED
/// If using zero for 'fromContext' and CUDA has not been initialized yet on the calling
/// thread.
/// - OPTIX_ERROR_CUDA_ERROR
/// CUDA operation failed.
/// - OPTIX_ERROR_HOST_OUT_OF_MEMORY
/// Heap allocation failed.
/// - OPTIX_ERROR_INTERNAL_ERROR
/// Internal error
OptixResult optixDeviceContextCreate( CUcontext fromContext, const OptixDeviceContextOptions* options, OptixDeviceContext* context );
/// Destroys all CPU and GPU state associated with the device.
///
/// It will attempt to block on CUDA streams that have launch work outstanding.
///
/// Any API objects, such as OptixModule and OptixPipeline, not already destroyed will be
/// destroyed.
///
/// Thread safety: A device context must not be destroyed while it is still in use by concurrent API calls in other threads.
OptixResult optixDeviceContextDestroy( OptixDeviceContext context );
/// Query properties of a device context.
///
/// \param[in] context the device context to query the property for
/// \param[in] property the property to query
/// \param[out] value pointer to the returned
/// \param[in] sizeInBytes size of output
OptixResult optixDeviceContextGetProperty( OptixDeviceContext context, OptixDeviceProperty property, void* value, size_t sizeInBytes );
/// Sets the current log callback method.
///
/// See OptixLogCallback for more details.
///
/// Thread safety: It is guaranteed that the callback itself (callbackFunction and callbackData) are updated atomically.
/// It is not guaranteed that the callback itself (callbackFunction and callbackData) and the callbackLevel are updated
/// atomically. It is unspecified when concurrent API calls using the same context start to make use of the new
/// callback method.
///
/// \param[in] context the device context
/// \param[in] callbackFunction the callback function to call
/// \param[in] callbackData pointer to data passed to callback function while invoking it
/// \param[in] callbackLevel callback level
OptixResult optixDeviceContextSetLogCallback( OptixDeviceContext context,
OptixLogCallback callbackFunction,
void* callbackData,
unsigned int callbackLevel );
/// Enables or disables the disk cache.
///
/// If caching was previously disabled, enabling it will attempt to initialize
/// the disk cache database using the currently configured cache location. An
/// error will be returned if initialization fails.
///
/// Note that no in-memory cache is used, so no caching behavior will be observed if the disk cache
/// is disabled.
///
/// \param[in] context the device context
/// \param[in] enabled 1 to enabled, 0 to disable
OptixResult optixDeviceContextSetCacheEnabled( OptixDeviceContext context,
int enabled );
/// Sets the location of the disk cache.
///
/// The location is specified by a directory. This directory should not be used for other purposes
/// and will be created if it does not exist. An error will be returned if is not possible to
/// create the disk cache at the specified location for any reason (e.g., the path is invalid or
/// the directory is not writable). Caching will be disabled if the disk cache cannot be
/// initialized in the new location. If caching is disabled, no error will be returned until caching
/// is enabled. If the disk cache is located on a network file share, behavior is undefined.
///
/// The location of the disk cache can be overridden with the environment variable OPTIX_CACHE_PATH.
/// The environment variable takes precedence over this setting.
///
/// The default location depends on the operating system:
/// - Windows: %LOCALAPPDATA%\\NVIDIA\\OptixCache
/// - Linux: /var/tmp/OptixCache_\<username\> (or /tmp/OptixCache_\<username\> if the first choice is not usable),
/// the underscore and username suffix are omitted if the username cannot be obtained
/// - MacOS X: /Library/Application Support/NVIDIA/OptixCache
///
/// \param[in] context the device context
/// \param[in] location directory of disk cache
OptixResult optixDeviceContextSetCacheLocation( OptixDeviceContext context, const char* location );
/// Sets the low and high water marks for disk cache garbage collection.
///
/// Garbage collection is triggered when a new entry is written to the cache and
/// the current cache data size plus the size of the cache entry that is about
/// to be inserted exceeds the high water mark. Garbage collection proceeds until
/// the size reaches the low water mark. Garbage collection will always free enough
/// space to insert the new entry without exceeding the low water mark. Setting
/// either limit to zero will disable garbage collection. An error will be returned
/// if both limits are non-zero and the high water mark is smaller than the low water mark.
///
/// Note that garbage collection is performed only on writes to the disk cache. No garbage
/// collection is triggered on disk cache initialization or immediately when calling this function,
/// but on subsequent inserting of data into the database.
///
/// If the size of a compiled module exceeds the value configured for the high water
/// mark and garbage collection is enabled, the module will not be added to the cache
/// and a warning will be added to the log.
///
/// \param[in] context the device context
/// \param[in] lowWaterMark the low water mark
/// \param[in] highWaterMark the high water mark
OptixResult optixDeviceContextSetCacheDatabaseSizes( OptixDeviceContext context, size_t lowWaterMark, size_t highWaterMark );
/// Indicates whether the disk cache is enabled or disabled.
///
/// \param[in] context the device context
/// \param[out] enabled 1 if enabled, 0 if disabled
OptixResult optixDeviceContextGetCacheEnabled( OptixDeviceContext context, int* enabled );
/// Returns the location of the disk cache.
///
/// \param[in] context the device context
/// \param[out] location directory of disk cache, null terminated if locationSize > 0
/// \param[in] locationSize locationSize
OptixResult optixDeviceContextGetCacheLocation( OptixDeviceContext context, char* location, size_t locationSize );
/// Returns the low and high water marks for disk cache garbage collection.
///
/// \param[in] context the device context
/// \param[out] lowWaterMark the low water mark
/// \param[out] highWaterMark the high water mark
OptixResult optixDeviceContextGetCacheDatabaseSizes( OptixDeviceContext context, size_t* lowWaterMark, size_t* highWaterMark );
//@ }
/// \name Pipelines
//@ {
/// logString is an optional buffer that contains compiler feedback and errors. This
/// information is also passed to the context logger (if enabled), however it may be
/// difficult to correlate output to the logger to specific API invocations when using
/// multiple threads. The output to logString will only contain feedback for this specific
/// invocation of this API call.
///
/// logStringSize as input should be a pointer to the number of bytes backing logString.
/// Upon return it contains the length of the log message (including the null terminator)
/// which may be greater than the input value. In this case, the log message will be
/// truncated to fit into logString.
///
/// If logString or logStringSize are NULL, no output is written to logString. If
/// logStringSize points to a value that is zero, no output is written. This does not
/// affect output to the context logger if enabled.
///
/// \param[in] context
/// \param[in] pipelineCompileOptions
/// \param[in] pipelineLinkOptions
/// \param[in] programGroups array of ProgramGroup objects
/// \param[in] numProgramGroups number of ProgramGroup objects
/// \param[out] logString Information will be written to this string. If logStringSize > 0 logString will be null terminated.
/// \param[in,out] logStringSize
/// \param[out] pipeline
OptixResult optixPipelineCreate( OptixDeviceContext context,
const OptixPipelineCompileOptions* pipelineCompileOptions,
const OptixPipelineLinkOptions* pipelineLinkOptions,
const OptixProgramGroup* programGroups,
unsigned int numProgramGroups,
char* logString,
size_t* logStringSize,
OptixPipeline* pipeline );
/// Thread safety: A pipeline must not be destroyed while it is still in use by concurrent API calls in other threads.
OptixResult optixPipelineDestroy( OptixPipeline pipeline );
/// Sets the stack sizes for a pipeline.
///
/// Users are encouraged to see the programming guide and the implementations of the helper functions
/// to understand how to construct the stack sizes based on their particular needs.
///
/// If this method is not used, an internal default implementation is used. The default implementation is correct (but
/// not necessarily optimal) as long as the maximum depth of call trees of CC and DC programs is at most 2 and no motion transforms are used.
///
/// The maxTraversableGraphDepth responds to the maximal number of traversables visited when calling trace.
/// Every acceleration structure and motion transform count as one level of traversal.
/// E.g., for a simple IAS (instance acceleration structure) -> GAS (geometry acceleration structure)
/// traversal graph, the maxTraversableGraphDepth is two.
/// For IAS -> MT (motion transform) -> GAS, the maxTraversableGraphDepth is three.
/// Note that it does not matter whether a IAS or GAS has motion or not, it always counts as one.
/// Launching optix with exceptions turned on (see OPTIX_EXCEPTION_FLAG_TRACE_DEPTH) will throw an exception
/// if the specified maxTraversableGraphDepth is too small.
///
/// \param[in] pipeline The pipeline to configure the stack size for.
/// \param[in] directCallableStackSizeFromTraversal The direct stack size requirement for direct callables invoked from IS or AH.
/// \param[in] directCallableStackSizeFromState The direct stack size requirement for direct callables invoked from RG, MS, or CH.
/// \param[in] continuationStackSize The continuation stack requirement.
/// \param[in] maxTraversableGraphDepth The maximum depth of a traversable graph passed to trace.
OptixResult optixPipelineSetStackSize( OptixPipeline pipeline,
unsigned int directCallableStackSizeFromTraversal,
unsigned int directCallableStackSizeFromState,
unsigned int continuationStackSize,
unsigned int maxTraversableGraphDepth );
//@ }
/// \name Modules
//@ {
/// logString is an optional buffer that contains compiler feedback and errors. This
/// information is also passed to the context logger (if enabled), however it may be
/// difficult to correlate output to the logger to specific API invocations when using
/// multiple threads. The output to logString will only contain feedback for this specific
/// invocation of this API call.
///
/// logStringSize as input should be a pointer to the number of bytes backing logString.
/// Upon return it contains the length of the log message (including the null terminator)
/// which may be greater than the input value. In this case, the log message will be
/// truncated to fit into logString.
///
/// If logString or logStringSize are NULL, no output is written to logString. If
/// logStringSize points to a value that is zero, no output is written. This does not
/// affect output to the context logger if enabled.
///
/// \param[in] context
/// \param[in] moduleCompileOptions
/// \param[in] pipelineCompileOptions All modules in a pipeline need to use the same values for the pipeline compile options.
/// \param[in] PTX
/// \param[in] PTXsize
/// \param[out] logString Information will be written to this string. If logStringSize > 0 logString will be null terminated.
/// \param[in,out] logStringSize
/// \param[out] module
///
/// \return OPTIX_ERROR_INVALID_VALUE - context is 0, moduleCompileOptions is 0, pipelineCompileOptions is 0, PTX is 0, module is 0.
OptixResult optixModuleCreateFromPTX( OptixDeviceContext context,
const OptixModuleCompileOptions* moduleCompileOptions,
const OptixPipelineCompileOptions* pipelineCompileOptions,
const char* PTX,
size_t PTXsize,
char* logString,
size_t* logStringSize,
OptixModule* module );
/// Call for OptixModule objects created with optixModuleCreateFromPTX and optixModuleDeserialize.
///
/// Modules must not be destroyed while they are still used by any program group.
///
/// Thread safety: A module must not be destroyed while it is still in use by concurrent API calls in other threads.
OptixResult optixModuleDestroy( OptixModule module );
//@ }
/// \name Program groups
//@ {
/// Returns the stack sizes for the given program group.
///
/// \param[in] programGroup the program group
/// \param[out] stackSizes the corresponding stack sizes
OptixResult optixProgramGroupGetStackSize( OptixProgramGroup programGroup, OptixStackSizes* stackSizes );
/// logString is an optional buffer that contains compiler feedback and errors. This
/// information is also passed to the context logger (if enabled), however it may be
/// difficult to correlate output to the logger to specific API invocations when using
/// multiple threads. The output to logString will only contain feedback for this specific
/// invocation of this API call.
///
/// logStringSize as input should be a pointer to the number of bytes backing logString.
/// Upon return it contains the length of the log message (including the null terminator)
/// which may be greater than the input value. In this case, the log message will be
/// truncated to fit into logString.
///
/// If logString or logStringSize are NULL, no output is written to logString. If
/// logStringSize points to a value that is zero, no output is written. This does not
/// affect output to the context logger if enabled.
///
/// Creates numProgramGroups OptiXProgramGroup objects from the specified
/// OptixProgramGroupDesc array. The size of the arrays must match.
///
/// \param[in] context
/// \param[in] programDescriptions N * OptixProgramGroupDesc
/// \param[in] numProgramGroups N
/// \param[in] options
/// \param[out] logString Information will be written to this string. If logStringSize > 0 logString will be null terminated.
/// \param[in,out] logStringSize
/// \param[out] programGroups
OptixResult optixProgramGroupCreate( OptixDeviceContext context,
const OptixProgramGroupDesc* programDescriptions,
unsigned int numProgramGroups,
const OptixProgramGroupOptions* options,
char* logString,
size_t* logStringSize,
OptixProgramGroup* programGroups );
/// Thread safety: A program group must not be destroyed while it is still in use by concurrent API calls in other threads.
OptixResult optixProgramGroupDestroy( OptixProgramGroup programGroup );
//@ }
/// \name Launches
//@ {
/// Where the magic happens.
///
/// The stream and pipeline must belong to the same device context. Multiple launches
/// may be issues in parallel from multiple threads to different streams.
///
/// pipelineParamsSize number of bytes are copied from the device memory pointed to by
/// pipelineParams before launch. It is an error if pipelineParamsSize is greater than the
/// size of the variable declared in modules and identified by
/// OptixPipelineCompileOptions::pipelineLaunchParamsVariableName. If the launch params
/// variable was optimized out or not found in the modules linked to the pipeline then
/// the pipelineParams and pipelineParamsSize parameters are ignored.
///
/// sbt points to the shader binding table, which defines shader
/// groupings and their resources. See the SBT spec.
///
/// \param[in] pipeline
/// \param[in] stream
/// \param[in] pipelineParams
/// \param[in] pipelineParamsSize
/// \param[in] sbt
/// \param[in] width number of elements to compute
/// \param[in] height number of elements to compute
/// \param[in] depth number of elements to compute
///
/// Thread safety: In the current implementation concurrent launches to the same pipeline are not
/// supported. Concurrent launches require separate OptixPipeline objects.
OptixResult optixLaunch( OptixPipeline pipeline,
CUstream stream,
CUdeviceptr pipelineParams,
size_t pipelineParamsSize,
const OptixShaderBindingTable* sbt,
unsigned int width,
unsigned int height,
unsigned int depth );
/// \param[in] programGroup the program group containing the program(s)
/// \param[out] sbtRecordHeaderHostPointer the result sbt record header
OptixResult optixSbtRecordPackHeader( OptixProgramGroup programGroup, void* sbtRecordHeaderHostPointer );
//@ }
/// \name Acceleration structures
//@ {
/// \param[in] context device context of the pipeline
/// \param[in] accelOptions accel options
/// \param[in] buildInputs an array of OptixBuildInput objects
/// \param[in] numBuildInputs number of elements in buildInputs (must be at least 1)
/// \param[out] bufferSizes fills in buffer sizes
OptixResult optixAccelComputeMemoryUsage( OptixDeviceContext context,
const OptixAccelBuildOptions* accelOptions,
const OptixBuildInput* buildInputs,
unsigned int numBuildInputs,
OptixAccelBufferSizes* bufferSizes );
/// \param[in] context
/// \param[in] stream
/// \param[in] accelOptions accel options
/// \param[in] buildInputs an array of OptixBuildInput objects
/// \param[in] numBuildInputs must be >= 1 for GAS, and == 1 for IAS
/// \param[in] tempBuffer must be a multiple of OPTIX_ACCEL_BUFFER_BYTE_ALIGNMENT
/// \param[in] tempBufferSizeInBytes
/// \param[in] outputBuffer must be a multiple of OPTIX_ACCEL_BUFFER_BYTE_ALIGNMENT
/// \param[in] outputBufferSizeInBytes
/// \param[out] outputHandle
/// \param[out] emittedProperties types of requested properties and output buffers
/// OPTIX_PROPERTY_TYPE_AABBS is currently not supported
/// and must be requested via optixAccelEmitProperties
/// \param[in] numEmittedProperties number of post-build properties to populate (may be zero)
OptixResult optixAccelBuild( OptixDeviceContext context,
CUstream stream,
const OptixAccelBuildOptions* accelOptions,
const OptixBuildInput* buildInputs,
unsigned int numBuildInputs,
CUdeviceptr tempBuffer,
size_t tempBufferSizeInBytes,
CUdeviceptr outputBuffer,
size_t outputBufferSizeInBytes,
OptixTraversableHandle* outputHandle,
const OptixAccelEmitDesc* emittedProperties,
unsigned int numEmittedProperties );
/// Obtain relocation information, stored in OptixAccelRelocationInfo, for a given context
/// and acceleration structure's traversable handle.
///
/// The relocation information can be passed to optixAccelCheckRelocationCompatibility to
/// determine if an acceleration structure, referenced by 'handle', can be relocated to a
/// different device's memory space (see optixAccelCheckRelocationCompatibility).
///
/// When used with optixAccelRelocate, it provides data necessary for doing the relocation.
///
/// If the acceleration structure data associated with 'handle' is copied multiple times,
/// the same OptixAccelRelocationInfo can also be used on all copies.
///
/// \param[in] context
/// \param[in] handle
/// \param[out] info
/// \return OPTIX_ERROR_INVALID_VALUE will be returned for traversable handles that are not from
/// acceleration structure builds.
OptixResult optixAccelGetRelocationInfo( OptixDeviceContext context, OptixTraversableHandle handle, OptixAccelRelocationInfo* info );
/// Checks if an acceleration structure built using another OptixDeviceContext (that was
/// used to fill in 'info') is compatible with the OptixDeviceContext specified in the
/// 'context' parameter.
///
/// Any device is always compatible with itself.
///
/// \param[in] context
/// \param[in] info
/// \param[out] compatible If OPTIX_SUCCESS is returned 'compatible' will have the value of either:
/// - 0: This context is not compatible with acceleration structure data associated with 'info'.
/// - 1: This context is compatible.
OptixResult optixAccelCheckRelocationCompatibility( OptixDeviceContext context, const OptixAccelRelocationInfo* info, int* compatible );
/// optixAccelRelocate is called to update the acceleration structure after it has been
/// relocated. Relocation is necessary when the acceleration structure's location in device
/// memory has changed. optixAccelRelocate does not copy the memory. This function only
/// operates on the relocated memory who's new location is specified by 'targetAccel'.
/// optixAccelRelocate also returns the new OptixTraversableHandle associated with
/// 'targetAccel'. The original memory (source) is not required to be valid, only the
/// OptixAccelRelocationInfo.
///
/// Before copying the data and calling optixAccelRelocate,
/// optixAccelCheckRelocationCompatibility should be called to ensure the copy will be
/// compatible with the destination device context.
///
/// The memory pointed to by 'targetAccel' should be allocated with the same size as the
/// source acceleration. Similar to the 'outputBuffer' used in optixAccelBuild, this
/// pointer must be a multiple of OPTIX_ACCEL_BUFFER_BYTE_ALIGNMENT.
///
/// The memory in 'targetAccel' must be allocated as long as the accel is in use.
///
/// When relocating an accel that contains instances, 'instanceTraversableHandles' and
/// 'numInstanceTraversableHandles' should be supplied. These are the traversable handles
/// of the instances. These can be used when also relocating the instances. No updates to
/// the bounds are performed. Use optixAccelBuild to update the bounds.
/// 'instanceTraversableHandles' and 'numInstanceTraversableHandles' may be zero when
/// relocating bottom level accel (i.e. an accel with no instances).
///
/// \param[in] context
/// \param[in] stream
/// \param[in] info
/// \param[in] instanceTraversableHandles
/// \param[in] numInstanceTraversableHandles
/// \param[in] targetAccel
/// \param[in] targetAccelSizeInBytes
/// \param[out] targetHandle
OptixResult optixAccelRelocate( OptixDeviceContext context,
CUstream stream,
const OptixAccelRelocationInfo* info,
CUdeviceptr instanceTraversableHandles,
size_t numInstanceTraversableHandles,
CUdeviceptr targetAccel,
size_t targetAccelSizeInBytes,
OptixTraversableHandle* targetHandle );
/// After building an acceleration structure, it can be copied in a compacted form to reduce
/// memory. In order to be compacted, OPTIX_BUILD_FLAG_ALLOW_COMPACTION must be supplied in
/// OptixAccelBuildOptions::buildFlags passed to optixAccelBuild.
///
/// 'outputBuffer' is the pointer to where the compacted acceleration structure will be
/// written. This pointer must be a multiple of OPTIX_ACCEL_BUFFER_BYTE_ALIGNMENT.
///
/// The size of the memory specified in 'outputBufferSizeInBytes' should be at least the
/// value computed using the OPTIX_PROPERTY_TYPE_COMPACTED_SIZE that was reported during
/// optixAccelBuild.
///
/// \param[in] context
/// \param[in] stream
/// \param[in] inputHandle
/// \param[in] outputBuffer
/// \param[in] outputBufferSizeInBytes
/// \param[out] outputHandle
OptixResult optixAccelCompact( OptixDeviceContext context,
CUstream stream,
OptixTraversableHandle inputHandle,
CUdeviceptr outputBuffer,
size_t outputBufferSizeInBytes,
OptixTraversableHandle* outputHandle );
/// \param[in] onDevice
/// \param[in] pointer pointer to traversalbe allocated in OptixDeviceContext. This pointer must be a multiple of OPTIX_TRANSFORM_BYTE_ALIGNMENT
/// \param[in] traversableType Type of OptixTraversableHandle to create
/// \param[out] traversableHandle traversable handle. traversableHandle must be in host memory
OptixResult optixConvertPointerToTraversableHandle( OptixDeviceContext onDevice,
CUdeviceptr pointer,
OptixTraversableType traversableType,
OptixTraversableHandle* traversableHandle );
//@ }
/// \name Denoiser
//@ {
/// Creates a denoiser object with the given options.
///
/// \param[in] context
/// \param[in] options
/// \param[out] denoiser
OptixResult optixDenoiserCreate( OptixDeviceContext context, const OptixDenoiserOptions* options, OptixDenoiser* denoiser );
/// Sets the model of the denoiser.
///
/// If the kind is OPTIX_DENOISER_MODEL_KIND_USER, then the data and sizeInByes must not be
/// null and zero respectively. For other kinds, these parameters must be zero.
///
/// \param[in] denoiser
/// \param[in] kind
/// \param[in] data
/// \param[in] sizeInBytes
OptixResult optixDenoiserSetModel( OptixDenoiser denoiser, OptixDenoiserModelKind kind, void* data, size_t sizeInBytes );
/// Destroys the denoiser object and any associated host resources.
OptixResult optixDenoiserDestroy( OptixDenoiser denoiser );
/// Computes the GPU memory resources required to execute the denoiser.
///
/// \param[in] denoiser
/// \param[in] outputWidth
/// \param[in] outputHeight
/// \param[out] returnSizes
OptixResult optixDenoiserComputeMemoryResources( const OptixDenoiser denoiser,
unsigned int outputWidth,
unsigned int outputHeight,
OptixDenoiserSizes* returnSizes );
/// Initializes the state required by the denoiser.
///
/// \param[in] denoiser
/// \param[in] stream
/// \param[in] outputWidth
/// \param[in] outputHeight
/// \param[in] denoiserState
/// \param[in] denoiserStateSizeInBytes
/// \param[in] scratch
/// \param[in] scratchSizeInBytes
OptixResult optixDenoiserSetup( OptixDenoiser denoiser,
CUstream stream,
unsigned int outputWidth,
unsigned int outputHeight,
CUdeviceptr denoiserState,
size_t denoiserStateSizeInBytes,
CUdeviceptr scratch,
size_t scratchSizeInBytes );
/// Invokes denoiser on a set of input data and produces one output
/// image. Scratch memory must be available during the execution of the
/// denoiser.
///
/// \param[in] denoiser
/// \param[in] stream
/// \param[in] params
/// \param[in] denoiserState
/// \param[in] denoiserStateSizeInBytes
/// \param[in] inputLayers
/// \param[in] numInputLayers
/// \param[in] inputOffsetX
/// \param[in] inputOffsetY
/// \param[in] outputLayer
/// \param[in] scratch
/// \param[in] scratchSizeInBytes
OptixResult optixDenoiserInvoke( OptixDenoiser denoiser,
CUstream stream,
const OptixDenoiserParams* params,
CUdeviceptr denoiserState,
size_t denoiserStateSizeInBytes,
const OptixImage2D* inputLayers,
unsigned int numInputLayers,
unsigned int inputOffsetX,
unsigned int inputOffsetY,
const OptixImage2D* outputLayer,
CUdeviceptr scratch,
size_t scratchSizeInBytes );
/// \param[in] denoiser
/// \param[in] stream
/// \param[in] inputImage
/// \param[out] outputIntensity single float
/// \param[in] scratch
/// \param[in] scratchSizeInBytes
OptixResult optixDenoiserComputeIntensity( OptixDenoiser denoiser,
CUstream stream,
const OptixImage2D* inputImage,
CUdeviceptr outputIntensity,
CUdeviceptr scratch,
size_t scratchSizeInBytes );
//@ }
#ifdef __cplusplus
}
#endif
#include "optix_function_table.h"
#endif // __optix_optix_7_host_h__
| 52.075038 | 155 | 0.665167 | [
"geometry",
"object",
"model",
"transform"
] |
3236ba50bf11b1c5bb2ceca8c146435908580cb6 | 1,139 | h | C | GLTF/include/GLTFAnimation.h | cnheider/COLLADA2GLTF | 73caf2f3b17457403ddddcb8623bc26d75ef4f91 | [
"MIT"
] | 1 | 2019-11-11T16:55:37.000Z | 2019-11-11T16:55:37.000Z | GLTF/include/GLTFAnimation.h | cnheider/COLLADA2GLTF | 73caf2f3b17457403ddddcb8623bc26d75ef4f91 | [
"MIT"
] | 1 | 2019-10-22T03:38:04.000Z | 2019-10-22T03:38:04.000Z | GLTF/include/GLTFAnimation.h | cnheider/COLLADA2GLTF | 73caf2f3b17457403ddddcb8623bc26d75ef4f91 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <string>
#include <vector>
#include "GLTFAccessor.h"
#include "GLTFNode.h"
#include "GLTFObject.h"
namespace GLTF {
class Animation : public GLTF::Object {
public:
enum class Path {
TRANSLATION,
ROTATION,
SCALE,
WEIGHTS
};
class Sampler : public GLTF::Object {
public:
GLTF::Accessor* input;
std::string interpolation = "LINEAR";
GLTF::Accessor* output;
std::string inputString;
std::string outputString;
Path path;
virtual std::string typeName();
virtual void writeJSON(void* writer, GLTF::Options* options);
};
class Channel : public GLTF::Object {
public:
~Channel();
class Target : public GLTF::Object {
public:
GLTF::Node* node;
Path path;
virtual void writeJSON(void* writer, GLTF::Options* options);
};
GLTF::Animation::Sampler* sampler = nullptr;
Target* target = nullptr;
virtual void writeJSON(void* writer, GLTF::Options* options);
};
~Animation();
std::vector<Channel*> channels;
virtual std::string typeName();
virtual void writeJSON(void* writer, GLTF::Options* options);
};
}
| 18.983333 | 64 | 0.666374 | [
"object",
"vector"
] |
3236c824eb9a7ce94192f3b3402365ef3aa5f91c | 578 | h | C | BMR/proto_utils.h | fqliao/MP-SPDZ | 070fca5c52ee225fe681f16f150f5fb1a7b4b3ca | [
"BSD-2-Clause"
] | 429 | 2019-06-13T14:11:24.000Z | 2022-03-30T18:54:31.000Z | BMR/proto_utils.h | fqliao/MP-SPDZ | 070fca5c52ee225fe681f16f150f5fb1a7b4b3ca | [
"BSD-2-Clause"
] | 471 | 2019-06-13T09:28:49.000Z | 2022-03-31T17:46:03.000Z | BMR/proto_utils.h | fqliao/MP-SPDZ | 070fca5c52ee225fe681f16f150f5fb1a7b4b3ca | [
"BSD-2-Clause"
] | 162 | 2019-08-07T09:22:11.000Z | 2022-03-31T11:24:26.000Z | /*
* utils.h
*
*/
#ifndef PROTO_UTILS_H_
#define PROTO_UTILS_H_
#include "msg_types.h"
#include <time.h>
#include <sys/time.h>
#include <vector>
#include <iostream>
using namespace std;
#include "Tools/avx_memcpy.h"
#include "Tools/FlexBuffer.h"
#define LOOPBACK_STR "LOOPBACK"
class SendBuffer;
void fill_message_type(void* buffer, MSG_TYPE type);
void fill_message_type(SendBuffer& buffer, MSG_TYPE type);
void phex (const void *addr, int len);
inline void phex(const FlexBuffer& buffer) { phex(buffer.data(), buffer.size()); }
#endif /* NETWORK_TEST_UTILS_H_ */
| 18.0625 | 82 | 0.737024 | [
"vector"
] |
323a32568c46848d4df7dd1215be10f762f224bd | 2,024 | h | C | CubeEngine/EngineSrc/Rendering/RenderCommand.h | tangziwen/Cube-Engine | c79b878dcc7e2e382f4463ca63519627d6220afd | [
"MIT"
] | 360 | 2015-01-26T08:15:01.000Z | 2021-07-11T16:30:58.000Z | CubeEngine/EngineSrc/Rendering/RenderCommand.h | tangziwen/Cube-Engine | c79b878dcc7e2e382f4463ca63519627d6220afd | [
"MIT"
] | 6 | 2015-03-09T09:15:07.000Z | 2020-07-06T01:34:00.000Z | CubeEngine/EngineSrc/Rendering/RenderCommand.h | tangziwen/CubeMiniGame | 90bffa66d4beba5fddc39fc642a8fb36703cf32d | [
"MIT"
] | 41 | 2015-03-10T03:17:46.000Z | 2021-07-13T06:26:26.000Z | #ifndef TZW_RENDERCOMMAND_H
#define TZW_RENDERCOMMAND_H
#include "../Interface/DepthPolicy.h"
#include "../Math/Matrix44.h"
#include "Mesh/InstanceData.h"
#include <vector>
namespace tzw {
class Mesh;
class Material;
class InstancedMesh;
struct InstanceRendereData
{
InstanceData data;
Material * material;
Mesh * m_mesh;
};
struct TransformationInfo{
Matrix44 m_worldMatrix;
Matrix44 m_viewMatrix;
Matrix44 m_projectMatrix;
std::vector<vec3> m_instancedOffset;
};
class RenderCommand
{
friend class Renderer;
public:
enum class PrimitiveType
{
Lines,
TRIANGLES,
TRIANGLE_STRIP,
PATCHES,
};
enum class RenderBatchType
{
Single,
Instanced,
};
RenderCommand(Mesh * mesh,Material * material, void * obj, RenderFlag::RenderStage renderStage, PrimitiveType primitiveType = PrimitiveType::TRIANGLES, RenderBatchType batchType = RenderBatchType::Single);
void render();
RenderBatchType batchType() const;
void setBatchType(const RenderBatchType &type);
unsigned int Zorder() const;
void setZorder(unsigned int Zorder);
PrimitiveType primitiveType() const;
void setPrimitiveType(const PrimitiveType &primitiveType);
DepthPolicy depthTestPolicy() const;
void setDepthTestPolicy(const DepthPolicy &depthTestPolicy);
TransformationInfo m_transInfo;
RenderFlag::RenderStage getRenderState() const;
void setRenderState(const RenderFlag::RenderStage renderState);
RenderBatchType m_batchType;
InstancedMesh* getInstancedMesh() const;
void setInstancedMesh(InstancedMesh* const instancedMesh);
Material * getMat();
void setMat(Material * newMat);
Mesh * getMesh();
void * getDrawableObj();
private:
void *m_obj;
RenderFlag::RenderStage m_renderState;
Mesh * m_mesh;
InstancedMesh * m_instancedMesh;
Material *m_material;
PrimitiveType m_primitiveType;
unsigned int m_Zorder;
DepthPolicy m_depthTestPolicy;
};
} // namespace tzw
#endif // TZW_RENDERCOMMAND_H
| 25.948718 | 209 | 0.73913 | [
"mesh",
"render",
"vector"
] |
323b68fbe2afc2d1e30c3eb26fe7331f323879b9 | 4,263 | h | C | src/engine/systems/mono_behaviour_system.h | hvonck/lambda-lilac | c4cf744356c2d2056e8f66da4f95d2268f7c25d0 | [
"BSD-3-Clause"
] | 1 | 2019-05-28T16:39:19.000Z | 2019-05-28T16:39:19.000Z | src/engine/systems/mono_behaviour_system.h | hvonck/lambda-lilac | c4cf744356c2d2056e8f66da4f95d2268f7c25d0 | [
"BSD-3-Clause"
] | null | null | null | src/engine/systems/mono_behaviour_system.h | hvonck/lambda-lilac | c4cf744356c2d2056e8f66da4f95d2268f7c25d0 | [
"BSD-3-Clause"
] | 1 | 2019-05-28T16:39:06.000Z | 2019-05-28T16:39:06.000Z | #pragma once
#include "interfaces/isystem.h"
#include "interfaces/icomponent.h"
#include <containers/containers.h>
#include <memory/memory.h>
#include <glm/glm.hpp>
namespace lambda
{
namespace scene
{
struct Scene;
}
namespace components
{
class MonoBehaviourComponent : public IComponent
{
public:
MonoBehaviourComponent(const entity::Entity& entity, scene::Scene& scene);
MonoBehaviourComponent(const MonoBehaviourComponent& other);
MonoBehaviourComponent();
private:
scene::Scene* scene_;
};
namespace MonoBehaviourSystem
{
struct Data
{
Data() {}
Data(const entity::Entity& entity) : entity(entity) {};
Data(const Data& other);
Data& operator=(const Data& other);
void* object = nullptr;
void* initialize = nullptr;
void* deinitialize = nullptr;
void* update = nullptr;
void* fixed_update = nullptr;
void* on_collision_enter = nullptr;
void* on_collision_exit = nullptr;
void* on_trigger_enter = nullptr;
void* on_trigger_exit = nullptr;
bool valid = true;
entity::Entity entity;
};
struct SystemData
{
Vector<Data> data;
Map<entity::Entity, uint32_t> entity_to_data;
Map<uint32_t, entity::Entity> data_to_entity;
Set<entity::Entity> marked_for_delete;
Queue<uint32_t> unused_data_entries;
Data& add(const entity::Entity& entity);
Data& get(const entity::Entity& entity);
void remove(const entity::Entity& entity);
bool has(const entity::Entity& entity);
};
MonoBehaviourComponent addComponent(const entity::Entity& entity, scene::Scene& scene);
MonoBehaviourComponent getComponent(const entity::Entity& entity, scene::Scene& scene);
bool hasComponent(const entity::Entity& entity, scene::Scene& scene);
void removeComponent(const entity::Entity& entity, scene::Scene& scene);
void deinitialize(scene::Scene& scene);
void collectGarbage(scene::Scene& scene);
void update(const float& delta_time, scene::Scene& scene);
void fixedUpdate(const float& delta_time, scene::Scene& scene);
void setObject(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setInitialize(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setDeinitialize(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setUpdate(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setFixedUpdate(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setOnCollisionEnter(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setOnCollisionExit(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setOnTriggerEnter(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void setOnTriggerExit(const entity::Entity& entity, void* ptr, scene::Scene& scene);
void* getObject(const entity::Entity& entity, scene::Scene& scene);
void* getInitialize(const entity::Entity& entity, scene::Scene& scene);
void* getDeinitialize(const entity::Entity& entity, scene::Scene& scene);
void* getUpdate(const entity::Entity& entity, scene::Scene& scene);
void* getFixedUpdate(const entity::Entity& entity, scene::Scene& scene);
void* getOnCollisionEnter(const entity::Entity& entity, scene::Scene& scene);
void* getOnCollisionExit(const entity::Entity& entity, scene::Scene& scene);
void* getOnTriggerEnter(const entity::Entity& entity, scene::Scene& scene);
void* getOnTriggerExit(const entity::Entity& entity, scene::Scene& scene);
void onCollisionEnter(const entity::Entity& lhs, const entity::Entity& rhs, glm::vec3 normal, scene::Scene& scene);
void onCollisionExit(const entity::Entity& lhs, const entity::Entity& rhs, glm::vec3 normal, scene::Scene& scene);
void onTriggerEnter(const entity::Entity& lhs, const entity::Entity& rhs, glm::vec3 normal, scene::Scene& scene);
void onTriggerExit(const entity::Entity& lhs, const entity::Entity& rhs, glm::vec3 normal, scene::Scene& scene);
const MonoBehaviourSystem::Data* getClosest(entity::Entity entity, scene::Scene& scene);
}
}
}
| 39.472222 | 119 | 0.694816 | [
"object",
"vector"
] |
323b7e063a0650d47f4ef1558eacc9ec3ba05a13 | 55,840 | h | C | libRF24/src/main/cpp/RF24Network/RF24Network.h | mwinters-stuff/Android-Things-RF24 | 8643bf93aa6532c6afdca3e8afb0066a3bbb8d57 | [
"Apache-2.0"
] | 4 | 2020-05-12T03:01:44.000Z | 2021-08-19T07:49:18.000Z | libRF24/src/main/cpp/RF24Network/RF24Network.h | mwinters-stuff/Android-Things-RF24 | 8643bf93aa6532c6afdca3e8afb0066a3bbb8d57 | [
"Apache-2.0"
] | null | null | null | libRF24/src/main/cpp/RF24Network/RF24Network.h | mwinters-stuff/Android-Things-RF24 | 8643bf93aa6532c6afdca3e8afb0066a3bbb8d57 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2011 James Coliz, Jr. <maniacbug@ymail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
#ifndef __RF24NETWORK_H__
#define __RF24NETWORK_H__
/**
* @file RF24Network.h
*
* Class declaration for RF24Network
*/
#include <stddef.h>
#include <stdint.h>
#include "RF24Network_config.h"
#if (defined (__linux) || defined (linux)) && !defined (__ARDUINO_X86__)
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/time.h>
#include <stddef.h>
#include <assert.h>
#include <map>
#include <utility> // std::pair
#include <queue>
//ATXMega
#elif defined(XMEGA_D3)
#include "../../rf24lib/rf24lib/RF24.h"
#endif
/**
*/
/* Header types range */
#define MIN_USER_DEFINED_HEADER_TYPE 0
#define MAX_USER_DEFINED_HEADER_TYPE 127
/**
*/
// ACK Response Types
/**
* **Reserved network message types**
*
* The network will determine whether to automatically acknowledge payloads based on their general type <br>
*
* **User types** (1-127) 1-64 will NOT be acknowledged <br>
* **System types** (128-255) 192 through 255 will NOT be acknowledged<br>
*
* @defgroup DEFINED_TYPES Reserved System Message Types
*
* System types can also contain message data.
*
* @{
*/
/**
* A NETWORK_ADDR_RESPONSE type is utilized to manually route custom messages containing a single RF24Network address
*
* Used by RF24Mesh
*
* If a node receives a message of this type that is directly addressed to it, it will read the included message, and forward the payload
* on to the proper recipient. <br>
* This allows nodes to forward multicast messages to the master node, receive a response, and forward it back to the requester.
*/
#define NETWORK_ADDR_RESPONSE 128
//#define NETWORK_ADDR_CONFIRM 129
/**
* Messages of type NETWORK_PING will be dropped automatically by the recipient. A NETWORK_ACK or automatic radio-ack will indicate to the sender whether the
* payload was successful. The time it takes to successfully send a NETWORK_PING is the round-trip-time.
*/
#define NETWORK_PING 130
/**
* External data types are used to define messages that will be passed to an external data system. This allows RF24Network to route and pass any type of data, such
* as TCP/IP frames, while still being able to utilize standard RF24Network messages etc.
*
* **Linux**
* Linux devices (defined RF24_LINUX) will buffer all data types in the user cache.
*
* **Arduino/AVR/Etc:** Data transmitted with the type set to EXTERNAL_DATA_TYPE will not be loaded into the user cache. <br>
* External systems can extract external data using the following process, while internal data types are cached in the user buffer, and accessed using network.read() :
* @code
* uint8_t return_type = network.update();
* if(return_type == EXTERNAL_DATA_TYPE){
* uint16_t size = network.frag_ptr->message_size;
* memcpy(&myDataBuffer,network.frag_ptr->message_buffer,network.frag_ptr->message_size);
* }
* @endcode
*/
#define EXTERNAL_DATA_TYPE 131
/**
* Messages of this type designate the first of two or more message fragments, and will be re-assembled automatically.
*/
#define NETWORK_FIRST_FRAGMENT 148
/**
* Messages of this type indicate a fragmented payload with two or more message fragments.
*/
#define NETWORK_MORE_FRAGMENTS 149
/**
* Messages of this type indicate the last fragment in a sequence of message fragments.
* Messages of this type do not receive a NETWORK_ACK
*/
#define NETWORK_LAST_FRAGMENT 150
//#define NETWORK_LAST_FRAGMENT 201
// NO ACK Response Types
//#define NETWORK_ACK_REQUEST 192
/**
* Messages of this type are used internally, to signal the sender that a transmission has been completed.
* RF24Network does not directly have a built-in transport layer protocol, so message delivery is not 100% guaranteed.<br>
* Messages can be lost via corrupted dynamic payloads, or a NETWORK_ACK can fail, while the message was actually successful.
*
* NETWORK_ACK messages can be utilized as a traffic/flow control mechanism, since transmitting nodes will be forced to wait until
* the payload is transmitted across the network and acknowledged, before sending additional data.
*
* In the event that the transmitting device will be waiting for a direct response, manually sent by the recipient, a NETWORK_ACK is not required. <br>
* User messages utilizing a 'type' with a decimal value of 64 or less will not be acknowledged across the network via NETWORK_ACK messages.
*/
#define NETWORK_ACK 193
/**
* Used by RF24Mesh
*
* Messages of this type are used with multi-casting , to find active/available nodes.
* Any node receiving a NETWORK_POLL sent to a multicast address will respond directly to the sender with a blank message, indicating the
* address of the available node via the header.
*/
#define NETWORK_POLL 194
/**
* Used by RF24Mesh
*
* Messages of this type are used to request information from the master node, generally via a unicast (direct) write.
* Any (non-master) node receiving a message of this type will manually forward it to the master node using an normal network write.
*/
#define NETWORK_REQ_ADDRESS 195
//#define NETWORK_ADDR_LOOKUP 196
//#define NETWORK_ADDR_RELEASE 197
/** @} */
#define NETWORK_MORE_FRAGMENTS_NACK 200
/** Internal defines for handling written payloads */
#define TX_NORMAL 0
#define TX_ROUTED 1
#define USER_TX_TO_PHYSICAL_ADDRESS 2 //no network ACK
#define USER_TX_TO_LOGICAL_ADDRESS 3 // network ACK
#define USER_TX_MULTICAST 4
#define MAX_FRAME_SIZE 32 //Size of individual radio frames
#define FRAME_HEADER_SIZE 10 //Size of RF24Network frames - data
#define USE_CURRENT_CHANNEL 255 // Use current radio channel when setting up the network
/** Internal defines for handling internal payloads - prevents reading additional data from the radio
* when buffers are full */
#define FLAG_HOLD_INCOMING 1
/** FLAG_BYPASS_HOLDS is mainly for use with RF24Mesh as follows:
* a: Ensure no data in radio buffers, else exit
* b: Address is changed to multicast address for renewal
* c: Holds Cleared (bypass flag is set)
* d: Address renewal takes place and is set
* e: Holds Enabled (bypass flag off)
*/
#define FLAG_BYPASS_HOLDS 2
#define FLAG_FAST_FRAG 4
#define FLAG_NO_POLL 8
class RF24;
/**
* Header which is sent with each message
*
* The frame put over the air consists of this header and a message
*
* Headers are addressed to the appropriate node, and the network forwards them on to their final destination.
*/
struct RF24NetworkHeader
{
uint16_t from_node; /**< Logical address where the message was generated */
uint16_t to_node; /**< Logical address where the message is going */
uint16_t id; /**< Sequential message ID, incremented every time a new frame is constructed */
/**
* Message Types:
* User message types 1 through 64 will NOT be acknowledged by the network, while message types 65 through 127 will receive a network ACK.
* System message types 192 through 255 will NOT be acknowledged by the network. Message types 128 through 192 will receive a network ACK. <br>
* <br><br>
*/
unsigned char type; /**< <b>Type of the packet. </b> 0-127 are user-defined types, 128-255 are reserved for system */
/**
* During fragmentation, it carries the fragment_id, and on the last fragment
* it carries the header_type.<br>
*/
unsigned char reserved; /**< *Reserved for system use* */
static uint16_t next_id; /**< The message ID of the next message to be sent (unused)*/
/**
* Default constructor
*
* Simply constructs a blank header
*/
RF24NetworkHeader() {}
/**
* Send constructor
*
* @note Now supports automatic fragmentation for very long messages, which can be sent as usual if fragmentation is enabled.
*
* Fragmentation is enabled by default for all devices except ATTiny <br>
* Configure fragmentation and max payload size in RF24Network_config.h
*
* Use this constructor to create a header and then send a message
*
* @code
* uint16_t recipient_address = 011;
*
* RF24NetworkHeader header(recipient_address,'t');
*
* network.write(header,&message,sizeof(message));
* @endcode
*
* @param _to The Octal format, logical node address where the message is going
* @param _type The type of message which follows. Only 0-127 are allowed for
* user messages. Types 1-64 will not receive a network acknowledgement.
*/
RF24NetworkHeader(uint16_t _to, unsigned char _type = 0): to_node(_to), id(next_id++), type(_type) {}
/**
* Create debugging string
*
* Useful for debugging. Dumps all members into a single string, using
* internal static memory. This memory will get overridden next time
* you call the method.
*
* @return String representation of this object
*/
const char* toString(void) const;
};
/**
* Frame structure for internal message handling, and for use by external applications
*
* The actual frame put over the air consists of a header (8-bytes) and a message payload (Up to 24-bytes)<br>
* When data is received, it is stored using the RF24NetworkFrame structure, which includes:
* 1. The header
* 2. The size of the included message
* 3. The 'message' or data being received
*
*
*/
struct RF24NetworkFrame
{
RF24NetworkHeader header; /**< Header which is sent with each message */
uint16_t message_size; /**< The size in bytes of the payload length */
/**
* On Arduino, the message buffer is just a pointer, and can be pointed to any memory location.
* On Linux the message buffer is a standard byte array, equal in size to the defined MAX_PAYLOAD_SIZE
*/
#if defined (RF24_LINUX)
uint8_t message_buffer[MAX_PAYLOAD_SIZE]; //< Array to store the message
#else
uint8_t *message_buffer; //< Pointer to the buffer storing the actual message
#endif
/**
* Default constructor
*
* Simply constructs a blank frame. Frames are generally used internally. See RF24NetworkHeader.
*/
//RF24NetworkFrame() {}
RF24NetworkFrame() {}
/**
* Constructor - create a network frame with data
* Frames are constructed and handled differently on Arduino/AVR and Linux devices (defined RF24_LINUX)
*
* <br>
* **Linux:**
* @param _header The RF24Network header to be stored in the frame
* @param _message The 'message' or data.
* @param _len The size of the 'message' or data.
*
* <br>
* **Arduino/AVR/Etc.**
* @see RF24Network.frag_ptr
* @param _header The RF24Network header to be stored in the frame
* @param _message_size The size of the 'message' or data
*
*
* Frames are used internally and by external systems. See RF24NetworkHeader.
*/
#if defined (RF24_LINUX)
RF24NetworkFrame(RF24NetworkHeader& _header, const void* _message = NULL, uint16_t _len = 0) :
header(_header), message_size(_len) {
if (_message && _len) {
memcpy(message_buffer,_message,_len);
}
}
#else
RF24NetworkFrame(RF24NetworkHeader &_header, uint16_t _message_size):
header(_header), message_size(_message_size){
}
#endif
/**
* Create debugging string
*
* Useful for debugging. Dumps all members into a single string, using
* internal static memory. This memory will get overridden next time
* you call the method.
*
* @return String representation of this object
*/
const char* toString(void) const;
};
/**
* 2014-2015 - Optimized Network Layer for RF24 Radios
*
* This class implements an OSI Network Layer using nRF24L01(+) radios driven
* by RF24 library.
*/
class RF24Network
{
/**@}*/
/**
* @name Primary Interface
*
* These are the main methods you need to operate the network
*/
/**@{*/
public:
/**
* Construct the network
*
* @param _radio The underlying radio driver instance
*
*/
RF24Network( RF24& _radio );
/**
* Bring up the network using the current radio frequency/channel.
* Calling begin brings up the network, and configures the address, which designates the location of the node within RF24Network topology.
* @note Node addresses are specified in Octal format, see <a href=Addressing.html>RF24Network Addressing</a> for more information.
* @warning Be sure to 'begin' the radio first.
*
* **Example 1:** Begin on current radio channel with address 0 (master node)
* @code
* network.begin(00);
* @endcode
* **Example 2:** Begin with address 01 (child of master)
* @code
* network.begin(01);
* @endcode
* **Example 3:** Begin with address 011 (child of 01, grandchild of master)
* @code
* network.begin(011);
* @endcode
*
* @see begin(uint8_t _channel, uint16_t _node_address )
* @param _node_address The logical address of this node
*
*/
inline void begin(uint16_t _node_address){
begin(USE_CURRENT_CHANNEL,_node_address);
}
/**
* Main layer loop
*
* This function must be called regularly to keep the layer going. This is where payloads are
* re-routed, received, and all the action happens.
*
* @see
*
* @return Returns the type of the last received payload.
*/
uint8_t update(void);
/**
* Test whether there is a message available for this node
*
* @return Whether there is a message available for this node
*/
bool available(void);
/**
* Read the next available header
*
* Reads the next available header without advancing to the next
* incoming message. Useful for doing a switch on the message type
*
* If there is no message available, the header is not touched
*
* @param[out] header The header (envelope) of the next message
*/
uint16_t peek(RF24NetworkHeader& header);
/**
* Read a message
*
* @code
* while ( network.available() ) {
* RF24NetworkHeader header;
* uint32_t time;
* network.peek(header);
* if(header.type == 'T'){
* network.read(header,&time,sizeof(time));
* Serial.print("Got time: ");
* Serial.println(time);
* }
* }
* @endcode
* @param[out] header The header (envelope) of this message
* @param[out] message Pointer to memory where the message should be placed
* @param maxlen The largest message size which can be held in @p message
* @return The total number of bytes copied into @p message
*/
uint16_t read(RF24NetworkHeader& header, void* message, uint16_t maxlen);
/**
* Send a message
*
* @note RF24Network now supports fragmentation for very long messages, send as normal. Fragmentation
* may need to be enabled or configured by editing the RF24Network_config.h file. Default max payload size is 120 bytes.
*
* @code
* uint32_t time = millis();
* uint16_t to = 00; // Send to master
* RF24NetworkHeader header(to, 'T'); // Send header type 'T'
* network.write(header,&time,sizeof(time));
* @endcode
* @param[in,out] header The header (envelope) of this message. The critical
* thing to fill in is the @p to_node field so we know where to send the
* message. It is then updated with the details of the actual header sent.
* @param message Pointer to memory where the message is located
* @param len The size of the message
* @return Whether the message was successfully received
*/
bool write(RF24NetworkHeader& header,const void* message, uint16_t len);
/**@}*/
/**
* @name Advanced Configuration
*
* For advanced configuration of the network
*/
/**@{*/
/**
* Construct the network in dual head mode using two radio modules.
* @note Not working on RPi. Radios will share MISO, MOSI and SCK pins, but require separate CE,CS pins.
* @code
* RF24 radio(7,8);
* RF24 radio1(4,5);
* RF24Network(radio.radio1);
* @endcode
* @param _radio The underlying radio driver instance
* @param _radio1 The second underlying radio driver instance
*/
RF24Network( RF24& _radio, RF24& _radio1);
/**
* By default, multicast addresses are divided into levels.
*
* Nodes 1-5 share a multicast address, nodes n1-n5 share a multicast address, and nodes n11-n55 share a multicast address.<br>
*
* This option is used to override the defaults, and create custom multicast groups that all share a single
* address. <br>
* The level should be specified in decimal format 1-6 <br>
* @see multicastRelay
* @param level Levels 1 to 6 are available. All nodes at the same level will receive the same
* messages if in range. Messages will be routed in order of level, low to high by default, with the
* master node (00) at multicast Level 0
*/
void multicastLevel(uint8_t level);
/**
* Enabling this will allow this node to automatically forward received multicast frames to the next highest
* multicast level. Duplicate frames are filtered out, so multiple forwarding nodes at the same level should
* not interfere. Forwarded payloads will also be received.
* @see multicastLevel
*/
bool multicastRelay;
/**
* Set up the watchdog timer for sleep mode using the number 0 through 10 to represent the following time periods:<br>
* wdt_16ms = 0, wdt_32ms, wdt_64ms, wdt_128ms, wdt_250ms, wdt_500ms, wdt_1s, wdt_2s, wdt_4s, wdt_8s
* @code
* setup_watchdog(7); // Sets the WDT to trigger every second
* @endcode
* @param prescalar The WDT prescaler to define how often the node will wake up. When defining sleep mode cycles, this time period is 1 cycle.
*/
void setup_watchdog(uint8_t prescalar);
/**
* @note: This value is automatically assigned based on the node address
* to reduce errors and increase throughput of the network.
*
* Sets the timeout period for individual payloads in milliseconds at staggered intervals.
* Payloads will be retried automatically until success or timeout
* Set to 0 to use the normal auto retry period defined by radio.setRetries()
*
*/
uint32_t txTimeout; /**< Network timeout value */
/**
* This only affects payloads that are routed by one or more nodes.
* This specifies how long to wait for an ack from across the network.
* Radios sending directly to their parent or children nodes do not
* utilize this value.
*/
uint16_t routeTimeout; /**< Timeout for routed payloads */
/**@}*/
/**
* @name Advanced Operation
*
* For advanced operation of the network
*/
/**@{*/
/**
* Return the number of failures and successes for all transmitted payloads, routed or sent directly
* @note This needs to be enabled via #define ENABLE_NETWORK_STATS in RF24Network_config.h
*
* @code
* bool fails, success;
* network.failures(&fails,&success);
* @endcode
*
*/
#ifdef ENABLE_NETWORK_STATS
void failures(uint32_t *_fails, uint32_t *_ok);
#endif
#if defined (RF24NetworkMulticast)
/**
* Send a multicast message to multiple nodes at once
* Allows messages to be rapidly broadcast through the network
*
* Multicasting is arranged in levels, with all nodes on the same level listening to the same address
* Levels are assigned by network level ie: nodes 01-05: Level 1, nodes 011-055: Level 2
* @see multicastLevel
* @see multicastRelay
* @param message Pointer to memory where the message is located
* @param len The size of the message
* @param level Multicast level to broadcast to
* @return Whether the message was successfully sent
*/
bool multicast(RF24NetworkHeader& header,const void* message, uint16_t len, uint8_t level);
#endif
/**
* Writes a direct (unicast) payload. This allows routing or sending messages outside of the usual routing paths.
* The same as write, but a physical address is specified as the last option.
* The payload will be written to the physical address, and routed as necessary by the recipient
*/
bool write(RF24NetworkHeader& header,const void* message, uint16_t len, uint16_t writeDirect);
/**
* Sleep this node - For AVR devices only
* @note NEW - Nodes can now be slept while the radio is not actively transmitting. This must be manually enabled by uncommenting
* the #define ENABLE_SLEEP_MODE in RF24Network_config.h
* @note Setting the interruptPin to 255 will disable interrupt wake-ups
* @note The watchdog timer should be configured in setup() if using sleep mode.
* This function will sleep the node, with the radio still active in receive mode.
*
* The node can be awoken in two ways, both of which can be enabled simultaneously:
* 1. An interrupt - usually triggered by the radio receiving a payload. Must use pin 2 (interrupt 0) or 3 (interrupt 1) on Uno, Nano, etc.
* 2. The watchdog timer waking the MCU after a designated period of time, can also be used instead of delays to control transmission intervals.
* @code
* if(!network.available()){ network.sleepNode(1,0); } //Sleeps the node for 1 second or a payload is received
*
* Other options:
* network.sleepNode(0,0); // Sleep this node for the designated time period, or a payload is received.
* network.sleepNode(1,255); // Sleep this node for 1 cycle. Do not wake up until then, even if a payload is received ( no interrupt )
* @endcode
* @see setup_watchdog()
* @param cycles: The node will sleep in cycles of 1s. Using 2 will sleep 2 WDT cycles, 3 sleeps 3WDT cycles...
* @param interruptPin: The interrupt number to use (0,1) for pins two and three on Uno,Nano. More available on Mega etc.
* @return True if sleepNode completed normally, after the specified number of cycles. False if sleep was interrupted
*/
#ifndef RF24_LINUX
bool sleepNode( unsigned int cycles, int interruptPin, uint8_t INTERRUPT_MODE=0); //added interrupt mode support (default 0=LOW)
#endif
/**
* This node's parent address
*
* @return This node's parent address, or -1 if this is the base
*/
uint16_t parent() const;
/**
* Provided a node address and a pipe number, will return the RF24Network address of that child pipe for that node
*/
uint16_t addressOfPipe( uint16_t node,uint8_t pipeNo );
/**
* @note Addresses are specified in octal: 011, 034
* @return True if a supplied address is valid
*/
bool is_valid_address( uint16_t node );
/**@}*/
/**
* @name Deprecated
*
* Maintained for backwards compatibility
*/
/**@{*/
/**
* Bring up the network on a specific radio frequency/channel.
* @note Use radio.setChannel() to configure the radio channel
*
* **Example 1:** Begin on channel 90 with address 0 (master node)
* @code
* network.begin(90,0);
* @endcode
* **Example 2:** Begin on channel 90 with address 01 (child of master)
* @code
* network.begin(90,01);
* @endcode
* **Example 3:** Begin on channel 90 with address 011 (child of 01, grandchild of master)
* @code
* network.begin(90,011);
* @endcode
*
* @param _channel The RF channel to operate on
* @param _node_address The logical address of this node
*
*/
void begin(uint8_t _channel, uint16_t _node_address );
/**@}*/
/**
* @name External Applications/Systems
*
* Interface for External Applications and Systems ( RF24Mesh, RF24Ethernet )
*/
/**@{*/
/** The raw system frame buffer of received data. */
uint8_t frame_buffer[MAX_FRAME_SIZE];
/**
* **Linux** <br>
* Data with a header type of EXTERNAL_DATA_TYPE will be loaded into a separate queue.
* The data can be accessed as follows:
* @code
* RF24NetworkFrame f;
* while(network.external_queue.size() > 0){
* f = network.external_queue.front();
* uint16_t dataSize = f.message_size;
* //read the frame message buffer
* memcpy(&myBuffer,&f.message_buffer,dataSize);
* network.external_queue.pop();
* }
* @endcode
*/
#if defined (RF24_LINUX)
std::queue<RF24NetworkFrame> external_queue;
#endif
#if !defined ( DISABLE_FRAGMENTATION ) && !defined (RF24_LINUX)
/**
* **ARDUINO** <br>
* The frag_ptr is only used with Arduino (not RPi/Linux) and is mainly used for external data systems like RF24Ethernet. When
* an EXTERNAL_DATA payload type is received, and returned from network.update(), the frag_ptr will always point to the starting
* memory location of the received frame. <br>This is used by external data systems (RF24Ethernet) to immediately copy the received
* data to a buffer, without using the user-cache.
*
* @see RF24NetworkFrame
*
* @code
* uint8_t return_type = network.update();
* if(return_type == EXTERNAL_DATA_TYPE){
* uint16_t size = network.frag_ptr->message_size;
* memcpy(&myDataBuffer,network.frag_ptr->message_buffer,network.frag_ptr->message_size);
* }
* @endcode
* Linux devices (defined as RF24_LINUX) currently cache all payload types, and do not utilize frag_ptr.
*/
RF24NetworkFrame* frag_ptr;
#endif
/**
* Variable to determine whether update() will return after the radio buffers have been emptied (DEFAULT), or
* whether to return immediately when (most) system types are received.
*
* As an example, this is used with RF24Mesh to catch and handle system messages without loading them into the user cache.
*
* The following reserved/system message types are handled automatically, and not returned.
*
* | System Message Types <br> (Not Returned) |
* |-----------------------|
* | NETWORK_ADDR_RESPONSE |
* | NETWORK_ACK |
* | NETWORK_PING |
* | NETWORK_POLL <br>(With multicast enabled) |
* | NETWORK_REQ_ADDRESS |
*
*/
bool returnSysMsgs;
/**
* Network Flags allow control of data flow
*
* Incoming Blocking: If the network user-cache is full, lets radio cache fill up. Radio ACKs are not sent when radio internal cache is full.<br>
* This behaviour may seem to result in more failed sends, but the payloads would have otherwise been dropped due to the cache being full.<br>
*
* | FLAGS | Value | Description |
* |-------|-------|-------------|
* |FLAG_HOLD_INCOMING| 1(bit_1) | INTERNAL: Set automatically when a fragmented payload will exceed the available cache |
* |FLAG_BYPASS_HOLDS| 2(bit_2) | EXTERNAL: Can be used to prevent holds from blocking. Note: Holds are disabled & re-enabled by RF24Mesh when renewing addresses. This will cause data loss if incoming data exceeds the available cache space|
* |FLAG_FAST_FRAG| 4(bit_3) | INTERNAL: Replaces the fastFragTransfer variable, and allows for faster transfers between directly connected nodes. |
* |FLAG_NO_POLL| 8(bit_4) | EXTERNAL/USER: Disables NETWORK_POLL responses on a node-by-node basis. |
*
*/
uint8_t networkFlags;
private:
uint32_t txTime;
bool write(uint16_t, uint8_t directTo);
bool write_to_pipe( uint16_t node, uint8_t pipe, bool multicast );
uint8_t enqueue(RF24NetworkHeader *header);
bool is_direct_child( uint16_t node );
bool is_descendant( uint16_t node );
uint16_t direct_child_route_to( uint16_t node );
//uint8_t pipe_to_descendant( uint16_t node );
void setup_address(void);
bool _write(RF24NetworkHeader& header,const void* message, uint16_t len, uint16_t writeDirect);
struct logicalToPhysicalStruct{
uint16_t send_node;
uint8_t send_pipe;
bool multicast;
};
bool logicalToPhysicalAddress(logicalToPhysicalStruct *conversionInfo);
RF24& radio; /**< Underlying radio driver, provides link/physical layers */
#if defined (DUAL_HEAD_RADIO)
RF24& radio1;
#endif
#if defined (RF24NetworkMulticast)
uint8_t multicast_level;
#endif
uint16_t node_address; /**< Logical node address of this unit, 1 .. UINT_MAX */
//const static int frame_size = 32; /**< How large is each frame over the air */
uint8_t frame_size;
const static unsigned int max_frame_payload_size = MAX_FRAME_SIZE-sizeof(RF24NetworkHeader);
#if defined (RF24_LINUX)
std::queue<RF24NetworkFrame> frame_queue;
std::map< uint16_t, RF24NetworkFrame> frameFragmentsCache;
bool appendFragmentToFrame(RF24NetworkFrame frame);
#else
#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) || defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
#if !defined (NUM_USER_PAYLOADS)
#define NUM_USER_PAYLOADS 3
#endif
#endif
#if !defined (NUM_USER_PAYLOADS)
#define NUM_USER_PAYLOADS 5
#endif
#if defined (DISABLE_USER_PAYLOADS)
uint8_t frame_queue[1]; /**< Space for a small set of frames that need to be delivered to the app layer */
#else
uint8_t frame_queue[MAIN_BUFFER_SIZE]; /**< Space for a small set of frames that need to be delivered to the app layer */
#endif
uint8_t* next_frame; /**< Pointer into the @p frame_queue where we should place the next received frame */
#if !defined ( DISABLE_FRAGMENTATION )
RF24NetworkFrame frag_queue;
uint8_t frag_queue_message_buffer[MAX_PAYLOAD_SIZE]; //frame size + 1
#endif
#endif
//uint8_t frag_queue[MAX_PAYLOAD_SIZE + 11];
//RF24NetworkFrame frag_queue;
uint16_t parent_node; /**< Our parent's node address */
uint8_t parent_pipe; /**< The pipe our parent uses to listen to us */
uint16_t node_mask; /**< The bits which contain signfificant node address information */
#if defined ENABLE_NETWORK_STATS
static uint32_t nFails;
static uint32_t nOK;
#endif
public:
};
/**
* @example helloworld_tx.ino
*
* Simplest possible example of using RF24Network. Put this sketch
* on one node, and helloworld_rx.pde on the other. Tx will send
* Rx a nice message every 2 seconds which rx will print out for us.
*/
/**
* @example helloworld_rx.ino
*
* Simplest possible example of using RF24Network. Put this sketch
* on one node, and helloworld_tx.pde on the other. Tx will send
* Rx a nice message every 2 seconds which rx will print out for us.
*/
/**
* @example Network_Ping.ino
*
* Example to give users an understanding of addressing and topology in the mesh network
* Using this sketch, each node will send a ping to the base every
* few seconds. The RF24Network library will route the message across
* the mesh to the correct node.
*
*/
/**
* @example Network_Ping_Sleep.ino
*
* Example: This is almost exactly the same as the Network_Ping example, but with use
* of the integrated sleep mode.
*
* This example demonstrates how nodes on the network utilize sleep mode to conserve power. For example,
* the radio itself will draw about 13.5mA in receive mode. In sleep mode, it will use as little as 22ua (.000022mA)
* of power when not actively transmitting or receiving data. In addition, the Arduino is powered down as well,
* dropping network power consumption dramatically compared to previous capabilities. <br>
* Note: Sleeping nodes generate traffic that will wake other nodes up. This may be mitigated with further modifications. Sleep
* payloads are currently always routed to the master node, which will wake up intermediary nodes. Routing nodes can be configured
* to go back to sleep immediately.
* The displayed millis() count will give an indication of how much a node has been sleeping compared to the others, as millis() will
* not increment while a node sleeps.
*<br>
* - Using this sketch, each node will send a ping to every other node in the network every few seconds.<br>
* - The RF24Network library will route the message across the mesh to the correct node.<br>
*
*/
/**
* @example sensornet.pde
*
* Example of a sensor network.
* This sketch demonstrates how to use the RF24Network library to
* manage a set of low-power sensor nodes which mostly sleep but
* awake regularly to send readings to the base.
*/
/**
* @mainpage Network Layer for RF24 Radios
*
* This class implements an <a href="http://en.wikipedia.org/wiki/Network_layer">OSI Network Layer</a> using nRF24L01(+) radios driven
* by the newly optimized <a href="http://tmrh20.github.com/RF24/">RF24</a> library fork.
*
* @section Purpose Purpose/Goal
*
* Original: Create an alternative to ZigBee radios for Arduino communication.
*
* New: Enhance the current functionality for maximum efficiency, reliability, and speed
*
* Xbees are excellent little radios, backed up by a mature and robust standard
* protocol stack. They are also expensive.
*
* For many Arduino uses, they seem like overkill. So I am working to improve the current
* standard for nRF24L01 radios. The best RF24 modules are available for less than
* $6 from many sources. With the RF24Network layer, I hope to cover many
* common communication scenarios.
*
* Please see the @ref Zigbee page for a comparison against the ZigBee protocols
*
* @section Features Features
*
* <b>Whats new? </b><br>
* @li New: (Dec 8) Merge of RPi and Arduino code. Finally moving closer to a stable release. Report issues at https://github.com/TMRh20/RF24Network/issues
* @li New functionality: (Dec 8) Support for fragmented multicast payloads on both RPi and Arduino
* @li New functionality: (Nov 24) Fragmentation & reassembly supported on both RPi and Arduino
* @li Note: structure of network frames is changed, these are only used by external applications like RF24Ethernet and RF24toTUN, and for fragmentation
* @li New functionality: User message types 1 through 64 will not receive a network ack
*
* The layer provides:
* @li <b>New</b> (2014): Network ACKs: Efficient acknowledgement of network-wide transmissions, via dynamic radio acks and network protocol acks.
* @li <b>New</b> (2014): Updated addressing standard for optimal radio transmission.
* @li <b>New</b> (2014): Extended timeouts and staggered timeout intervals. The new txTimeout variable allows fully automated extended timeout periods via auto-retry/auto-reUse of payloads.
* @li <b>New</b> (2014): Optimization to the core library provides improvements to reliability, speed and efficiency. See https://tmrh20.github.io/RF24 for more info.
* @li <b>New</b> (2014): Built in sleep mode using interrupts. (Still under development. (Enable via RF24Network_config.h))
* @li <b>New</b> (2014): Dual headed operation: The use of dual radios for busy routing nodes or the master node enhances throughput and decreases errors. See the <a href="Tuning.html">Tuning</a> section.
* @li Host Addressing. Each node has a logical address on the local network.
* @li Message Forwarding. Messages can be sent from one node to any other, and
* this layer will get them there no matter how many hops it takes.
* @li Ad-hoc Joining. A node can join a network without any changes to any
* existing nodes.
*
* The layer does not provide:
* @li Dynamic address assignment. (See RF24Mesh)
* @li Layer 4 protocols (TCP/IP - See RF24Ethernet and RF24toTUN)
*
* @section More How to learn more
*
* @li <a href="classRF24Network.html">RF24Network Class Documentation</a>
* @li <a href="AdvancedConfig.html"> Advanced Configuration Options</a>
* @li <a href="Addressing.html"> Addressing format</a>
* @li <a href="Tuning.html"> Topology and Overview</a>
* @li <a href="https://github.com/TMRh20/RF24Network/archive/Development.zip">Download Current Development Package</a>
* @li <a href="examples.html">Examples Page</a>. Start with <a href="helloworld_rx_8ino-example.html">helloworld_rx</a> and <a href="helloworld_tx_8ino-example.html">helloworld_tx</a>.
*
* <b> Additional Information & Add-ons </b>
* @li <a href="https://github.com/TMRh20/RF24Mesh">RF24Mesh: Dynamic Mesh Layer for RF24Network Dev</a>
* @li <a href="https://github.com/TMRh20/RF24Ethernet">RF24Ethernet: TCP/IP over RF24Network</a>
* @li <a href="http://tmrh20.blogspot.com/2014/03/high-speed-data-transfers-and-wireless.html">My Blog: RF24 Optimization Overview</a>
* @li <a href="http://tmrh20.blogspot.com/2014/03/arduino-radiointercomwireless-audio.html">My Blog: RF24 Wireless Audio</a>
* @li <a href="http://maniacbug.github.com/RF24/">RF24: Original Author</a>
* @section Topology Topology for Mesh Networks using nRF24L01(+)
*
* This network layer takes advantage of the fundamental capability of the nRF24L01(+) radio to
* listen actively to up to 6 other radios at once. The network is arranged in a
* <a href="http://en.wikipedia.org/wiki/Network_Topology#Tree">Tree Topology</a>, where
* one node is the base, and all other nodes are children either of that node, or of another.
* Unlike a true mesh network, multiple nodes are not connected together, so there is only one
* path to any given node.
*
* @section Octal Octal Addressing and Topology
*
* Each node must be assigned an 15-bit address by the administrator. This address exactly
* describes the position of the node within the tree. The address is an octal number. Each
* digit in the address represents a position in the tree further from the base.
*
* @li Node 00 is the base node.
* @li Nodes 01-05 are nodes whose parent is the base.
* @li Node 021 is the second child of node 01.
* @li Node 0321 is the third child of node 021, an so on.
* @li The largest node address is 05555, so 3,125 nodes are allowed on a single channel.
* An example topology is shown below, with 5 nodes in direct communication with the master node,
* and multiple leaf nodes spread out at a distance, using intermediate nodes to reach other nodes.
*
*| | | 00 | | | 00 | | | | Master Node (00) |
*|---|----|----|----|----|----|----|----|----|-----------------------------------------------------|
*| | | 01 | | | 04 | | | | 1st level children of master (00) |
*| | 011| | 021| | |014 | | | 2nd level children of master. Children of 1st level.|
*|111| | | 121| 221| | | 114| | 3rd level children of master. Children of 2nd level.|
*| | | | |1221| |1114|2114|3114| 4th level children of master. Children of 3rd level.|
*
* @section Routing How routing is handled
*
* When sending a message using RF24Network::write(), you fill in the header with the logical
* node address. The network layer figures out the right path to find that node, and sends
* it through the system until it gets to the right place. This works even if the two nodes
* are far separated, as it will send the message down to the base node, and then back out
* to the final destination.
*
* All of this work is handled by the RF24Network::update() method, so be sure to call it
* regularly or your network will miss packets.
*
* @section Startup Starting up a node
*
* When a node starts up, it only has to contact its parent to establish communication.
* No direct connection to the Base node is needed. This is useful in situations where
* relay nodes are being used to bridge the distance to the base, so leaf nodes are out
* of range of the base.
*
* @section Directionality Directionality
*
* By default all nodes are always listening, so messages will quickly reach
* their destination.
*
* You may choose to sleep any nodes on the network if using interrupts. This is useful in a
* case where the nodes are operating on batteries and need to sleep. This greatly decreases
* the power requirements for a sensor network. The leaf nodes can sleep most of the time,
* and wake every few minutes to send in a reading. Routing nodes can be triggered to wake up
* whenever a payload is received See sleepNode() in the class documentation, and RFNetwork_config.h
* to enable sleep mode.
*
*
* @page Addressing Addressing Format: Understanding Addressing and Topology
* An overview of addressing in RF24Network
*
* @section Overview Overview
* The nrf24 radio modules typically use a 40-bit address format, requiring 5-bytes of storage space per address, and allowing a wide
* array of addresses to be utilized. In addition, the radios are limited to direct communication with 6 other nodes while using the
* Enhanced-Shock-Burst (ESB) functionality of the radios.
*
* RF24Network uses a simple method of data compression to store the addresses using only 2 bytes, in a format designed to represent the
* network topology in an intuitive way.
* See the <a href="Tuning.html"> Topology and Overview</a> page for more info regarding topology.
*
* @section Octal_Binary Decimal, Octal and Binary formats
*
* Say we want to designate a logical address to a node, using a tree topology as defined by the manufacturer.
* In the simplest format, we could assign the first node the address of 1, the second 2 and so on.
* Since a single node can only connect to 6 other nodes (1 parent and 5 children) subnets need to be created if using more than 6 nodes.<br>
* In this case the children of node 1 could simply be designated as 11,21,31,41, and 51<br>
* Children of node 2 could be designated as 12,22,32,42, and 52
*
* The above example is exactly how RF24Network manages the addresses, but they are represented in Octal format.
*
* <b>Decimal, Octal and Binary</b>
* <table>
* <tr bgcolor="#a3b4d7" >
* <td> Decimal </td> <td> Binary </td><td> Decimal </td> <td> Binary </td><td> Decimal </td> <td> Binary </td>
* </tr><tr>
* <td> 1 </td> <td> 00000001 </td><td> 11 </td> <td> 00001011 </td><td> 111 </td> <td> 01101111 </td>
* </tr><tr bgcolor="#a3b4d7" >
* <td> Octal </td> <td> Binary </td><td> Octal </td> <td> Binary </td><td> Octal </td> <td> Binary </td>
* </tr><tr>
* <td> 1 </td> <td> 00000001 </td><td> 011 </td> <td> 00001001 </td><td> 0111 </td> <td> 1001001 </td>
* </tr>
* </table>
*
*
* Since the numbers 0-7 can be represented in exactly three bits, each digit is represented by exactly 3 bits when viewed in octal format.
* This allows a very simple method of managing addresses via masking and bit shifting.
*
* @section DisplayAddresses Displaying Addresses
*
* When using Arduino devices, octal addresses can be printed in the following manner:
* @code
* uint16_t address = 0111;
* Serial.println(address,OCT);
* @endcode
*
* Printf can also be used, if enabled, or if using linux/RPi
* @code
* uint16_t address = 0111;
* printf("0%o\n",address);
* @endcode
*
* See http://www.cplusplus.com/doc/hex/ for more information<br>
* See the <a href="Tuning.html"> Topology and Overview</a> page for more info regarding topology.
*
* @page AdvancedConfig Advanced Configuration
*
* RF24Network offers many features, some of which can be configured by editing the RF24Network_config.h file
*
* | Configuration Option | Description |
* |----------------------|-------------|
* |<b> #define RF24NetworkMulticast </b> | This option allows nodes to send and receive multicast payloads. Nodes with multicast enabled can also be configured to relay multicast payloads on to further multicast levels. See multicastRelay |
* | <b> #define DISABLE_FRAGMENTATION </b> | Fragmentation is enabled by default, and uses an additional 144 bytes of memory. |
* | <b> #define MAX_PAYLOAD_SIZE 144 </b> | The maximum size of payloads defaults to 144 bytes. If used with RF24toTUN and two Raspberry Pi, set this to 1514 (TAP) or 1500 (TUN) |
* | <b> #define NUM_USER_PAYLOADS 5 </b> | This is the number of 24-byte payloads the network layer will cache for the user. If using fragmentation, this number * 24 must be larger than MAX_PAYLOAD_SIZE |
* | <b> #define DISABLE_USER_PAYLOADS </b> | This option will disable user-caching of payloads entirely. Use with RF24Ethernet to reduce memory usage. (TCP/IP is an external data type, and not cached) |
* | <b> #define ENABLE_SLEEP_MODE </b> | Uncomment this option to enable sleep mode for AVR devices. (ATTiny,Uno, etc) |
* | <b> #define DUAL_HEAD_RADIO </b> | Uncomment this option to enable use of dual radios |
* | **#define ENABLE_NETWORK_STATS** | Enable counting of all successful or failed transmissions, routed or sent directly |
*
** @page Tuning Performance and Data Loss: Tuning the Network
* Tips and examples for tuning the network and general operation.
*
* <img src="tmrh20/topologyImage.jpg" alt="Topology" height="75%" width="75%">
*
* @section General Understanding Radio Communication and Topology
* When a transmission takes place from one radio module to another, the receiving radio will communicate
* back to the sender with an acknowledgement (ACK) packet, to indicate success. If the sender does not
* receive an ACK, the radio automatically engages in a series of timed retries, at set intervals. The
* radios use techniques like addressing and numbering of payloads to manage this, but it is all done
* automatically by the nrf chip, out of sight from the user.
*
* When working over a radio network, some of these automated techniques can actually hinder data transmission to a degree.
* Retrying failed payloads over and over on a radio network can hinder communication for nearby nodes, or
* reduce throughput and errors on routing nodes.
*
* Radios in this network are linked by <b>addresses</b> assigned to <b>pipes</b>. Each radio can listen
* to 6 addresses on 6 pipes, therefore each radio has a parent pipe and 5 child pipes, which are used
* to form a tree structure. Nodes communicate directly with their parent and children nodes. Any other
* traffic to or from a node must be routed through the network.
*
* @section Topology Topology of RF24Network
*
* Anybody who is familiar at all with IP networking should be able to easily understand RF24Network topology. The
* master node can be seen as the gateway, with up to 4 directly connected nodes. Each of those nodes creates a
* subnet below it, with up to 4 additional child nodes. The numbering scheme can also be related to IP addresses,
* for purposes of understanding the topology via subnetting. Nodes can have 5 children if multicast is disabled.
*
* Expressing RF24Network addresses in IP format:
*
* As an example, we could designate the master node in theory, as Address 10.10.10.10 <br>
* The children nodes of the master would be 10.10.10.1, 10.10.10.2, 10.10.10.3, 10.10.10.4 and 10.10.10.5 <br>
* The children nodes of 10.10.10.1 would be 10.10.1.1, 10.10.2.1, 10.10.3.1, 10.10.4.1 and 10.10.5.1 <br>
*
* In RF24Network, the master is just 00 <br>
* Children of master are 01,02,03,04,05 <br>
* Children of 01 are 011,021,031,041,051 <br>
*
* @section Network Routing
*
* Routing of traffic is handled invisibly to the user, by the network layer. If the network addresses are
* assigned in accordance with the physical layout of the network, nodes will route traffic automatically
* as required. Users simply constuct a header containing the appropriate destination address, and the network
* will forward it through to the correct node. Individual nodes only route individual fragments, so if using
* fragmentation, routing nodes do not need it enabled, unless sending or receiving fragmented payloads themselves.
*
* If routing data between parent and child nodes (marked by direct links on the topology image above) the network
* uses built-in acknowledgement and retry functions of the chip to prevent data loss. When payloads are sent to
* other nodes, they need to be routed. Routing is managed using a combination of built in ACK requests, and
* software driven network ACKs. This allows all routing nodes to forward data very quickly, with only the final
* routing node confirming delivery and sending back an
* acknowledgement.
*
* Example: Node 00 sends to node 01. The nodes will use the built in auto-retry and auto-ack functions.<br>
* Example: Node 00 sends to node 011. Node 00 will send to node 01 as before. Node 01 will forward the message to
* 011. If delivery was successful, node 01 will also forward a message back to node 00, indicating success.
*
* Old Functionality: Node 00 sends to node 011 using auto-ack. Node 00 first sends to 01, 01 acknowledges.
* Node 01 forwards the payload to 011 using auto-ack. If the payload fails between 01 and 011, node 00 has
* no way of knowing.
*
* @note When retrying failed payloads that have been routed, there is a chance of duplicate payloads if the network-ack
* is not successful. In this case, it is left up to the user to manage retries and filtering of duplicate payloads.
*
* Acknowledgements can and should be managed by the application or user. If requesting a response from another node,
* an acknowledgement is not required, so a user defined type of 0-64 should be used, to prevent the network from
* responding with an acknowledgement. If not requesting a response, and wanting to know if the payload was successful
* or not, users can utilize header types 65-127.
*
* @section TuningOverview Tuning Overview
* The RF24 radio modules are generally only capable of either sending or receiving data at any given
* time, but have built-in auto-retry mechanisms to prevent the loss of data. These values are adjusted
* automatically by the library on startup, but can be further adjusted to reduce data loss, and
* thus increase throughput of the network. This page is intended to provide a general overview of its
* operation within the context of the network library, and provide guidance for adjusting these values.
*
* @section RetryTiming Auto-Retry Timing
*
* The core radio library provides the functionality of adjusting the internal auto-retry interval of the
* radio modules. In the network configuration, the radios can be set to automatically retry failed
* transmissions at intervals ranging anywhere from 500us (.5ms) up to 4000us (4ms). When operating any
* number of radios larger than two, it is important to stagger the assigned intervals, to prevent the
* radios from interfering with each other at the radio frequency (RF) layer.
*
* The library should provide fairly good working values, as it simply staggers the assigned values within
* groups of radios in direct communication. This value can be set manually by calling radio.setRetries(X,15);
* and adjusting the value of X from 1 to 15 (steps of 250us).
*
* @section AutoRetry Auto-Retry Count and Extended Timeouts
*
* The core radio library also provides the ability to adjust the internal auto-retry count of the radio
* modules. The default setting is 15 automatic retries per payload, and can be extended by configuring
* the network.txTimeout variable. This default retry count should generally be left at 15, as per the
* example in the above section. An interval/retry setting of (15,15) will provide 15 retrys at intervals of
* 4ms, taking up to 60ms per payload. The library now provides staggered timeout periods by default, but
* they can also be adjusted on a per-node basis.
*
* The txTimeout variable is used to extend the retry count to a defined duration in milliseconds. See the
* network.txTimeout variable. Timeout periods of extended duration (500+) will generally not help when payloads
* are failing due to data collisions, it will only extend the duration of the errors. Extended duration timeouts
* should generally only be configured on leaf nodes that do not receive data, or on a dual-headed node.
*
* @section Examples
*
* <b>Example 1:</b> Network with master node and three leaf nodes that send data to the master node. None of the leaf
* nodes need to receive data.
*
* a: Master node uses default configuration<br>
* b: Leaf nodes can be configured with extended timeout periods to ensure reception by the master.<br>
* c:
* @code
* Leaf 01: network.txTimeout = 500; Leaf 02: network.txTimeout = 573; Leaf 03: network.txTimeout = 653;
* @endcode
* This configuration will provide a reduction in errors, as the timeouts have been extended, and are staggered
* between devices.
*
*
* <b>Example 2:</b> Network with master node and three leaf nodes that send data to the master node. The second leaf
* node needs to receive configuration data from the master at set intervals of 1 second, and send data back to the
* master node. The other leaf nodes will send basic sensor information every few seconds, and a few dropped payloads
* will not affect the operation greatly.
*
* a: Master node configured with extended timeouts of .5 seconds, and increased retry delay:
* @code
* radio.setRetries(11,15);
* network.txTimeout = 500;
* @endcode
* b: Second leaf node configured with a similar timeout period and retry delay:
* @code
* radio.setRetries(8,15);
* network.txTimeout = 553;
* @endcode
* c: First and third leaf nodes configured with default timeout periods or slightly increased timout periods.
*
* @section DualHead Dual Headed Operation
*
* The library now supports a dual radio configuration to further enhance network performance, while reducing errors on
* busy networks. Master nodes or relay nodes with a large number of child nodes can benefit somewhat from a dual headed
* configuration, since one radio is used for receiving, and the other entirely for transmission.
*
* To configure a dual headed node:
* 1. Edit the RF24Network_config.h file, and uncomment #define DUAL_HEAD_RADIO
* 2. Connect another radio, using the same MOSI, MISO, and SCK lines.
* 3. Choose another two pins to use for CE and CS on the second radio. Connect them.
* 4. Setup the radio and network like so:
*
* @code
* RF24 radio(7,8); // Using CE (7) and CS (8) for first radio
* RF24 radio1(4,5); // Using CE (4) and CS (5) for second radio
* RF24Network network(radio,radio1); // Set up the network using both radios
*
* Then in setup(), call radio.begin(); and radio1.begin(); before network.begin();
* @endcode
*
* 5. Upload to MCU. The node will now use the first radio to receive data, and radio1 to transmit, preventing data loss on a busy network.
* 6. Re-comment the #define in the config file as required if configuring other single-headed radios.
*
*
* Any node can be configured in dual-head mode.
*
*
*
*
* @page Zigbee Comparison to ZigBee
*
* This network layer is influenced by the design of ZigBee, but does not implement it
* directly.
*
* @section Advantage Which is better?
*
* ZigBee is a much more robust, feature-rich set of protocols, with many different vendors
* providing compatible chips.
*
* RF24Network is cheap. While ZigBee radios are well over $20, nRF24L01 modules can be found
* for under $2. My personal favorite is
* <a href="http://www.mdfly.com/index.php?main_page=product_info&products_id=82">MDFly RF-IS2401</a>.
*
* @section Contrast Similiarities & Differences
*
* Here are some comparisons between RF24Network and ZigBee.
*
* @li Both networks support Star and Tree topologies. Only Zigbee supports a true mesh.
* @li In ZigBee networks, only leaf nodes can sleep
* @li ZigBee nodes are configured using AT commands, or a separate Windows application.
* RF24 nodes are configured by recompiliing the firmware or writing to EEPROM.
*
* @section NodeNames Node Naming
*
* @li Leaf node: A node at the outer edge of the network with no children. ZigBee calls it
* an End Device node.
* @li Relay node: A node which has both parents and children, and relays messages from one
* to the other. ZigBee calls it a Router.
* @li Base node. The top of the tree node with no parents, only children. Typically this node
* will bridge to another kind of network like Ethernet. ZigBee calls it a Co-ordinator node.
*
*
*
*
*/
#endif // __RF24NETWORK_H__
| 42.723795 | 241 | 0.718553 | [
"mesh",
"object"
] |
32405508df32ede46534e08cd0bb38de55f03a6a | 4,628 | h | C | src/mongo/db/s/shard_local.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/shard_local.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/s/shard_local.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include "mongo/db/rs_local_client.h"
#include "mongo/s/client/shard.h"
namespace mongo {
Status createIndexOnConfigCollection(OperationContext* opCtx,
const NamespaceString& ns,
const BSONObj& keys,
bool unique);
class ShardLocal : public Shard {
ShardLocal(const ShardLocal&) = delete;
ShardLocal& operator=(const ShardLocal&) = delete;
public:
explicit ShardLocal(const ShardId& id);
~ShardLocal() = default;
/**
* These functions are implemented for the Shard interface's sake. They should not be called on
* ShardLocal because doing so triggers invariants.
*/
ConnectionString getConnString() const override;
std::shared_ptr<RemoteCommandTargeter> getTargeter() const override;
void updateReplSetMonitor(const HostAndPort& remoteHost,
const Status& remoteCommandStatus) override;
std::string toString() const override;
bool isRetriableError(ErrorCodes::Error code, RetryPolicy options) final;
Status createIndexOnConfig(OperationContext* opCtx,
const NamespaceString& ns,
const BSONObj& keys,
bool unique) override;
void updateLastCommittedOpTime(LogicalTime lastCommittedOpTime) final;
LogicalTime getLastCommittedOpTime() const final;
void runFireAndForgetCommand(OperationContext* opCtx,
const ReadPreferenceSetting& readPref,
const std::string& dbName,
const BSONObj& cmdObj) override;
Status runAggregation(
OperationContext* opCtx,
const AggregateCommandRequest& aggRequest,
std::function<bool(const std::vector<BSONObj>& batch,
const boost::optional<BSONObj>& postBatchResumeToken)> callback);
private:
StatusWith<Shard::CommandResponse> _runCommand(OperationContext* opCtx,
const ReadPreferenceSetting& unused,
StringData dbName,
Milliseconds maxTimeMSOverrideUnused,
const BSONObj& cmdObj) final;
StatusWith<Shard::QueryResponse> _runExhaustiveCursorCommand(
OperationContext* opCtx,
const ReadPreferenceSetting& readPref,
StringData dbName,
Milliseconds maxTimeMSOverride,
const BSONObj& cmdObj) final;
StatusWith<Shard::QueryResponse> _exhaustiveFindOnConfig(
OperationContext* opCtx,
const ReadPreferenceSetting& readPref,
const repl::ReadConcernLevel& readConcernLevel,
const NamespaceString& nss,
const BSONObj& query,
const BSONObj& sort,
boost::optional<long long> limit,
const boost::optional<BSONObj>& hint = boost::none) final;
RSLocalClient _rsLocalClient;
};
} // namespace mongo
| 41.321429 | 99 | 0.64758 | [
"vector"
] |
3240d868f281bae5de7c3091ae157e2c8f9be7c2 | 1,443 | h | C | model/v1beta2_deployment_spec.h | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | model/v1beta2_deployment_spec.h | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | model/v1beta2_deployment_spec.h | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | /*
* v1beta2_deployment_spec.h
*
* DeploymentSpec is the specification of the desired behavior of the Deployment.
*/
#ifndef _v1beta2_deployment_spec_H_
#define _v1beta2_deployment_spec_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "v1_label_selector.h"
#include "v1_pod_template_spec.h"
#include "v1beta2_deployment_strategy.h"
typedef struct v1beta2_deployment_spec_t {
int minReadySeconds; //numeric
int paused; //boolean
int progressDeadlineSeconds; //numeric
int replicas; //numeric
int revisionHistoryLimit; //numeric
v1_label_selector_t *selector; //model
v1beta2_deployment_strategy_t *strategy; //model
v1_pod_template_spec_t *template; //model
} v1beta2_deployment_spec_t;
v1beta2_deployment_spec_t *v1beta2_deployment_spec_create(
int minReadySeconds,
int paused,
int progressDeadlineSeconds,
int replicas,
int revisionHistoryLimit,
v1_label_selector_t *selector,
v1beta2_deployment_strategy_t *strategy,
v1_pod_template_spec_t *template
);
void v1beta2_deployment_spec_free(v1beta2_deployment_spec_t *v1beta2_deployment_spec);
v1beta2_deployment_spec_t *v1beta2_deployment_spec_parseFromJSON(cJSON *v1beta2_deployment_specJSON);
cJSON *v1beta2_deployment_spec_convertToJSON(v1beta2_deployment_spec_t *v1beta2_deployment_spec);
#endif /* _v1beta2_deployment_spec_H_ */
| 28.294118 | 101 | 0.798337 | [
"model"
] |
32498c22b898e0916753db05352239ab3d8bc1b5 | 472 | h | C | src/Three20/TTLinkView.h | places/three20 | 20638f8e0f4d4ac19efea19f4e7dcd05863e31b0 | [
"Apache-2.0"
] | 1 | 2016-05-09T08:02:33.000Z | 2016-05-09T08:02:33.000Z | src/Three20/TTLinkView.h | ctlittle22/three20 | 20638f8e0f4d4ac19efea19f4e7dcd05863e31b0 | [
"Apache-2.0"
] | null | null | null | src/Three20/TTLinkView.h | ctlittle22/three20 | 20638f8e0f4d4ac19efea19f4e7dcd05863e31b0 | [
"Apache-2.0"
] | null | null | null | #import "Three20/TTGlobal.h"
@class TTBackgroundView;
@interface TTLinkView : UIControl {
id _delegate;
id _url;
TTBackgroundView* _screenView;
int _borderRadius;
}
@property(nonatomic,assign) id delegate;
/**
* The object that will be navigated to when the control is touched.
*
* This can be a string or an object that whose type is registered with TTNavigationCenter.
*/
@property(nonatomic,retain) id url;
@property(nonatomic) int borderRadius;
@end
| 19.666667 | 91 | 0.747881 | [
"object"
] |
324daf4557aaf0bf71538deb2f5787cf00e2fd6a | 13,249 | h | C | aws-cpp-sdk-ec2/include/aws/ec2/model/AllocateHostsRequest.h | pixvana/aws-sdk-cpp | 7ba3f49c8a2636b48342c71e038aa09b6e47077c | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-ec2/include/aws/ec2/model/AllocateHostsRequest.h | isubscribed/aws-sdk-cpp | 4689ffab8c5601976e73ac185f20e12a2a0fbc37 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/include/aws/ec2/model/AllocateHostsRequest.h | isubscribed/aws-sdk-cpp | 4689ffab8c5601976e73ac185f20e12a2a0fbc37 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/ec2/model/AutoPlacement.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/TagSpecification.h>
#include <utility>
namespace Aws
{
namespace EC2
{
namespace Model
{
/**
*/
class AWS_EC2_API AllocateHostsRequest : public EC2Request
{
public:
AllocateHostsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "AllocateHosts"; }
Aws::String SerializePayload() const override;
protected:
void DumpBodyToUrl(Aws::Http::URI& uri ) const override;
public:
/**
* <p>This is enabled by default. This property allows instances to be
* automatically placed onto available Dedicated Hosts, when you are launching
* instances without specifying a host ID.</p> <p>Default: Enabled</p>
*/
inline const AutoPlacement& GetAutoPlacement() const{ return m_autoPlacement; }
/**
* <p>This is enabled by default. This property allows instances to be
* automatically placed onto available Dedicated Hosts, when you are launching
* instances without specifying a host ID.</p> <p>Default: Enabled</p>
*/
inline void SetAutoPlacement(const AutoPlacement& value) { m_autoPlacementHasBeenSet = true; m_autoPlacement = value; }
/**
* <p>This is enabled by default. This property allows instances to be
* automatically placed onto available Dedicated Hosts, when you are launching
* instances without specifying a host ID.</p> <p>Default: Enabled</p>
*/
inline void SetAutoPlacement(AutoPlacement&& value) { m_autoPlacementHasBeenSet = true; m_autoPlacement = std::move(value); }
/**
* <p>This is enabled by default. This property allows instances to be
* automatically placed onto available Dedicated Hosts, when you are launching
* instances without specifying a host ID.</p> <p>Default: Enabled</p>
*/
inline AllocateHostsRequest& WithAutoPlacement(const AutoPlacement& value) { SetAutoPlacement(value); return *this;}
/**
* <p>This is enabled by default. This property allows instances to be
* automatically placed onto available Dedicated Hosts, when you are launching
* instances without specifying a host ID.</p> <p>Default: Enabled</p>
*/
inline AllocateHostsRequest& WithAutoPlacement(AutoPlacement&& value) { SetAutoPlacement(std::move(value)); return *this;}
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline const Aws::String& GetAvailabilityZone() const{ return m_availabilityZone; }
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline void SetAvailabilityZone(const Aws::String& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = value; }
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline void SetAvailabilityZone(Aws::String&& value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone = std::move(value); }
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline void SetAvailabilityZone(const char* value) { m_availabilityZoneHasBeenSet = true; m_availabilityZone.assign(value); }
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline AllocateHostsRequest& WithAvailabilityZone(const Aws::String& value) { SetAvailabilityZone(value); return *this;}
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline AllocateHostsRequest& WithAvailabilityZone(Aws::String&& value) { SetAvailabilityZone(std::move(value)); return *this;}
/**
* <p>The Availability Zone for the Dedicated Hosts.</p>
*/
inline AllocateHostsRequest& WithAvailabilityZone(const char* value) { SetAvailabilityZone(value); return *this;}
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline const Aws::String& GetClientToken() const{ return m_clientToken; }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline AllocateHostsRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;}
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline AllocateHostsRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;}
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request. For more information, see <a
* href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html">How
* to Ensure Idempotency</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
* </p>
*/
inline AllocateHostsRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;}
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline const Aws::String& GetInstanceType() const{ return m_instanceType; }
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline void SetInstanceType(const Aws::String& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; }
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline void SetInstanceType(Aws::String&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); }
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline void SetInstanceType(const char* value) { m_instanceTypeHasBeenSet = true; m_instanceType.assign(value); }
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline AllocateHostsRequest& WithInstanceType(const Aws::String& value) { SetInstanceType(value); return *this;}
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline AllocateHostsRequest& WithInstanceType(Aws::String&& value) { SetInstanceType(std::move(value)); return *this;}
/**
* <p>Specify the instance type for which to configure your Dedicated Hosts. When
* you specify the instance type, that is the only instance type that you can
* launch onto that host.</p>
*/
inline AllocateHostsRequest& WithInstanceType(const char* value) { SetInstanceType(value); return *this;}
/**
* <p>The number of Dedicated Hosts to allocate to your account with these
* parameters.</p>
*/
inline int GetQuantity() const{ return m_quantity; }
/**
* <p>The number of Dedicated Hosts to allocate to your account with these
* parameters.</p>
*/
inline void SetQuantity(int value) { m_quantityHasBeenSet = true; m_quantity = value; }
/**
* <p>The number of Dedicated Hosts to allocate to your account with these
* parameters.</p>
*/
inline AllocateHostsRequest& WithQuantity(int value) { SetQuantity(value); return *this;}
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline const Aws::Vector<TagSpecification>& GetTagSpecifications() const{ return m_tagSpecifications; }
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline void SetTagSpecifications(const Aws::Vector<TagSpecification>& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications = value; }
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline void SetTagSpecifications(Aws::Vector<TagSpecification>&& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications = std::move(value); }
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline AllocateHostsRequest& WithTagSpecifications(const Aws::Vector<TagSpecification>& value) { SetTagSpecifications(value); return *this;}
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline AllocateHostsRequest& WithTagSpecifications(Aws::Vector<TagSpecification>&& value) { SetTagSpecifications(std::move(value)); return *this;}
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline AllocateHostsRequest& AddTagSpecifications(const TagSpecification& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications.push_back(value); return *this; }
/**
* <p>The tags to apply to the Dedicated Host during creation.</p>
*/
inline AllocateHostsRequest& AddTagSpecifications(TagSpecification&& value) { m_tagSpecificationsHasBeenSet = true; m_tagSpecifications.push_back(std::move(value)); return *this; }
private:
AutoPlacement m_autoPlacement;
bool m_autoPlacementHasBeenSet;
Aws::String m_availabilityZone;
bool m_availabilityZoneHasBeenSet;
Aws::String m_clientToken;
bool m_clientTokenHasBeenSet;
Aws::String m_instanceType;
bool m_instanceTypeHasBeenSet;
int m_quantity;
bool m_quantityHasBeenSet;
Aws::Vector<TagSpecification> m_tagSpecifications;
bool m_tagSpecificationsHasBeenSet;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| 41.927215 | 184 | 0.701034 | [
"vector",
"model"
] |
324e1d1530bc6baa82a590db56b8c9077559c78b | 8,001 | h | C | core/sql/langman/LmResultSetJava.h | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 148 | 2015-06-18T21:26:04.000Z | 2017-12-25T01:47:01.000Z | core/sql/langman/LmResultSetJava.h | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 1,352 | 2015-06-20T03:05:01.000Z | 2017-12-25T14:13:18.000Z | core/sql/langman/LmResultSetJava.h | CoderSong2015/Apache-Trafodion | 889631aae9cdcd38fca92418d633f2dedc0be619 | [
"Apache-2.0"
] | 166 | 2015-06-19T18:52:10.000Z | 2017-12-27T06:19:32.000Z | /**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
******************************************************************************
*
* File: LmResultSetJava.h
* Description: Container for Java specific result set data.
*
* Created: 09/07/2005
* Language: C++
*
******************************************************************************
*/
#ifndef LMRESULTSETJAVA_H
#define LMRESULTSETJAVA_H
#include "ComSmallDefs.h"
#include "LmCommon.h"
#include "LmResultSet.h"
#include "LmLangManagerJava.h"
#include "LmRoutineJava.h"
#include "jni.h"
#include "LmConnection.h"
//////////////////////////////////////////////////////////////////////
//
// LmResultSetJava
//
//////////////////////////////////////////////////////////////////////
class LmResultSetJava : public LmResultSet
{
friend class LmRoutineJava;
public:
enum LmResultSetInfoStatus {
RS_INFO_OK = 0,
RS_INFO_CLOSED,
RS_INFO_LOBCOL,
RS_INFO_ERROR = -1
};
enum LmJDBCConnectionType {
JDBC_UNKNOWN_CONNECTION = -1,
JDBC_TYPE4_CONNECTION = 1,
JDBC_TYPE2_CONNECTION = 2
};
// Accessor methods
LmHandle getResultSet() const { return jdbcRSRef_; }
char *getProxySyntax() { return proxySyntax_; }
NABoolean usesT2Connection()
{ return connectionType_ == JDBC_TYPE2_CONNECTION; }
NABoolean usesT4Connection()
{ return connectionType_ == JDBC_TYPE4_CONNECTION; }
NABoolean moreSpecialRows()
{ return (usesT2Connection()) ?
lastBufferedRow_ > currentRowPosition_ : TRUE; }
NABoolean isCLIStmtClosed()
{
return CLIStmtClosed_;
}
Lng32 fetchSpecialRows(void *dataPtr,
LmParameter *colDesc,
ComUInt32 numCols,
ComDiagsArea &da,
ComDiagsArea *rda);
private:
NABoolean isScrollable() const
{
if (cursorType_ == RS_TYPE_SCROLL_INSENSITIVE ||
cursorType_ == RS_TYPE_SCROLL_SENSITIVE)
return TRUE;
else
return FALSE;
}
// The constructor and destructor are defined as private
// since the object management of this class can only be
// done by the LmRoutineJava class.
// Constrcutor:
// Makes a JNI call to LmUtility::getRSInfo()
// to get result set information for the passed in
// java.sql.ResultSet object (parameter rsRef) and
// initializes the data members accordingly.
//
// Parameters description:
// lm : Pointer to LmLanguageManagerJava object
// rsRef : java.sql.ResultSet object reference
// paramPos : The position (1-based) of the Java result set object
// in the java method signature. Used only in error reporting.
// routineName : The name of the routine. Used only in error reporting.
// status (output) : The status indicating the outcome of calling the
// LmUtility::getRSInfo() java method.
// da (output) : Diagnostics area to report errors
//
// The following 'status' can be returned:
// RS_INFO_OK : Result set information was retrieved successfully
// RS_INFO_CLOSED : The result set object (rsRef) is already closed
// RS_INFO_ERROR : There was a problem getting result set information
LmResultSetJava(LmLanguageManagerJava *lm,
LmHandle rsRef,
Int32 paramPos,
const char *routineName,
LmResultSetInfoStatus &status,
NAList<LmConnection*> &lmConnList,
ComDiagsArea *da);
// Destructor:
// Deletes the global references in jdbcRSRef_.
// Should be called only from within the close() method
~LmResultSetJava();
void initType4ResultSet(Int32 paramPos,
const char *routineName,
LmResultSetInfoStatus &status,
NAList<LmConnection*> &lmConnList,
ComDiagsArea *da);
void initType2ResultSet(Int32 paramPos,
const char *routineName,
LmResultSetInfoStatus &status,
NAList<LmConnection*> &lmConnList,
ComDiagsArea *da);
// Calls the close() method on the Java result set object
// Decrements the reference count in the associated LmConnection object
// Calls the class destructor
void close( ComDiagsArea *da = NULL );
void insertIntoDiagnostic(ComDiagsArea &da, ComUInt32 col_num);
LmResult getValueAsJlong(jobject bigdecObj,
ComUInt32 columnIndex,
ComDiagsArea &da,
NABoolean &wasNull,
jlong &returnvalue);
LmLanguageManagerJava *lmj_;
NAList<LmConnection*> &lmConnList_; // +++ NEED COMMENTS
LmConnection *lmConn_; // Manages the java.sql.Connection object
// of this result set
LmJDBCConnectionType connectionType_; // Type 2 or Type 4 connection
LmHandle jdbcRSRef_; // The Java result set object of this
// result set. Contains a global reference
// the object passed into the init() method.
char *proxySyntax_; // Proxy syntax (used when T4 conn is used)
Int32 firstBufferedRow_; // The row position of the first row that JDBC/MX
// has fetched from SQL/MX and that is still
// buffered in the JDBC/MX driver. The row
// numbers are 1-based.
Int32 lastBufferedRow_; // The row position of the last row that JDBC/MX
// has fetched from SQL/MX and that is still
// buffered in the JDBC/MX driver.
Int32 currentRowPosition_; // The current row position of this
// java.sql.ResultSet instance.
LmResultSetType cursorType_; // Indicates whether this is a scrollable
// or forward-only cursor etc.
Int64 rsCounter_; // An unique value given to each result set
// object in JDBC/MX to indicate the order
// in which the result set's underlying SQL
// statement was executed.
NABoolean CLIStmtClosed_; // Indicates whether the CLI statement is
// closed or not
// The following fields are allocated in the constructor and used as
// parameters to the LmUtility::getRSInfo() method. Destructor
// deallocates them.
// ++++++++++++++++++++
// TBD:
// Can we declare the below fields as 'static' since they are only used
// during LmUtility::getRSInfo() JNI call and are not required beyond the
// constructor. We can just allocate them the first time this class
// constructor is called and then just re-use them after that. They
// will need to be deallocated when LM gets destructed.
//
// Will this static approach be a concern if LM is made to work in a
// multi-threaded environment in the future.
// ++++++++++++++++++++
jintArray iArray_;
jlongArray lArray_;
jobjectArray oArray_;
jintArray errCode_;
jobjectArray errDetail_;
};
#endif
| 34.636364 | 78 | 0.613548 | [
"object"
] |
324e79ef07fe02ebf8ed45503dd26f9c819e6d30 | 5,701 | c | C | examples/switch_ms/main.c | AramVartanyan/esp-homekit-demo | 007cdb10539acf31dd1873a354bd2833f2a504e6 | [
"MIT"
] | 3 | 2019-11-05T15:01:03.000Z | 2021-02-23T01:31:44.000Z | examples/switch_ms/main.c | AramVartanyan/esp-homekit-demo | 007cdb10539acf31dd1873a354bd2833f2a504e6 | [
"MIT"
] | null | null | null | examples/switch_ms/main.c | AramVartanyan/esp-homekit-demo | 007cdb10539acf31dd1873a354bd2833f2a504e6 | [
"MIT"
] | 2 | 2019-04-11T04:32:36.000Z | 2019-11-24T21:18:39.000Z | /*
* Switch + Motion sensor HC-SR501 (device Sonoff redesign)
*/
#include <stdio.h>
#include <espressif/esp_wifi.h>
#include <espressif/esp_sta.h>
#include <espressif/esp_common.h>
#include <esp/uart.h>
#include <esp8266.h>
#include <FreeRTOS.h>
#include <task.h>
#include <homekit/homekit.h>
#include <homekit/characteristics.h>
#include <wifi_config.h>
#include "adv_button.h"
#define MOTION_SENSOR_GPIO 14
#define RELAY_GPIO 12
#define LED_GPIO 2
#ifndef BUTTON_GPIO
#define BUTTON_GPIO 0
#endif
void switch_on_callback(homekit_characteristic_t *_ch, homekit_value_t on, void *context);
void relay_write(bool on) {
gpio_write(RELAY_GPIO, on ? 1 : 0);
}
void led_write(bool on) {
gpio_write(LED_GPIO, on ? 0 : 1);
}
void reset_configuration_task() {
//Flash the LED before the reset
for (int i=0; i<3; i++) {
led_write(true);
vTaskDelay(100 / portTICK_PERIOD_MS);
led_write(false);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
printf("Resetting Wifi Config\n");
wifi_config_reset();
vTaskDelay(1000 / portTICK_PERIOD_MS);
printf("Resetting HomeKit Config\n");
homekit_server_reset();
vTaskDelay(1000 / portTICK_PERIOD_MS);
printf("Restarting\n");
sdk_system_restart();
vTaskDelete(NULL);
}
void reset_configuration(const uint8_t gpio) {
printf("Resetting device configuration\n");
xTaskCreate(reset_configuration_task, "Reset configuration", 256, NULL, 2, NULL);
}
homekit_characteristic_t switch_on = HOMEKIT_CHARACTERISTIC_(ON, false, .callback=HOMEKIT_CHARACTERISTIC_CALLBACK(switch_on_callback));
homekit_characteristic_t motion_detected = HOMEKIT_CHARACTERISTIC_(MOTION_DETECTED, 0);
void motion_sensor_task(void *_args) {
gpio_set_pullup(MOTION_SENSOR_GPIO, false, false);
while (1) {
if (gpio_read(MOTION_SENSOR_GPIO) == true) {
motion_detected.value.bool_value = 1;
printf("Motion Detected\n");
led_write(true);
vTaskDelay(50 / portTICK_PERIOD_MS);
led_write(false);
vTaskDelay(50 / portTICK_PERIOD_MS);
}
else {
motion_detected.value.bool_value = 0;
}
led_write(switch_on.value.bool_value);
homekit_characteristic_notify(&motion_detected, motion_detected.value);
vTaskDelay(250 / portTICK_PERIOD_MS);
}
}
void gpio_init() {
gpio_enable(MOTION_SENSOR_GPIO, GPIO_INPUT);
gpio_enable(LED_GPIO, GPIO_OUTPUT);
gpio_enable(RELAY_GPIO, GPIO_OUTPUT);
led_write(false);
relay_write(false);
xTaskCreate(motion_sensor_task, "Motion Sensor", 256, NULL, 2, NULL);
}
void switch_on_callback(homekit_characteristic_t *_ch, homekit_value_t on, void *context) {
led_write(switch_on.value.bool_value);
relay_write(switch_on.value.bool_value);
}
void toggle_switch(const uint8_t gpio) {
printf("Toggle Switch manual\n");
switch_on.value.bool_value = !switch_on.value.bool_value;
led_write(switch_on.value.bool_value);
relay_write(switch_on.value.bool_value);
homekit_characteristic_notify(&switch_on, switch_on.value);
}
void switch_identify_task(void *_args) {
// Device identification
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
led_write(true);
vTaskDelay(100 / portTICK_PERIOD_MS);
led_write(false);
vTaskDelay(100 / portTICK_PERIOD_MS);
}
vTaskDelay(250 / portTICK_PERIOD_MS);
}
led_write(false);
vTaskDelete(NULL);
}
void switch_identify(homekit_value_t _value) {
printf("Switch identify\n");
xTaskCreate(switch_identify_task, "Switch identify", 128, NULL, 2, NULL);
}
homekit_characteristic_t name = HOMEKIT_CHARACTERISTIC_(NAME, "Switch");
homekit_accessory_t *accessories[] = {
HOMEKIT_ACCESSORY(.id=1, .category=homekit_accessory_category_switch, .services=(homekit_service_t*[]){
HOMEKIT_SERVICE(ACCESSORY_INFORMATION, .characteristics=(homekit_characteristic_t*[]){
&name,
HOMEKIT_CHARACTERISTIC(MANUFACTURER, "Armo Ltd."),
HOMEKIT_CHARACTERISTIC(SERIAL_NUMBER, "007A1AVBG02P"),
HOMEKIT_CHARACTERISTIC(MODEL, "S-MS"),
HOMEKIT_CHARACTERISTIC(FIRMWARE_REVISION, "0.2.4"),
HOMEKIT_CHARACTERISTIC(IDENTIFY, switch_identify),
NULL
}),
HOMEKIT_SERVICE(SWITCH, .primary=true, .characteristics=(homekit_characteristic_t*[]){
HOMEKIT_CHARACTERISTIC(NAME, "Switch"),
&switch_on,
NULL
}),
HOMEKIT_SERVICE(MOTION_SENSOR, .primary=false, .characteristics=(homekit_characteristic_t*[]) {
HOMEKIT_CHARACTERISTIC(NAME, "Motion Sensor"),
&motion_detected,
NULL
}),
NULL
}),
NULL
};
homekit_server_config_t config = {
.accessories = accessories,
.password = "320-10-140"
};
void on_wifi_ready() {
homekit_server_init(&config);
}
void create_accessory_name() {
uint8_t macaddr[6];
sdk_wifi_get_macaddr(STATION_IF, macaddr);
int name_len = snprintf(NULL, 0, "Switch-%02X%02X%02X",
macaddr[3], macaddr[4], macaddr[5]);
char *name_value = malloc(name_len+1);
snprintf(name_value, name_len+1, "Switch-%02X%02X%02X",
macaddr[3], macaddr[4], macaddr[5]);
name.value = HOMEKIT_STRING(name_value);
}
void user_init(void) {
uart_set_baud(0, 115200);
create_accessory_name();
wifi_config_init("Switch", NULL, on_wifi_ready);
gpio_init();
adv_button_create(BUTTON_GPIO);
adv_button_register_callback_fn(BUTTON_GPIO, toggle_switch, 1);
adv_button_register_callback_fn(BUTTON_GPIO, reset_configuration, 5);
}
| 30.650538 | 135 | 0.687248 | [
"model"
] |
3252adb19e4c2e48f86c3c811bfc7d75fd06a8f7 | 56,954 | h | C | paddle/math/Matrix.h | OleNet/Paddle | 59271d643b13b13346889d12355611b9a2ce4e31 | [
"Apache-2.0"
] | 1 | 2016-10-07T20:40:11.000Z | 2016-10-07T20:40:11.000Z | paddle/math/Matrix.h | anuranrc/Paddle | 21fa3eb0688459d3b71141d316e8358d31882b8d | [
"Apache-2.0"
] | 1 | 2017-05-26T18:33:00.000Z | 2017-05-26T18:33:00.000Z | paddle/math/Matrix.h | anuranrc/Paddle | 21fa3eb0688459d3b71141d316e8358d31882b8d | [
"Apache-2.0"
] | 1 | 2016-10-07T00:50:53.000Z | 2016-10-07T00:50:53.000Z | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include <stdint.h>
#include <memory>
#include <thread>
#include "paddle/utils/Logging.h"
#include "paddle/utils/ThreadLocal.h"
#include <hl_gpu.h>
#include "BaseMatrix.h"
#include "MemoryHandle.h"
#include "Vector.h"
#include "paddle/utils/Common.h"
#include "paddle/utils/ThreadLocal.h"
namespace paddle {
/// TODO(tianbing), move to paddle/function/TensorType.h
enum SparseValueType { NO_VALUE = 0, FLOAT_VALUE = 1 };
/**
* @brief matrix sparse_format .
*
* nnz represents nonzero number in sparse matrix.
*
* SPARSE_CSR: row major matrix. length of row is height_ + 1, each element
* represents row start index in Matrix. length of col and value are nnz.
*
* SPARSE_CSC: col major matrix. length of col is width_ + 1, each element
* represents col start index in Matrix. length of col and value are nnz.
*
* @code
* for example: [0, 1, 0, 2, 0;
* 1, 0, 0, 0, 0;
* 0, 0, 0, 2, 5];
* SPARSE_CSR row [0, 2, 3, 5];
* col [1, 3, 0, 3, 4];
* value [1, 2, 1, 2, 5]
* SPARSE_CSC col [0, 1, 2, 2, 4, 5];
* row [1, 0, 0, 2, 2];
* value [1, 1, 2, 2, 5]
* @endcode
*/
/// TODO(tianbing), move to paddle/function/TensorType.h
enum SparseFormat { SPARSE_CSR = 0, SPARSE_CSC = 1 };
class Matrix;
class GpuMatrix;
class CpuMatrix;
class CpuSparseMatrix;
class GpuSparseMatrix;
typedef std::shared_ptr<Matrix> MatrixPtr;
typedef std::shared_ptr<GpuMatrix> GpuMatrixPtr;
typedef std::shared_ptr<CpuMatrix> CpuMatrixPtr;
typedef std::shared_ptr<GpuSparseMatrix> GpuSparseMatrixPtr;
typedef std::shared_ptr<CpuSparseMatrix> CpuSparseMatrixPtr;
/**
* Copy or assignemnt constructor will share the data as opposed to making a
* copy of the original data. To make a copy of the orinal data, use copyFrom()
* instead.
*/
class Matrix : public BaseMatrix {
protected:
Matrix(MemoryHandlePtr memHandle,
size_t height,
size_t width,
bool trans,
bool use_gpu);
Matrix(real* data, size_t height, size_t width, bool trans, bool use_gpu);
Matrix(real* data,
size_t height,
size_t width,
size_t stride,
bool trans,
bool use_gpu);
static ThreadLocal<MatrixPtr> tmpMat_;
public:
size_t elementCnt_; // maximal number of elements which can be held in data_
MemoryHandlePtr memoryHandle_;
public:
virtual ~Matrix() {}
static MatrixPtr create(MemoryHandlePtr memHandle,
size_t height,
size_t width,
bool trans = false);
static MatrixPtr create(size_t height,
size_t width,
bool trans = false,
bool useGpu = false);
static MatrixPtr create(real* data,
size_t height,
size_t width,
bool trans = false,
bool useGpu = false);
static MatrixPtr create(real* data,
size_t height,
size_t width,
size_t stride,
bool trans = false,
bool useGpu = false);
static MatrixPtr createSparseMatrix(size_t height,
size_t width,
size_t nnz,
SparseValueType valueType = FLOAT_VALUE,
bool trans = false,
bool useGpu = false);
static MatrixPtr createSparseMatrix(size_t height,
size_t width,
size_t nnz,
SparseValueType valueType = FLOAT_VALUE,
SparseFormat foramt = SPARSE_CSR,
bool trans = false,
bool useGpu = false);
static MatrixPtr createSparseMatrix(real* data,
int* row,
int* col,
size_t height,
size_t width,
size_t nnz, /* used to allocate space */
SparseValueType valueType, /*value type*/
SparseFormat format,
bool trans,
bool useGpu);
static void resizeOrCreateSparseMatrix(
MatrixPtr& matrix,
size_t height,
size_t width,
size_t nnz,
SparseValueType valueType = FLOAT_VALUE,
SparseFormat foramt = SPARSE_CSR,
bool trans = false,
bool useGpu = false);
static void resizeOrCreate(MatrixPtr& a,
size_t height,
size_t width,
bool trans = false,
bool useGpu = false);
/**
* @brief set the data buffer used to hold the matrix data.
*
* caller should make sure that the size of data is at least
* sizeof(real)*height*width.
*/
void setData(real* data) {
BaseMatrix::setData(data);
memoryHandle_.reset();
}
/// the data should be contiguous
void setData(real* data, size_t newHeight, size_t newWidth) {
setData(data);
height_ = newHeight;
width_ = newWidth;
elementCnt_ = newHeight * newWidth;
stride_ = width_;
}
size_t getWidth() const { return width_; }
size_t getHeight() const { return height_; }
size_t getStride() const { return stride_; }
size_t getElementCnt() const { return elementCnt_; }
virtual real* getData() { return data_; }
virtual const real* getData() const { return data_; }
bool isTransposed() const { return trans_; }
bool isContiguous() const { return stride_ == width_ || height_ == 1; }
// If sparse matrix, need to dynamic_cast to CpuSparseMatrix/GpuSparseMatrix
// befor call the following functions.
// Declare these functions in the base class just easy to call them.
// And these declarations should be moved to base class of sparse matrix
// if refactor sparse matrix
virtual int* getRows() const {
LOG(FATAL) << "Not implemented";
return nullptr; //! suppress warning for no return value.
}
virtual int* getCols() const {
LOG(FATAL) << "Not implemented";
return nullptr; //! suppress warning for no return value.
}
virtual SparseFormat getFormat() const {
LOG(FATAL) << "Not implemented";
return SPARSE_CSR; //! suppress warning for no return value.
}
virtual SparseValueType getValueType() const {
LOG(FATAL) << "Not implemented";
return NO_VALUE; //! suppress warning for no return value.
}
/**
* @brief matrix elment-wise add
*
* Named add3 just because add/add2 has been used in BaseMatrix.cu
* and they are not virtual function.
*/
virtual void add3(MatrixPtr b) { LOG(FATAL) << "Not implemented"; }
MemoryHandlePtr getMemoryHandle() const { return memoryHandle_; }
virtual void zeroMem() { LOG(FATAL) << "Not implemented"; }
virtual void resetOne() { LOG(FATAL) << "Not implemented"; }
void setDiag(real value);
virtual void copyFrom(const Matrix& src) { LOG(FATAL) << "Not implemented"; }
virtual void trimFrom(const CpuSparseMatrix& src) {
LOG(FATAL) << "Not implemented";
}
// asynchronous copy
virtual void copyFrom(const Matrix& src, hl_stream_t stream) {
LOG(FATAL) << "Not implemented";
}
MatrixPtr subMatrix(size_t startRow,
size_t endRow,
size_t startCol,
size_t endCol);
MatrixPtr subRowMatrix(size_t startRow, size_t endRow) {
return subMatrix(startRow, endRow, 0, getWidth());
}
MatrixPtr subColMatrix(size_t startCol, size_t endCol) {
return subMatrix(0, getHeight(), startCol, endCol);
}
virtual MatrixPtr subMatrix(size_t startRow, size_t numRows) {
CHECK_LE(startRow + numRows, getHeight());
return Matrix::create(getData() + startRow * getWidth(),
numRows,
getWidth(),
trans_,
useGpu_);
}
virtual MatrixPtr subMatrix(size_t startRow, size_t numRows, MatrixPtr dest) {
CHECK_LE(startRow + numRows, getHeight());
CHECK_EQ(useGpu_, dest->useGpu_);
dest->setData(this->rowBuf(startRow), numRows, getWidth());
return dest;
}
/**
* If this is GpuMatrix, src is assumed to be CPU memory
*
* If this is CpuMatrix, src is assumed to be CPU memory
*/
virtual void copyFrom(const real* src, size_t size) {
LOG(FATAL) << "Not implemented";
}
virtual void copyFrom(const real* src, const int64_t* seq) {
LOG(FATAL) << "Not implemented";
}
/**
* @brief convert a int vector to a real matrix.
*
* (1) source and dest are both in CPU.
*
* (2) sizes are exactly match.
*/
virtual void copyFrom(const IVector& src) {
LOG(FATAL) << "copy data from int vector only available on CpuMatrix.";
}
virtual void copyByRowIndex(Matrix& b, const IVector& rowIndex) {
LOG(FATAL) << "Not implemented";
}
/**
* @brief Create a matrix with the same type (GpuMatrix, CpuMatrix,
* NonValueSparseMatrix, etc.) as this.
*
* If height and width is zero, the new matrix will have the same size
* as this, otherwise the new matrix will have the specified size.
*
*/
virtual MatrixPtr clone(size_t height = 0,
size_t width = 0,
bool useGpu = false) {
LOG(FATAL) << "Not implemented";
return nullptr;
}
virtual real* getRowBuf(size_t row) {
LOG(FATAL) << "Not implemented";
return nullptr;
}
virtual real getElement(size_t x, size_t y) const {
LOG(FATAL) << "Not implemented";
return 0;
}
virtual real getSum() {
LOG(FATAL) << "Not implemented";
return 0;
}
virtual void accumulateColSum(Matrix& src) {
LOG(FATAL) << "Not implemented";
}
virtual real getAbsSum() {
LOG(FATAL) << "Not implemented";
return 0;
}
/**
* @note Original data may not be preserved after resize().
*/
virtual void resize(size_t newHeight, size_t newWidth) = 0;
/**
* @note This should only be used for sparse matrix.
*/
virtual void resize(size_t newHeight,
size_t newWidth,
size_t newNnz, /* total item used to allocate space */
SparseValueType valueType,
SparseFormat format) = 0;
/**
* @brief This should only be used for sparse matrix.
*
* Currently must be called for each row in order.
* The matrix is not valid until setRow is called for the last row.
*/
virtual void setRow(size_t row,
size_t colNum,
const unsigned int* cols,
const real* values) = 0;
virtual MatrixPtr getTranspose() = 0;
/**
* @brief hard transpose.
*
* allocate matTrans' memory outside, then set memAlloc as false;
* else set as true.
*/
virtual void transpose(MatrixPtr& matTrans, bool memAlloc) {
LOG(FATAL) << "Not implemented";
}
/**
* @brief rotate 90 degrees in clock-wise if clockWise=true;
* otherwise rotate in anti clock-wise
* clock-wise:
* \f[
* y(j,i) = x(M-i-1,j)
* \f]
* anti clock-wise:
* \f[
* y(j,i) = x(i, N-1-j)
* \f]
* where \f$x\f$ is (M x N) input, and \f$y\f$ is (N x M) output.
*
* allocate matRot' memory outside, then set memAlloc as false;
* else set as true.
*/
virtual void rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise) {
LOG(FATAL) << "Not implemented";
}
virtual MatrixPtr getInverse() {
LOG(FATAL) << "Not implemented";
return nullptr;
}
/**
* @brief inverse.
*
* if allocate matInv's memory outside, then set memAlloc as false;
* else set as true.
*/
virtual void inverse(MatrixPtr& matInv, bool memAlloc) {
LOG(FATAL) << "Not implemented";
}
public:
/// Only set all variables to 0 or NULL but not free them.
virtual void clear() {
height_ = 0;
width_ = 0;
data_ = NULL;
}
void reshape(size_t height, size_t width);
/// add b to each sample of this.
virtual void addBias(Matrix& b, real scale) {
LOG(FATAL) << "Not implemented";
}
virtual void addSharedBias(Matrix& b, real scale) {
LOG(FATAL) << "Not implemented";
}
void addBias(Matrix& b, real scale, bool sharedBias) {
if (!sharedBias) {
addBias(b, scale);
} else {
addSharedBias(b, scale);
}
}
/// add each sample from a to this.
virtual void collectBias(Matrix& a, real scale) {
LOG(FATAL) << "Not implemented";
}
virtual void collectSharedBias(Matrix& a, real scale) {
LOG(FATAL) << "Not implemented";
}
void collectBias(Matrix& a, real scale, bool sharedBias) {
if (!sharedBias) {
collectBias(a, scale);
} else {
collectSharedBias(a, scale);
}
}
virtual void sequenceAvgForward(Matrix& a,
const IVector& startsPos,
int mode) {
LOG(FATAL) << "Not implemented";
}
virtual void sequenceAvgBackward(Matrix& a,
const IVector& startsPos,
int mode) {
LOG(FATAL) << "Not implemented";
}
/**
* @code
* this = scaleAB*(a*b) + scaleT*this
* @endcode
*/
virtual void mul(const Matrix& a,
const Matrix& b,
real scaleAB,
real scaleT) {
LOG(FATAL) << "Not implemented";
}
/// Add a vector (column) b to matrix a, column by column.
virtual void addColumnVector(const Matrix& b) {
LOG(FATAL) << "Not implemented";
}
/**
* @code
* For j < codeLength:
* this(i, j) += vec(index(i, j), 0)
* where index(i, j) = ((codes(i) + numClasses) >> (j + 1)) - 1
* @endcode
*/
virtual void addByBitCode(size_t numClasses,
const IVector& codes,
const Matrix& vec) {
(void)numClasses;
(void)codes;
(void)vec;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* For j < codeLength:
* vec(index(i, j), 0) += this(i, j)
* where index is same as the index for addByBitCode
* @endcode
*/
virtual void addByBitCodeBackward(size_t numClasses,
const IVector& codes,
Matrix& vec) {
(void)numClasses;
(void)codes;
(void)vec;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* For j < codeLength:
* this(i, j) += <mat.row(index(i, j)), input.row(i)>
* where index is same as the index for addByBitCode
* @endcode
*/
virtual void mulByBitCode(size_t numClasses,
const IVector& codes,
const Matrix& mat,
const Matrix& input) {
(void)numClasses;
(void)codes;
(void)mat;
(void)input;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* For j < codeLength:
* mat.row(index(i, j)) += this(i, j) * input.row(i)
* where index is same as the index for addByBitCode
* @endcode
*/
virtual void mulByBitCodeBackwardWeight(size_t numClasses,
const IVector& codes,
Matrix& mat,
const Matrix& input) {
(void)numClasses;
(void)codes;
(void)mat;
(void)input;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* For j < codeLength:
* input.row(i) += this(i, j) * mat.row(index(i, j))
* where index is same as the index for addByBitCode
* @endcode
*/
virtual void mulByBitCodeBackwardError(size_t numClasses,
const IVector& codes,
const Matrix& mat,
Matrix& input) {
(void)numClasses;
(void)codes;
(void)mat;
(void)input;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* For j < codeLength
* sum(i, 0) = scaleSum * \sum_j bit(i, j) * this(i, j)
* where bit(i, j) = ((codes(i) + numClasses) & 2^j) ? 1 : 0
* @endcode
*/
virtual void sumByBitCode(size_t numClasses,
IVector& codes,
Matrix& sum,
real scaleSum) {
(void)numClasses;
(void)codes;
(void)sum;
(void)scaleSum;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* For j < codeLength
* this(i, j) -= bit(i, j)
* where bit(i, j) is same as that for sumByBitCode
* @endcode
*/
virtual void subByBitCode(size_t numClasses_, IVector& codes) {
(void)numClasses_;
(void)codes;
LOG(FATAL) << "Not implemeted";
}
/**
* add the sum of each row of this to mat
*/
virtual void rowSum(Matrix& sum) {
(void)sum;
LOG(FATAL) << "Not implemeted";
}
/**
* set the max of each row of this to mat
*/
virtual void rowMax(Matrix& max) {
(void)max;
LOG(FATAL) << "Not implemeted";
}
/**
* set the max of each column of this to mat
*/
virtual void colMax(Matrix& max) { LOG(FATAL) << "not implemented"; }
/**
* @brief Get the top k elements of each column of this matrix.
*
* The row ids and values of these elements are stored in
* maxIds and max respectively. where k is the size of maxIds.
* And note that the top k elements are not sorted.
*/
virtual void colMax(IVector& maxIds, Matrix& maxVal) {
LOG(FATAL) << "not implemented";
}
virtual void maxoutForward(Matrix& a,
IVector& id,
size_t channels,
size_t groups) {
LOG(FATAL) << "not implemented";
}
virtual void maxoutBackward(Matrix& a,
IVector& id,
size_t channels,
size_t groups) {
LOG(FATAL) << "not implemented";
}
virtual void rowMaxId(IVector& maxIds) { LOG(FATAL) << "Not implemented"; }
/**
* @brief Get the top k elements of each row of this matrix.
*
* The column ids and values of these elements are stored in
* maxIds and max respectively. where k is the size of maxIds.
* And note that the top k elements are not sorted.
*/
virtual void rowMax(IVector& maxIds, Matrix& max) {
LOG(FATAL) << "Not implemented";
}
/// normalize each row so that the sum of each row is 1.
virtual void rowNormalizeL1(Matrix& out) {
(void)out;
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* this = a*b
* @endcode
*/
virtual void mul(const Matrix& a, const Matrix& b) {
LOG(FATAL) << "Not implemented";
}
/**
* @code
* this = scaleAB*(this*b) + scaleT*this
* @endcode
*/
virtual void rightMul(Matrix& b, real scaleAB, real scaleT) {
LOG(FATAL) << "Not implemented";
}
/**
* @code
* this = this* b
* @endcode
*/
virtual void rightMul(Matrix& b) { LOG(FATAL) << "Not implemented"; }
/**
* @code
* this = scaleAB*(a*this) + scaleT*this
* @endcode
*/
virtual void leftMul(Matrix& a, real scaleAB, real scaleT) {
LOG(FATAL) << "Not implemented";
}
/**
* @code
* this = a*this)
* @endcode
*/
virtual void leftMul(Matrix& a) { LOG(FATAL) << "Not implemented"; }
/// merge the element for each col.
virtual void colMerge(Matrix& src) { LOG(FATAL) << "Not implemented"; }
/// copy -log(output[label]) to this->data[i].
virtual void oneHotCrossEntropy(Matrix& output, IVector& label) {
LOG(FATAL) << "Not implemented";
}
/// calculate the error of outputV according to label.
virtual void oneHotCrossEntropyBp(Matrix& outputV, IVector& label) {
LOG(FATAL) << "Not implemented";
}
/// copy -log(output[label]) to this->data[i].
virtual void oneHotCrossEntropyWithSelfNorm(Matrix& output,
IVector& label,
real alpha) {
LOG(FATAL) << "Not implemented";
}
/// calculate the error of outputV according to label.
virtual void oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
IVector& label,
real alpha) {
LOG(FATAL) << "Not implemented";
}
/**
* \f[
* a[i] = \sum_{j=-(N-1)/2}^{(N-1)/2} b_{i+j} * c_{j}
* \f]
*
* b contains M elements,
* c contains N elements (N is odd),
* b's index arithmetic is computed modulo M,
* c's index arithmetic is computed modulo N.
*/
virtual void circularConv(Matrix& b, Matrix& c) {
LOG(FATAL) << "Not implemented";
}
virtual void circularConvDerivative(Matrix& output,
Matrix& prevOut1,
Matrix& prevOut2,
Matrix& prevGrad1,
Matrix& prevGrad2) {
LOG(FATAL) << "Not implemented";
}
/* output_ij = exp(this_{ij}) / (sum_j exp(this_ij)) */
virtual void softmax(Matrix& output) {
(void)output;
LOG(FATAL) << "Not implemeted";
}
virtual void sequenceSoftmax(Matrix& output, const IVector& index) {
(void)output;
LOG(FATAL) << "Not implemeted";
}
virtual void softmaxBackward(Matrix& outputV) {
(void)outputV;
LOG(FATAL) << "Not implemeted";
}
/*
sum_i = sum_j this_ij * output_ij
this_ij = output_ij* (this_ij - sum_i)
*/
virtual void softmaxDerivative(Matrix& output, Matrix& sftmaxSum) {
LOG(FATAL) << "Not implemented";
}
/// calculate the sum of squares diff cost.
virtual void sumOfSquares(Matrix& output, Matrix& label) {
LOG(FATAL) << "Not implemented";
}
/// gradient of sumOfSquares.
virtual void sumOfSquaresBp(Matrix& outputV, Matrix& label) {
LOG(FATAL) << "Not implemented";
}
virtual void smoothL1(Matrix& output, Matrix& label) {
LOG(FATAL) << "Not implemented";
}
virtual void smoothL1Bp(Matrix& outputV, Matrix& label) {
LOG(FATAL) << "Not implemented";
}
virtual void tanh(Matrix& output) { LOG(FATAL) << "Not implemented"; }
virtual void tanhDerivative(Matrix& output) {
LOG(FATAL) << "Not implemented";
}
virtual void softrelu(Matrix& output) { LOG(FATAL) << "Not implemented"; }
virtual void softreluDerivative(Matrix& output) {
LOG(FATAL) << "Not implemented";
}
virtual void scaledTanh(Matrix& output, real p1, real p2) {
LOG(FATAL) << "Not implemented";
}
/// print out the values of elements to os
virtual void print(std::ostream& os) const {
LOG(FATAL) << "Not implemented";
}
/**
* print a part of the matrix
* from the (top,left) value to the (height, width) value (not included)
*/
virtual void print(std::ostream& os, size_t height, size_t width) const {
LOG(FATAL) << "Not implemented";
}
/// print one row to os
virtual void printOneRow(std::ostream& os, size_t idx) const {
LOG(FATAL) << "Not implemented";
}
virtual void check(std::ostream& os, Matrix& refMat, bool printDiff = true) {}
virtual real getMin() {
LOG(FATAL) << "Not implemented";
return 0;
}
virtual real getMax() {
LOG(FATAL) << "Not implemented";
return 0;
}
virtual void randomizeUniform() { LOG(FATAL) << "Not implemented"; }
/**
* @brief calulate the error of classification
*
* output[i] = 1 if row i is an error.
*
* output[i] = 0 if row i is correct.
*
*/
virtual void classificationError(Matrix& output,
IVector& label,
size_t topkSize = 1) {
LOG(FATAL) << "Not implemented";
}
/**
* This function is used to calculate the convolution:
*
* It will expand a feature matrix according to the
* convolution filters
*/
virtual void convExpand(Matrix& feature,
int feaImgHeight,
int feaImgWidth,
int channels,
int blockH,
int blockW,
int strideH,
int strideW,
int paddingH,
int paddingW,
int outputH,
int outputW) {
LOG(FATAL) << "Not implemeted";
}
/**
* This function is the reverse implementation of convExpand:
*
* Its function is to restore a expanded-matrix into a feature matrix
*/
virtual void convShrink(Matrix& expandColMat,
int thisImgHeight,
int thisImgWidth,
int channels,
int blockH,
int blockW,
int strideH,
int strideW,
int paddingH,
int paddingW,
int outputH,
int outputW,
real alpha = 1.0f,
real beta = 0.0f) {
LOG(FATAL) << "Not implemeted";
}
/**
* Pooling forward operation, pick out the largest element
* in the sizeX of value
*/
virtual void maxPoolForward(Matrix& inputMat,
size_t imgSizeH,
size_t imgSizeW,
size_t channels,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
size_t paddingH,
size_t paddingW) {
LOG(FATAL) << "Not implemeted";
}
/// Pooling backward operation.
virtual void maxPoolBackward(Matrix& image,
size_t imgSizeH,
size_t imgSizeW,
Matrix& outGrad,
Matrix& outV,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
real scaleTargets,
real scaleOutput,
size_t paddingH,
size_t paddingW) {
LOG(FATAL) << "Not implemeted";
}
/// Pooling forward operation, caculate the average of sizeX elements.
virtual void avgPoolForward(Matrix& input,
size_t imgSizeH,
size_t imgSizeW,
size_t channels,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
size_t paddingH,
size_t paddingW) {
LOG(FATAL) << "Not implemeted";
}
virtual void avgPoolBackward(Matrix& input,
size_t imgSizeH,
size_t imgSizeW,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
real scaleTargets,
real scaleOutput,
size_t paddingH,
size_t paddingW) {
LOG(FATAL) << "Not implemeted";
}
/**
* Input: one or more sequences. Each sequence contains some instances.
*
* Output: output size is the number of input sequences (NOT input
* instances).
*
* output[i] is set to max_input[i].
*/
virtual void maxSequenceForward(Matrix& input,
const IVector& sequence,
IVector& index) {
LOG(FATAL) << "Not implemeted";
}
virtual void maxSequenceBackward(Matrix& outputGrad,
const IVector& sequence,
IVector& index) {
LOG(FATAL) << "Not implemeted";
}
/**
* @code
* this.row[i] += table.row[ids[i]]
* if ids[i] == -1, it will be ignored
* @endcode
*/
virtual void selectRows(Matrix& table, IVector& ids) {
(void)table;
(void)ids;
LOG(FATAL) << "Not implemented";
}
/**
* @code
* this[i] = table[i, id[i]]
* @endcode
*/
virtual void selectElements(Matrix& table, IVector& ids) {
LOG(FATAL) << "Not implemented";
}
/**
* @code
* table.row[ids[i]] += this.row[i]
* if ids[i] == -1, it will be ignored
* @endcode
*/
virtual void addToRows(Matrix& table, IVector& ids) {
(void)table;
(void)ids;
LOG(FATAL) << "Not implemented";
}
/**
* @code
* table[i, id[i]] += this[i]
* @endcode
*/
virtual void addElements(Matrix& table, IVector& ids) {
LOG(FATAL) << "Not implemented";
}
/**
* @brief cross entropy for multi binary labels
*
* @code
* this[i] = -sum(label[i][j]*log(output[i][j])
* + (1-label[i][j])*log(1-output[i][j]))
* @endcode
*/
virtual void multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label) {
LOG(FATAL) << "Not implemented";
}
/**
* @brief The gradient of cross entropy for multi binary labels on output
*
* @code
* this[i][j] = -label[i][j]/output[i][j]
* + (1-label[i][j])/(1-output[i][j])
* @endcode
*/
virtual void multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label) {
LOG(FATAL) << "Not implemented";
}
/**
* @brief Calculate the classification error for multi binary labels
*
* @code
* this[i] = sum((output[i][j] >= threshold && label[i][j] == 0)
* || (output[i][j] < threshold && label[i][j] == 1))
* / output->getWidth()
* @endcode
*/
virtual void classificationErrorMulti(Matrix& output,
Matrix& label,
real threshold) {
LOG(FATAL) << "Not implemented";
}
virtual void paramReluForward(Matrix& data, Matrix& W) {
LOG(FATAL) << "Not implemented";
}
virtual void paramReluBackwardW(Matrix& oGrad, Matrix& data) {
LOG(FATAL) << "Not implemented";
}
virtual void paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W) {
LOG(FATAL) << "Not implemented";
}
virtual void bilinearForward(const Matrix& in,
const size_t inImgH,
const size_t inImgW,
const size_t outImgH,
const size_t outImgW,
const size_t numChannels,
const real ratioH,
const real ratioW) {
LOG(FATAL) << "Not implemented";
}
virtual void bilinearBackward(const Matrix& out,
const size_t outImgH,
const size_t outImgW,
const size_t inImgH,
const size_t inImgW,
const size_t numChannels,
const real ratioH,
const real ratioW) {
LOG(FATAL) << "Not implemented";
}
template <typename ExpressionType>
void operator=(const ExpressionType& expr) {
if (useGpu_) {
TensorGpuApply<real>(*this, expr);
} else {
TensorCpuApply<real>(*this, expr);
}
}
bool isEmpty() const { return data_ == nullptr; }
explicit operator bool() const { return !isEmpty(); }
};
inline std::ostream& operator<<(std::ostream& os, const Matrix& mat) {
mat.print(os);
return os;
}
class GpuMatrix : public Matrix {
public:
GpuMatrix();
GpuMatrix(size_t height, size_t width, bool trans = false);
GpuMatrix(real* data, size_t height, size_t width, bool trans = false)
: Matrix(data, height, width, trans, true) {}
GpuMatrix(real* data,
size_t height,
size_t width,
size_t stride,
bool trans = false)
: Matrix(data, height, width, stride, trans, true) {}
GpuMatrix(GpuMemHandlePtr dataHandle,
size_t height,
size_t width,
bool trans = false)
: Matrix(dataHandle, height, width, trans, true) {}
~GpuMatrix();
void zeroMem();
void resetOne();
void setDiag(real value);
void resize(size_t newHeight, size_t newWidth);
void resize(size_t newHeight,
size_t newWidth,
size_t newNnz, /* used to allocate space */
SparseValueType valueType,
SparseFormat format) {
LOG(FATAL) << "Only Support Sparse Matrix";
}
void setRow(size_t row,
size_t colNum,
const unsigned int* cols,
const real* values) {
LOG(FATAL) << "Only Support Sparse Matrix";
}
/**
* Copy the data from cpu_memory buffer
*/
void copyFrom(const real* hostSrc, size_t size);
void copyFrom(const real* hostSrc, const int64_t* seq);
void copyFrom(const Matrix& src, hl_stream_t stream);
void copyFrom(const Matrix& src);
void copyFrom(const IVector& src);
void copyByRowIndex(Matrix& b, const IVector& rowIndex);
MatrixPtr clone(size_t height, size_t width, bool useGpu = false);
real getElement(size_t x, size_t y) const;
real* getRow(size_t row) { return BaseMatrix::rowBuf(row); }
virtual real* getRowBuf(size_t row) { return getRow(row); }
real getSum();
void accumulateColSum(Matrix& src);
real getAbsSum();
real getMin();
real getMax();
MatrixPtr getTranspose();
void transpose(MatrixPtr& matTrans, bool memAlloc);
void rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise);
MatrixPtr getInverse();
void inverse(MatrixPtr& matInv, bool memAlloc);
/// add b to each sample of this.
void addBias(Matrix& b, real scale);
void addSharedBias(Matrix& b, real scale);
/**
* @code
* add each sample from a to this.
* @endcode
*/
void collectBias(Matrix& a, real scale);
void collectSharedBias(Matrix& a, real scale);
void sequenceAvgForward(Matrix& a, const IVector& startsPos, int mode);
void sequenceAvgBackward(Matrix& a, const IVector& startsPos, int mode);
/**
* @code
* this.row[i] += table.row[ids[i]]
* @endcode
*/
virtual void selectRows(Matrix& table, IVector& ids);
/**
* @code
* this[i] = table[i, id[i]]
* @endcode
*/
virtual void selectElements(Matrix& table, IVector& ids);
/**
* @code
* table.row[ids[i]] += this.row[i]
* @endcode
*/
virtual void addToRows(Matrix& table, IVector& ids);
void addColumnVector(const Matrix& b);
/**
* @code
* this = scaleAB*(a*b) + scaleT*this
* @endcode
*/
void mul(const Matrix& a, const Matrix& b, real scaleAB, real scaleT);
/**
* @code
* this = a*b
* @endcode
*/
void mul(const Matrix& a, const Matrix& b);
void mul(const GpuMatrix& a, const GpuMatrix& b, real scaleAB, real scaleT);
void mul(const GpuSparseMatrix& a,
const GpuMatrix& b,
real scaleAB,
real scaleT);
void mul(const GpuMatrix& a,
const GpuSparseMatrix& b,
real scaleAB,
real scaleT);
/**
* @code
* this = scaleAB*(this*b) + scaleT*this
* @endcode
*/
void rightMul(Matrix& b, real scaleAB, real scaleT);
/**
* @code
* this = this* b
* @endcode
*/
void rightMul(Matrix& b);
/**
* @code
* this = scaleAB*(a*this) + scaleT*this
* @endcode
*/
void leftMul(Matrix& a, real scaleAB, real scaleT);
/**
* @code
* this = a*this
* @endcode
*/
void leftMul(Matrix& a);
void colMerge(Matrix& src);
void rowSum(Matrix& sum);
void rowMax(Matrix& max);
void rowMax(IVector& maxIds, Matrix& max);
void colMax(Matrix& max);
void colMax(IVector& maxIds, Matrix& max);
void maxoutForward(Matrix& a, IVector& id, size_t channels, size_t groups);
void maxoutBackward(Matrix& a, IVector& id, size_t channels, size_t groups);
void oneHotCrossEntropy(Matrix& output, IVector& label);
void oneHotCrossEntropyBp(Matrix& outputV, IVector& label);
void oneHotCrossEntropyWithSelfNorm(Matrix& output,
IVector& label,
real alpha);
void oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
IVector& label,
real alpha);
void softmax(Matrix& output);
void sequenceSoftmax(Matrix& output, const IVector& index);
void softmaxBackward(Matrix& outputV);
void softmaxDerivative(Matrix& output, Matrix& sftmaxSum);
/// calculate the sum of squares diff cost.
void sumOfSquares(Matrix& output, Matrix& label);
/// gradient of sumOfSquares.
void sumOfSquaresBp(Matrix& outputV, Matrix& label);
void tanh(Matrix& output);
void tanhDerivative(Matrix& output);
void softrelu(Matrix& output);
void softreluDerivative(Matrix& output);
void scaledTanh(Matrix& output, real p1, real p2);
virtual void print(std::ostream& os) const;
virtual void print(std::ostream& os, size_t height, size_t width) const;
void paramReluForward(Matrix& data, Matrix& W);
void paramReluBackwardW(Matrix& oGrad, Matrix& data);
void paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W);
void check(std::ostream& os, Matrix& refMat, bool printDiff = true);
void randomizeUniform();
void classificationError(Matrix& output, IVector& label, size_t topkSize = 1);
void convExpand(Matrix& feature,
int feaImgHeight,
int feaImgWidth,
int channels,
int blockH,
int blockW,
int strideH,
int strideW,
int paddingH,
int paddingW,
int outputH,
int outputW);
void convShrink(Matrix& expandColMat,
int thisImgHeight,
int thisImgWidth,
int channels,
int blockH,
int blochW,
int strideH,
int strideW,
int paddingH,
int paddingWreal,
int outputH,
int outputW,
real alpha = 1.0f,
real beta = 0.0f);
void maxPoolForward(Matrix& inputMat,
size_t imgSizeH,
size_t imgSizeW,
size_t channels,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
size_t paddingH,
size_t paddingW);
void maxPoolBackward(Matrix& image,
size_t imgSizeH,
size_t imgSizeW,
Matrix& outGrad,
Matrix& outV,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
real scaleTargets,
real scaleOutput,
size_t paddingH,
size_t paddingW);
void avgPoolForward(Matrix& input,
size_t imgSizeH,
size_t imgSizeW,
size_t channels,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
size_t paddingH,
size_t paddingW);
void avgPoolBackward(Matrix& input,
size_t imgSizeH,
size_t imgSizeW,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
real scaleTargets,
real scaleOutput,
size_t paddingH,
size_t paddingW);
void maxSequenceForward(Matrix& input,
const IVector& sequence,
IVector& index);
void maxSequenceBackward(Matrix& outputGrad,
const IVector& sequence,
IVector& index);
void bilinearForward(const Matrix& in,
const size_t inImgH,
const size_t inImgW,
const size_t outImgH,
const size_t outImgW,
const size_t numChannels,
const real ratioH,
const real ratioW);
void bilinearBackward(const Matrix& out,
const size_t outImgH,
const size_t outImgW,
const size_t inImgH,
const size_t inImgW,
const size_t numChannels,
const real ratioH,
const real ratioW);
void multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label);
void multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label);
template <typename ExpressionType>
void operator=(const ExpressionType& expr) {
TensorGpuApply<real>(*this, expr);
}
};
class CpuMatrix : public Matrix {
public:
CpuMatrix(size_t height, size_t width, bool trans = false);
CpuMatrix(real* data, size_t height, size_t width, bool trans = false)
: Matrix(data, height, width, trans, false) {}
CpuMatrix(real* data,
size_t height,
size_t width,
size_t stride,
bool trans = false)
: Matrix(data, height, width, stride, trans, false) {}
CpuMatrix(CpuMemHandlePtr dataHandle,
size_t height,
size_t width,
bool trans = false)
: Matrix(dataHandle, height, width, trans, false) {}
~CpuMatrix();
void zeroMem();
void resetOne();
void setDiag(real value);
void resize(size_t newHeight, size_t newWidth);
void resize(size_t newHeight,
size_t newWidth,
size_t newNnz, /* used to allocate space */
SparseValueType valueType,
SparseFormat format) {
LOG(FATAL) << "Only Support Sparse Matrix";
}
void setRow(size_t row,
size_t colNum,
const unsigned int* cols,
const real* values) {
LOG(FATAL) << "Only Support Sparse Matrix";
}
real getElement(size_t x, size_t y) const;
real getSum();
void accumulateColSum(Matrix& src);
real getAbsSum();
MatrixPtr getTranspose();
void transpose(MatrixPtr& matTrans, bool memAlloc);
void rotate(MatrixPtr& matRot, bool memAlloc, bool clockWise);
MatrixPtr getInverse();
void inverse(MatrixPtr& matInv, bool memAlloc);
void copyFrom(const Matrix& src);
void copyFrom(const Matrix& src, hl_stream_t stream);
void copyFrom(const real* cpuSrc, size_t size);
void copyFrom(const real* cpuSrc, const int64_t* seq);
void copyFrom(const IVector& src);
void copyFrom(CpuSparseMatrix& src);
void copyByRowIndex(Matrix& b, const IVector& rowIndex);
MatrixPtr clone(size_t height, size_t width, bool useGpu = false);
void convExpand(Matrix& feature,
int feaImgHeight,
int feaImgWidth,
int channels,
int blcokH,
int blockW,
int strideH,
int strideW,
int paddingH,
int paddingW,
int outputH,
int outputW);
void convShrink(Matrix& expandFeat,
int thisImgHeight,
int thisImgWidth,
int channels,
int blockH,
int blockW,
int strideH,
int strideW,
int paddingH,
int paddingW,
int outputH,
int outputW,
real alpha = 1.0f,
real beta = 0.0f);
void maxPoolForward(Matrix& inputMat,
size_t imgSizeH,
size_t imgSizeW,
size_t channels,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
size_t paddingH,
size_t paddingW);
void maxPoolBackward(Matrix& image,
size_t imgSizeH,
size_t imgSizeW,
Matrix& outGrad,
Matrix& outV,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
real scaleTargets,
real scaleOutput,
size_t paddingH,
size_t paddingW);
void avgPoolForward(Matrix& input,
size_t imgSizeH,
size_t imgSizeW,
size_t channels,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
size_t paddingH,
size_t paddingW);
void avgPoolBackward(Matrix& input,
size_t imgSizeH,
size_t imgSizeW,
size_t sizeX,
size_t sizeY,
size_t strideH,
size_t strideW,
size_t outputH,
size_t outputW,
real scaleTargets,
real scaleOutput,
size_t paddingH,
size_t paddingW);
void maxSequenceForward(Matrix& input,
const IVector& sequence,
IVector& index);
void maxSequenceBackward(Matrix& outputGrad,
const IVector& sequence,
IVector& index);
real* getRow(size_t row) { return BaseMatrix::rowBuf(row); }
virtual real* getRowBuf(size_t row) { return getRow(row); }
public:
/// add b to each sample of this.
void addBias(Matrix& b, real scale);
void addSharedBias(Matrix& b, real scale);
/// add each sample of a to this.
void collectBias(Matrix& a, real scale);
void collectSharedBias(Matrix& a, real scale);
void sequenceAvgForward(Matrix& a, const IVector& startsPos, int mode);
void sequenceAvgBackward(Matrix& a, const IVector& startsPos, int mode);
/**
* @code
* this.row[i] += table.row[ids[i]]
* @endcode
*/
virtual void selectRows(Matrix& table, IVector& ids);
/**
* @code
* table.row[ids[i]] += this.row[i]
* @endcode
*/
virtual void addToRows(Matrix& table, IVector& ids);
/**
* @code
* this[i] = table[i, id[i]]
* @endcode
*/
virtual void selectElements(Matrix& table, IVector& ids);
/**
* @code
* table[i, id[i]] += this[i]
* @endcode
*/
virtual void addElements(Matrix& table, IVector& ids);
/**
* use abstract getRow() to get row from table.
*
* Define table as template instead of virtual class for performance sake.
* internal used by above two virtual funcs.
*/
template <typename TableMatType>
void selectRowsImp(TableMatType& table, IVector& ids);
template <typename TableMatType>
void addToRowsImp(TableMatType& table, IVector& ids);
void addColumnVector(const Matrix& b);
void mul(const Matrix& a, const Matrix& b, real scaleAB, real scaleT);
void mul(CpuMatrix* a, CpuMatrix* b, real scaleAB, real scaleT);
void mul(CpuMatrix* a, CpuSparseMatrix* b, real scaleAB, real scaleT);
static void mul(CpuMatrix* a,
CpuMatrix* b,
CpuSparseMatrix* c,
real scaleAB,
real scaleT);
/**
* c = a * b
*
* use abstract getRow() to get row from B,C.
* Define B,C as template instead of virtual class for performance sake.
*/
template <typename MatBType, typename MatCType>
static void mul(
CpuSparseMatrix* a, MatBType* b, MatCType* c, real scaleAB, real scaleT);
virtual void mul(CpuSparseMatrix* a, CpuMatrix* b, real scaleAB, real scaleT);
void mul(const Matrix& a, const Matrix& b);
void rightMul(Matrix& b, real scaleAB, real scaleT);
void rightMul(Matrix& b);
void leftMul(Matrix& a, real scaleAB, real scaleT);
void leftMul(Matrix& a);
void colMerge(Matrix& src);
void rowSum(Matrix& sum);
void rowMaxId(IVector& maxIds);
void rowMax(Matrix& max);
void rowMax(IVector& maxIds, Matrix& maxVal);
void colMax(Matrix& max);
void colMax(IVector& maxIds, Matrix& maxVal);
void maxoutForward(Matrix& a, IVector& id, size_t channels, size_t groups);
void maxoutBackward(Matrix& a, IVector& id, size_t channels, size_t groups);
void rowNormalizeL1(Matrix& out);
void oneHotCrossEntropy(Matrix& output, IVector& label);
void oneHotCrossEntropyBp(Matrix& outputV, IVector& label);
void oneHotCrossEntropyWithSelfNorm(Matrix& output,
IVector& label,
real alpha);
void oneHotCrossEntropyWithSelfNormBp(Matrix& outputV,
IVector& label,
real alpha);
void circularConv(Matrix& b, Matrix& c);
void circularConvDerivative(Matrix& output,
Matrix& prevOut1,
Matrix& prevOut2,
Matrix& prevGrad1,
Matrix& prevGrad2);
void softmax(Matrix& output);
void sequenceSoftmax(Matrix& output, const IVector& index);
void softmaxDerivative(Matrix& output, Matrix& sftmaxSum);
/// calculate the sum of squares diff cost.
void sumOfSquares(Matrix& output, Matrix& label);
/// gradient of sumOfSquares.
void sumOfSquaresBp(Matrix& outputV, Matrix& label);
void smoothL1(Matrix& output, Matrix& label);
void smoothL1Bp(Matrix& output, Matrix& label);
void tanh(Matrix& output);
void tanhDerivative(Matrix& output);
void softrelu(Matrix& output);
void softreluDerivative(Matrix& output);
void scaledTanh(Matrix& output, real p1, real p2);
void print(std::ostream& os) const;
void print(std::ostream& os, size_t height, size_t width) const;
void printOneRow(std::ostream& os, size_t idx) const;
void paramReluForward(Matrix& data, Matrix& W);
void paramReluBackwardW(Matrix& oGrad, Matrix& data);
void paramReluBackwardDiff(Matrix& oGrad, Matrix& data, Matrix& W);
void check(std::ostream& os, Matrix& refMat, bool printDiff = true);
real getMin();
real getMax();
void randomizeUniform();
void classificationError(Matrix& output, IVector& label, size_t topkSize = 1);
void addByBitCode(size_t numClasses, const IVector& codes, const Matrix& vec);
void addByBitCodeBackward(size_t numClasses,
const IVector& codes,
Matrix& vec);
void mulByBitCode(size_t numClasses,
const IVector& codes,
const Matrix& mat,
const Matrix& input);
void mulByBitCodeBackwardWeight(size_t numClasses,
const IVector& codes,
Matrix& mat,
const Matrix& input);
void mulByBitCodeBackwardError(size_t numClasses,
const IVector& codes,
const Matrix& mat,
Matrix& input);
void sumByBitCode(size_t numClasses,
IVector& codes,
Matrix& sum,
real scaleSum);
void subByBitCode(size_t numClasses_, IVector& codes);
void multiBinaryLabelCrossEntropy(Matrix& output, Matrix& label);
void multiBinaryLabelCrossEntropyBp(Matrix& output, Matrix& label);
void classificationErrorMulti(Matrix& output, Matrix& label, real threshold);
void bilinearForward(const Matrix& in,
const size_t inImgH,
const size_t inImgW,
const size_t outImgH,
const size_t outImgW,
const size_t numChannels,
const real ratioH,
const real ratioW);
void bilinearBackward(const Matrix& out,
const size_t outImgH,
const size_t outImgW,
const size_t inImgH,
const size_t inImgW,
const size_t numChannels,
const real ratioH,
const real ratioW);
template <typename ExpressionType>
void operator=(const ExpressionType& expr) {
TensorCpuApply<real>(*this, expr);
}
};
class SharedCpuMatrix : public CpuMatrix {
public:
/* blockNum is number of partitions of the matrix */
SharedCpuMatrix(int blockNum, size_t height, size_t width, bool trans = false)
: CpuMatrix(height, width, trans) {
initShared(blockNum);
}
SharedCpuMatrix(
int blockNum, real* data, size_t height, size_t width, bool trans = false)
: CpuMatrix(data, height, width, trans) {
initShared(blockNum);
}
SharedCpuMatrix(int blockNum,
CpuMemHandlePtr dataHandle,
size_t height,
size_t width,
bool trans = false)
: CpuMatrix(dataHandle, height, width, trans) {
initShared(blockNum);
}
SharedCpuMatrix(CpuMemHandlePtr dataHandle,
size_t height,
size_t width,
bool trans = false)
: CpuMatrix(dataHandle, height, width, trans) {
initBlock(1);
}
~SharedCpuMatrix() {}
public:
virtual void mul(CpuSparseMatrix* a, CpuMatrix* b, real scaleAB, real scaleT);
virtual void add(Matrix& b, real p1, real p2);
virtual void add(real p1, real p2);
private:
using Matrix::mul;
void initShared(int blockNum);
void initBlock(int blockNum);
int blockNum_;
std::vector<std::unique_ptr<std::mutex>> blockLocks_;
ThreadLocal<CpuMatrixPtr> localBuf_;
ThreadLocal<std::vector<int>> localBufRows_;
ThreadLocal<std::vector<int>> blockSeq_;
};
typedef struct { unsigned int col; } sparse_non_value_t;
typedef struct {
unsigned int col;
float value;
} sparse_float_value_t;
} // namespace paddle
#include "ExecViaCpu.h"
| 30.294681 | 80 | 0.548653 | [
"vector"
] |
3256d53c643b6049d8a1e26417870feb5e2be8dc | 707 | h | C | Simple Game/Vector2f.h | DaanSander/Engine | ac71a40d2db7f045189ed30cb6deb61965adba85 | [
"MIT"
] | null | null | null | Simple Game/Vector2f.h | DaanSander/Engine | ac71a40d2db7f045189ed30cb6deb61965adba85 | [
"MIT"
] | null | null | null | Simple Game/Vector2f.h | DaanSander/Engine | ac71a40d2db7f045189ed30cb6deb61965adba85 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
namespace engine {
namespace math {
struct Vector2f {
float x, y;
Vector2f();
Vector2f(float x, float y);
Vector2f& add(const Vector2f& other);
Vector2f& subtract(const Vector2f& other);
Vector2f& devide(const Vector2f& other);
Vector2f& multiply(const Vector2f& other);
friend Vector2f& operator+(Vector2f& left, const Vector2f& right);
friend Vector2f& operator-(Vector2f& left, const Vector2f& right);
friend Vector2f& operator/(Vector2f& left, const Vector2f& right);
friend Vector2f& operator*(Vector2f& left, const Vector2f& right);
friend std::ostream& operator<<(std::ostream& stream, const Vector2f& vector);
};
}
} | 25.25 | 81 | 0.704385 | [
"vector"
] |
3256d603fad63752f6602cc2fe1d81e458d72b5c | 2,810 | h | C | Examples/include/Aspose.Pdf.Cpp/Text/TableAbsorber/AbsorbedTable.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/Aspose.Pdf.Cpp/Text/TableAbsorber/AbsorbedTable.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | Examples/include/Aspose.Pdf.Cpp/Text/TableAbsorber/AbsorbedTable.h | kashifiqb/Aspose.PDF-for-C | 13d49bba591c5704685820185741e64a462a5bdc | [
"MIT"
] | null | null | null | #pragma once
#include <system/shared_ptr.h>
#include <system/object.h>
#include <system/collections/list.h>
#include <system/collections/ilist.h>
#include <cstdint>
#include "Text/TableAbsorber/ITableElement.h"
#include "aspose_pdf_api_defs.h"
namespace Aspose { namespace Pdf { namespace Text { class TableAbsorber; } } }
namespace Aspose { namespace Pdf { namespace Text { class AbsorbedRow; } } }
namespace Aspose { namespace Pdf { class Rectangle; } }
namespace Aspose {
namespace Pdf {
namespace Text {
/// <summary>
/// Represents table that exist on the page
/// </summary>
class ASPOSE_PDF_SHARED_API AbsorbedTable : public Aspose::Pdf::Text::ITableElement
{
typedef AbsorbedTable ThisType;
typedef Aspose::Pdf::Text::ITableElement BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
FRIEND_FUNCTION_System_MakeObject;
friend class Aspose::Pdf::Text::TableAbsorber;
public:
/// <summary>
/// Gets readonly IList containing rows of the table
/// </summary>
System::SharedPtr<System::Collections::Generic::IList<System::SharedPtr<AbsorbedRow>>> get_RowList();
/// <summary>
/// Gets rectangle that describes position of the table on page
/// </summary>
System::SharedPtr<Aspose::Pdf::Rectangle> get_Rectangle();
/// <summary>
/// Gets number of the page containing this table
/// </summary>
int32_t get_PageNum();
protected:
/// <summary>
/// Gets number of the page containing this table
/// </summary>
void set_PageNum(int32_t value);
/// <summary>
/// Initializes new AbsorbedTable object with list of its rows
/// </summary>
/// <param name="rows">List collection of rows of the table</param>
AbsorbedTable(System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<AbsorbedRow>>> rows);
/// <summary>
/// Initializes new AbsorbedTable object with AbsorbedRow object
/// </summary>
/// <param name="row">Object representing first row of table</param>
AbsorbedTable(System::SharedPtr<AbsorbedRow> row);
/// <summary>
/// Adds AbsorbedRow object to the table
/// </summary>
/// <param name="row">Object representing row of table</param>
void AddRow(System::SharedPtr<AbsorbedRow> row);
/// <summary>
/// Please call this after adding of rows to recompute rectangle of the table
/// </summary>
void RecomputeRectangle();
System::Object::shared_members_type GetSharedMembers() override;
private:
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<AbsorbedRow>>> rows;
System::SharedPtr<Aspose::Pdf::Rectangle> rect;
int32_t pageNum;
};
} // namespace Text
} // namespace Pdf
} // namespace Aspose
| 30.215054 | 110 | 0.6879 | [
"object"
] |
325755c9f69cd051245cfd693f1182ef1d99004c | 20,249 | h | C | src/esp/assets/managers/AssetAttributesManager.h | wecacuee/habitat-sim | 973ab45c08e8b6d7e578db87b25700fbfdd10a02 | [
"MIT"
] | null | null | null | src/esp/assets/managers/AssetAttributesManager.h | wecacuee/habitat-sim | 973ab45c08e8b6d7e578db87b25700fbfdd10a02 | [
"MIT"
] | null | null | null | src/esp/assets/managers/AssetAttributesManager.h | wecacuee/habitat-sim | 973ab45c08e8b6d7e578db87b25700fbfdd10a02 | [
"MIT"
] | null | null | null | // Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#ifndef ESP_ASSETS_MANAGERS_ASSETATTRIBUTEMANAGER_H_
#define ESP_ASSETS_MANAGERS_ASSETATTRIBUTEMANAGER_H_
#include "AttributesManagerBase.h"
namespace esp {
namespace assets {
/**
* @brief The kinds of primitive modelled objects supported. Paired with
* Magnum::Primitive namespace objects
*/
enum class PrimObjTypes : uint32_t {
/**
* Primitive object corresponding to Magnum::Primitives::capsule3DSolid
*/
CAPSULE_SOLID,
/**
* Primitive object corresponding to Magnum::Primitives::capsule3DWireframe
*/
CAPSULE_WF,
/**
* Primitive object corresponding to Magnum::Primitives::coneSolid
*/
CONE_SOLID,
/**
* Primitive object corresponding to Magnum::Primitives::coneWireframe
*/
CONE_WF,
/**
* Primitive object corresponding to Magnum::Primitives::cubeSolid
*/
CUBE_SOLID,
/**
* Primitive object corresponding to Magnum::Primitives::cubeWireframe
*/
CUBE_WF,
/**
* Primitive object corresponding to Magnum::Primitives::cylinderSolid
*/
CYLINDER_SOLID,
/**
* Primitive object corresponding to Magnum::Primitives::cylinderWireframe
*/
CYLINDER_WF,
/**
* Primitive object corresponding to Magnum::Primitives::icosphereSolid
*/
ICOSPHERE_SOLID,
/**
* Primitive object corresponding to Magnum::Primitives::icosphereWireframe
*/
ICOSPHERE_WF,
/**
* Primitive object corresponding to Magnum::Primitives::uvSphereSolid
*/
UVSPHERE_SOLID,
/**
* Primitive object corresponding to Magnum::Primitives::uvSphereWireframe
*/
UVSPHERE_WF,
/**
* marker for no more primitive objects - add any new objects above this entry
*/
END_PRIM_OBJ_TYPES
};
namespace managers {
class AssetAttributesManager
: public AttributesManager<AbstractPrimitiveAttributes::ptr> {
public:
/**
* @brief Constant Map holding names of all Magnum 3D primitive classes
* supported, keyed by @ref PrimObjTypes enum entry. Note final entry is not
* a valid primitive.
*/
static const std::map<PrimObjTypes, const char*> PrimitiveNames3DMap;
AssetAttributesManager()
: AttributesManager<
AbstractPrimitiveAttributes::ptr>::AttributesManager() {
buildCtorFuncPtrMaps();
} // AssetAttributesManager::ctor
/**
* @brief Should only be called internally. Creates an instance of a primtive
* asset attributes template described by passed string. For primitive assets
* this is the Magnum primitive class name
*
* @param primClassName a string descriptor of the primitive asset
* template to be created, corresponding to the Magnum Primitive class
* name.
* @param registerTemplate whether to add this template to the library or
* not. If the user is going to edit this template, this should be false.
* @return a reference to the desired template.
*/
AbstractPrimitiveAttributes::ptr createAttributesTemplate(
const std::string& primClassName,
bool registerTemplate = true) override {
auto primAssetAttributes = buildPrimAttributes(primClassName);
if (nullptr != primAssetAttributes && registerTemplate) {
registerAttributesTemplate(primAssetAttributes, "");
}
return primAssetAttributes;
} // AssetAttributesManager::createAttributesTemplate
/**
* @brief Should only be called internally. Creates an instance of a primtive
* asset attributes template described by passed enum value. For primitive
* assets this mapes to the Magnum primitive class name
*
* @param primObjType an enum value denoting the class of the primitive to
* instantiate
* @param registerTemplate whether to add this template to the library or
* not. If the user is going to edit this template, this should be false.
* @return a reference to the desired template.
*/
AbstractPrimitiveAttributes::ptr createAttributesTemplate(
PrimObjTypes primObjType,
bool registerTemplate = true) {
auto primAssetAttributes = buildPrimAttributes(primObjType);
if (nullptr != primAssetAttributes && registerTemplate) {
registerAttributesTemplate(primAssetAttributes, "");
}
return primAssetAttributes;
} // AssetAttributesManager::createAttributesTemplate
/**
* @brief Get list of primitive asset template handles used as keys in @ref
* primitiveAssetTemplateLibrary_ related to passed primitive descriptor enum.
*
* @param primType Enum describing primitive type
* @param contains whether to search for keys containing, or not containing,
* @ref subStr
* @return list containing 0 or more string keys corresponding to templates in
* @ref primitiveAssetTemplateLibrary_ that contain the passed substring
*/
std::vector<std::string> getTemplateHandlesByPrimType(
PrimObjTypes primType,
bool contains = true) const {
if (primType == PrimObjTypes::END_PRIM_OBJ_TYPES) {
LOG(ERROR) << "AssetAttributesManager::getTemplateHandlesByPrimType : "
"Illegal primtitive type "
"name PrimObjTypes::END_PRIM_OBJ_TYPES. Aborting.";
return {};
}
std::string subStr = PrimitiveNames3DMap.at(primType);
return this->getTemplateHandlesBySubStringPerType(this->templateLibKeyByID_,
subStr, contains);
} // AssetAttributeManager::getTemplateHandlesByPrimType
/**
* @brief Return the default capsule template, either solid or wireframe.
* @param isWireFrame whether should be wireframe or solid template
* @return appropriately cast template
*/
CapsulePrimitiveAttributes::ptr getDefaultCapsuleTemplate(bool isWireFrame) {
std::string templateHndle;
if (isWireFrame) {
templateHndle = defaultPrimAttributeHandles_.at("capsule3DWireframe");
} else {
templateHndle = defaultPrimAttributeHandles_.at("capsule3DSolid");
}
return this->getTemplateCopyByHandle<CapsulePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getDefaultCapsuleTemplate
/**
* @brief Return the spedified capsule template.
* @param templateHndle The handle of the desired capsule template. Verifies
* that handle is to specified template type
* @return appropriately cast template, or nullptr if template handle
* incorrectly specified.
*/
CapsulePrimitiveAttributes::ptr getCapsuleTemplate(
const std::string& templateHndle) {
if (!verifyTemplateHandle(templateHndle, "capsule")) {
return nullptr;
}
return this->getTemplateCopyByHandle<CapsulePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getCapsuleTemplate
/**
* @brief Return the default cone template, either solid or wireframe.
* @param isWireFrame whether should be wireframe or solid template
* @return appropriately cast template
*/
ConePrimitiveAttributes::ptr getDefaultConeTemplate(bool isWireFrame) {
std::string templateHndle;
if (isWireFrame) {
templateHndle = defaultPrimAttributeHandles_.at("coneWireframe");
} else {
templateHndle = defaultPrimAttributeHandles_.at("coneSolid");
}
return this->getTemplateCopyByHandle<ConePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getDefaultConeTemplate
/**
* @brief Return the spedified cone template, either solid or wireframe.
* @param templateHndle The handle of the desired cone template. Verifies
* that handle is to specified template type
* @return appropriately cast template, or nullptr if template handle
* incorrectly specified.
*/
ConePrimitiveAttributes::ptr getConeTemplate(
const std::string& templateHndle) {
if (!verifyTemplateHandle(templateHndle, "cone")) {
return nullptr;
}
return this->getTemplateCopyByHandle<ConePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getConeTemplate
/**
* @brief Return the default cube template, either solid or wireframe.
* @param isWireFrame whether should be wireframe or solid template
* @return appropriately cast template
*/
CubePrimitiveAttributes::ptr getDefaultCubeTemplate(bool isWireFrame) {
std::string templateHndle;
if (isWireFrame) {
templateHndle = defaultPrimAttributeHandles_.at("cubeWireframe");
} else {
templateHndle = defaultPrimAttributeHandles_.at("cubeSolid");
}
return this->getTemplateCopyByHandle<CubePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getDefaultCubeTemplate
/**
* @brief Return the spedified cube template.
* @param templateHndle The handle of the desired cube template. Verifies
* that handle is to specified template type
* @return appropriately cast template, or nullptr if template handle
* incorrectly specified.
*/
CubePrimitiveAttributes::ptr getCubeTemplate(
const std::string& templateHndle) {
if (!verifyTemplateHandle(templateHndle, "cube")) {
return nullptr;
}
return this->getTemplateCopyByHandle<CubePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getCubeTemplate
/**
* @brief Return the default cylinder template, either solid or wireframe.
* @param isWireFrame whether should be wireframe or solid template
* @return appropriately cast template
*/
CylinderPrimitiveAttributes::ptr getDefaultCylinderTemplate(
bool isWireFrame) {
std::string templateHndle;
if (isWireFrame) {
templateHndle = defaultPrimAttributeHandles_.at("cylinderWireframe");
} else {
templateHndle = defaultPrimAttributeHandles_.at("cylinderSolid");
}
return this->getTemplateCopyByHandle<CylinderPrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getDefaultCylinderTemplate
/**
* @brief Return the spedified cylinder template.
* @param templateHndle The handle of the desired cylinder template. Verifies
* that handle is to specified template type
* @return appropriately cast template, or nullptr if template handle
* incorrectly specified.
*/
CylinderPrimitiveAttributes::ptr getCylinderTemplate(
const std::string& templateHndle) {
if (!verifyTemplateHandle(templateHndle, "cylinder")) {
return nullptr;
}
return this->getTemplateCopyByHandle<CylinderPrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getCylinderTemplate
/**
* @brief Return the default icosphere template, either solid or wireframe.
* @param isWireFrame whether should be wireframe or solid template
* @return appropriately cast template
*/
IcospherePrimitiveAttributes::ptr getDefaultIcosphereTemplate(
bool isWireFrame) {
std::string templateHndle;
if (isWireFrame) {
templateHndle = defaultPrimAttributeHandles_.at("icosphereWireframe");
} else {
templateHndle = defaultPrimAttributeHandles_.at("icosphereSolid");
}
return this->getTemplateCopyByHandle<IcospherePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getDefaultIcosphereTemplate
/**
* @brief Return the spedified icosphere template.
* @param templateHndle The handle of the desired icosphere template. Verifies
* that handle is to specified template type
* @return appropriately cast template, or nullptr if template handle
* incorrectly specified.
*/
IcospherePrimitiveAttributes::ptr getIcosphereTemplate(
const std::string& templateHndle) {
if (!verifyTemplateHandle(templateHndle, "icosphere")) {
return nullptr;
}
return this->getTemplateCopyByHandle<IcospherePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getIcosphereTemplate
/**
* @brief Return the default UVSphere template, either solid or wireframe.
* @param isWireFrame whether should be wireframe or solid template
* @return appropriately cast template
*/
UVSpherePrimitiveAttributes::ptr getDefaultUVSphereTemplate(
bool isWireFrame) {
std::string templateHndle;
if (isWireFrame) {
templateHndle = defaultPrimAttributeHandles_.at("uvSphereWireframe");
} else {
templateHndle = defaultPrimAttributeHandles_.at("uvSphereSolid");
}
return this->getTemplateCopyByHandle<UVSpherePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getDefaultUVSphereTemplate
/**
* @brief Return the spedified cube template.
* @param templateHndle The handle of the desired cube template. Verifies
* that handle is to specified template type
* @return appropriately cast template, or nullptr if template handle
* incorrectly specified.
*/
UVSpherePrimitiveAttributes::ptr getUVSphereTemplate(
const std::string& templateHndle) {
if (!verifyTemplateHandle(templateHndle, "uvSphere")) {
return nullptr;
}
return this->getTemplateCopyByHandle<UVSpherePrimitiveAttributes>(
templateHndle);
} // AssetAttributeManager::getUVSphereTemplate
protected:
/**
* @brief Verify that passed template handle describes attributes of type
* specified by passed primtive name (ie "cube", "capsule")
* @param templateHandle The handle to test.
* @param attrType Type of primitive the attributes owning templateHandle
* describe.
* @return If template handle describes template for objects of desired
* primitive class name
*/
bool verifyTemplateHandle(const std::string& templateHandle,
const std::string& attrType) {
if (std::string::npos == templateHandle.find(attrType)) {
LOG(ERROR) << "AssetAttributesManager::verifyTemplateHandle : Handle : "
<< templateHandle << " is not of appropriate type for desired "
<< attrType << " primitives. Aborting.";
return false;
}
return true;
} // AttributesManager::verifyTemplateHandle
/**
* @brief Add an @ref AbstractPrimitiveAttributes object to the @ref
* templateLibrary_.
*
* @param attributesTemplate The attributes template.
* @param ignored Not used for asset attributes templates - handle is derived
* by configuration.
* @return The index in the @ref templateLibrary_ of object
* template.
*/
int registerAttributesTemplateFinalize(
AbstractPrimitiveAttributes::ptr attributesTemplate,
const std::string& ignored = "") override;
/**
* @brief Whether template described by passed handle is read only, or can be
* deleted. Default primitive asset templates should not be removed.
* @param templateHandle the handle to the template to verify removability.
* Assumes template exists.
* @return Whether the template is read-only or not
*/
bool isTemplateReadOnly(const std::string& templateHandle) override {
for (auto handle : defaultTemplateNames) {
if (handle.compare(templateHandle) == 0) {
return true;
}
}
return false;
};
/**
* @brief Build an @ref AbstractPrimtiveAttributes object of type associated
* with passed class name
* @param primClassName Magnum::Primitives class name of primitive being
* constructed
*/
AbstractPrimitiveAttributes::ptr buildPrimAttributes(
const std::string& primClassName) {
if (primTypeConstructorMap_.count(primClassName) == 0) {
LOG(ERROR) << "AssetAttributesManager::buildPrimAttributes : No "
"primitive class"
<< primClassName << "exists in Magnum::Primitives. Aborting.";
return nullptr;
}
return (*this.*primTypeConstructorMap_[primClassName])();
} // AssetAttributeManager::buildPrimAttributes
/**
* @brief Build an @ref AbstractPrimtiveAttributes object of type associated
* with passed enum value, which maps to class name via @ref
* PrimitiveNames3DMap
*/
AbstractPrimitiveAttributes::ptr buildPrimAttributes(PrimObjTypes primType) {
if (primType == PrimObjTypes::END_PRIM_OBJ_TYPES) {
LOG(ERROR) << "AssetAttributesManager::buildPrimAttributes : Illegal "
"primtitive type name PrimObjTypes::END_PRIM_OBJ_TYPES. "
"Aborting.";
return nullptr;
}
return (*this.*primTypeConstructorMap_[PrimitiveNames3DMap.at(primType)])();
} // AssetAttributeManager::buildPrimAttributes
/**
* @brief Build an @ref AbstractPrimtiveAttributes object of type associated
* with passed enum value, which maps to class name via @ref
* PrimitiveNames3DMap
*/
AbstractPrimitiveAttributes::ptr buildPrimAttributes(int primTypeVal) {
if ((primTypeVal < 0) ||
(primTypeVal > static_cast<int>(PrimObjTypes::END_PRIM_OBJ_TYPES))) {
LOG(ERROR) << "AssetAttributesManager::buildPrimAttributes : Unknown "
"PrimObjTypes value requested :"
<< primTypeVal << ". Aborting";
return nullptr;
}
return (*this.*primTypeConstructorMap_[PrimitiveNames3DMap.at(
static_cast<PrimObjTypes>(primTypeVal))])();
} // AssetAttributeManager::buildPrimAttributes
/**
* @brief Build a shared pointer to the appropriate attributes for passed
* object type as defined in @ref PrimObjTypes, where each entry except @ref
* END_PRIM_OBJ_TYPES corresponds to a Magnum Primitive type
*/
template <typename T, bool isWireFrame, PrimObjTypes primitiveType>
AbstractPrimitiveAttributes::ptr createPrimAttributes() {
if (primitiveType == PrimObjTypes::END_PRIM_OBJ_TYPES) {
LOG(ERROR)
<< "AssetAttributeManager::createPrimAttributes : Cannot instantiate "
"AbstractPrimitiveAttributes object for "
"PrimObjTypes::END_PRIM_OBJ_TYPES. Aborting.";
return nullptr;
}
int idx = static_cast<int>(primitiveType);
return T::create(isWireFrame, idx, PrimitiveNames3DMap.at(primitiveType));
} // AssetAttributeManager::createPrimAttributes
/**
* @brief Any Assset-attributes-specific resetting that needs to happen on
* reset.
*/
void resetFinalize() override {
// build default AbstractPrimitiveAttributes objects - reset does not remove
// constructor mappings;
for (const std::pair<PrimObjTypes, const char*>& elem :
PrimitiveNames3DMap) {
if (elem.first == PrimObjTypes::END_PRIM_OBJ_TYPES) {
continue;
}
createAttributesTemplate(elem.second, true);
}
} // AssetAttributesManager::resetFinalize()
/**
* @brief This function will assign the appropriately configured function
* pointers for @ref createPrimAttributes calls for each type of
* supported primitive to the @ref primTypeConstructorMap, keyed by type of
* primtive
*/
void buildCtorFuncPtrMaps() override;
// ======== Typedefs and Instance Variables ========
/**
* @brief Define a map type referencing function pointers to @ref
* createPrimAttributes() keyed by string names of classes being
* instanced, as defined in @ref PrimNames3D
*/
typedef std::map<std::string,
AbstractPrimitiveAttributes::ptr (
AssetAttributesManager::*)()>
Map_Of_PrimTypeCtors;
/**
* @brief Map of function pointers to instantiate a primitive attributes
* object, keyed by the Magnum primitive class name as listed in @ref
* PrimNames3D. A primitive attributes object is instanced by accessing
* the approrpiate function pointer.
*/
Map_Of_PrimTypeCtors primTypeConstructorMap_;
/**
* @brief vector holding string template handles of all default primitive
* asset templates, to make sure they are never deleted.
*/
std::vector<std::string> defaultTemplateNames;
/**
* @brief Map relating primitive class name to default attributes template
* handle. There should always be a template for each of these handles.
*/
std::map<std::string, std::string> defaultPrimAttributeHandles_;
public:
ESP_SMART_POINTERS(AssetAttributesManager)
}; // AssetAttributesManager
} // namespace managers
} // namespace assets
} // namespace esp
#endif // ESP_ASSETS_MANAGERS_ASSETATTRIBUTEMANAGER_H_ | 38.20566 | 80 | 0.71727 | [
"object",
"vector",
"3d",
"solid"
] |
325a231191e3a56b6d0d87b842610ff4c37dee27 | 19,368 | h | C | Examples/PcapSplitter/IPPortSplitters.h | NUS-SNL/PcapPlusPlus | 79ce861c373e7f4e029552fe8df52f2663c879f0 | [
"Unlicense"
] | 1,856 | 2015-01-08T21:43:04.000Z | 2022-03-30T05:36:25.000Z | Examples/PcapSplitter/IPPortSplitters.h | NUS-SNL/PcapPlusPlus | 79ce861c373e7f4e029552fe8df52f2663c879f0 | [
"Unlicense"
] | 604 | 2015-01-05T22:31:11.000Z | 2022-03-31T16:22:39.000Z | Examples/PcapSplitter/IPPortSplitters.h | NUS-SNL/PcapPlusPlus | 79ce861c373e7f4e029552fe8df52f2663c879f0 | [
"Unlicense"
] | 537 | 2015-06-27T09:14:39.000Z | 2022-03-25T15:35:30.000Z | #pragma once
#include "Splitters.h"
#include "PacketUtils.h"
#include "SystemUtils.h"
/**
* A virtual abstract class for all splitters that split files by IP address or TCP/UDP port. Inherits from ValueBasedSplitter,
* so it already contains a mapping of IP/port to file number, a flow table, and supports max number of files or undefined
* number of files. This class arranges packets by TCP/UDP flows and for each flow lets the inherited classes determine
* to which file number this flow will be matched
*/
class IPPortSplitter : public ValueBasedSplitter
{
public:
/**
* C'tor for this class, does nothing but calling its ancestor
*/
IPPortSplitter(int maxFiles) : ValueBasedSplitter(maxFiles) {}
/**
* Implements Splitter's abstract method. This method takes a packet and decides to which flow it belongs to (can
* be an existing flow or a new flow). When opening new flows it uses a virtual abstract method that should be
* Implemented by inherited classes to determine to which file number the flow will be written to
*/
int getFileNumber(pcpp::Packet& packet, std::vector<int>& filesToClose)
{
// if it's not a TCP or UDP packet, put it in file #0
if (!packet.isPacketOfType(pcpp::TCP) && !packet.isPacketOfType(pcpp::UDP))
{
return 0;
}
// hash the 5-tuple and look for it in the flow table
uint32_t hash = pcpp::hash5Tuple(&packet);
if (m_FlowTable.find(hash) != m_FlowTable.end())
{
writingToFile(m_FlowTable[hash], filesToClose);
// if found it, follow the file number written in the hash record
return m_FlowTable[hash];
}
// if it's the first packet seen on this flow, try to guess the server port
if (packet.isPacketOfType(pcpp::TCP))
{
// extract TCP layer
pcpp::TcpLayer* tcpLayer = packet.getLayerOfType<pcpp::TcpLayer>();
if (tcpLayer != NULL)
{
uint16_t srcPort = tcpLayer->getSrcPort();
uint16_t dstPort = tcpLayer->getDstPort();
if (tcpLayer->getTcpHeader()->synFlag)
{
// SYN packet
if (!tcpLayer->getTcpHeader()->ackFlag)
{
m_FlowTable[hash] = getFileNumberForValue(getValue(packet, SYN, srcPort, dstPort), filesToClose);
return m_FlowTable[hash];
}
// SYN/ACK packet
else
{
m_FlowTable[hash] = getFileNumberForValue(getValue(packet, SYN_ACK, srcPort, dstPort), filesToClose);
return m_FlowTable[hash];
}
}
// Other TCP packet
else
{
m_FlowTable[hash] = getFileNumberForValue(getValue(packet, TCP_OTHER, srcPort, dstPort), filesToClose);
return m_FlowTable[hash];
}
}
}
else if (packet.isPacketOfType(pcpp::UDP))
{
// for UDP packets, decide the server port by the lower port
pcpp::UdpLayer* udpLayer = packet.getLayerOfType<pcpp::UdpLayer>();
if (udpLayer != NULL)
{
uint16_t srcPort = udpLayer->getSrcPort();
uint16_t dstPort = udpLayer->getDstPort();
m_FlowTable[hash] = getFileNumberForValue(getValue(packet, UDP, srcPort, dstPort), filesToClose);
return m_FlowTable[hash];
}
}
// if reached here, return 0
writingToFile(0, filesToClose);
return 0;
}
/**
* Re-implement Splitter's getFileName() method, this time with the IP/port value
*/
std::string getFileName(pcpp::Packet& packet, std::string outputPcapBasePath, int fileNumber)
{
// first set the base string as the outputPcapBasePath
std::string result = outputPcapBasePath;
// if it's not a TCP or UDP packet, put it in file #0
if (!packet.isPacketOfType(pcpp::TCP) && !packet.isPacketOfType(pcpp::UDP))
{
return result + "miscellaneous";
}
if (packet.isPacketOfType(pcpp::TCP))
{
// extract TCP layer
pcpp::TcpLayer* tcpLayer = packet.getLayerOfType<pcpp::TcpLayer>();
if (tcpLayer != NULL)
{
uint16_t srcPort = tcpLayer->getSrcPort();
uint16_t dstPort = tcpLayer->getDstPort();
if (tcpLayer->getTcpHeader()->synFlag)
{
// SYN packet
if (!tcpLayer->getTcpHeader()->ackFlag)
{
return result + getValueString(packet, SYN, srcPort, dstPort);
}
// SYN/ACK packet
else
{
return result + getValueString(packet, SYN_ACK, srcPort, dstPort);
}
}
// Other TCP packet
else
{
return result + getValueString(packet, TCP_OTHER, srcPort, dstPort);
}
}
}
else if (packet.isPacketOfType(pcpp::UDP))
{
// for UDP packets, decide the server port by the lower port
pcpp::UdpLayer* udpLayer = packet.getLayerOfType<pcpp::UdpLayer>();
if (udpLayer != NULL)
{
uint16_t srcPort = udpLayer->getSrcPort();
uint16_t dstPort = udpLayer->getDstPort();
return result + getValueString(packet, UDP, srcPort, dstPort);
}
}
// if reached here, return 'miscellaneous'
return result + "miscellaneous";
}
protected:
/**
* An enum for TCP/UDP packet type: can be either TCP-SYN, TCP-SYN/ACK, Other TCP packet of UDP packet
*/
enum PacketType
{
SYN,
SYN_ACK,
TCP_OTHER,
UDP
};
/**
* This is the virtual abstract method that needs to be implemented by inherited classes. It gets the packet,
* the packet type, and the source and dest ports and should return the value by which file will be split.
* For example: if files should be split by client IP, this method should extract the client IP and return it as
* uint32_t value, or if files should be split by server port, this method should extract the server port and
* return it as uint32_t value
*/
virtual uint32_t getValue(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort) = 0;
/**
* This is a virtual abstract method that needs to be implemented by inherited classes. It gets the packet,
* packet type, src and dest ports and return the value by which the file will be split, but in its string format.
* For example: if the file is split by client-ip the expected result is the client-ip string ("a.b.c.d")
*/
virtual std::string getValueString(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort) = 0;
/**
* An auxiliary method for extracting packet's IPv4/IPv6 source address hashed as 4 bytes uint32_t value
*/
uint32_t getSrcIPValue(pcpp::Packet& packet)
{
if (packet.isPacketOfType(pcpp::IPv4))
return packet.getLayerOfType<pcpp::IPv4Layer>()->getSrcIPv4Address().toInt();
else if (packet.isPacketOfType(pcpp::IPv6))
return pcpp::fnvHash((uint8_t*)packet.getLayerOfType<pcpp::IPv6Layer>()->getSrcIPv6Address().toBytes(), 16);
else
return 0;
}
/**
* An auxiliary method for extracting packet's IPv4/IPv6 dest address hashed as 4 bytes uint32_t value
*/
uint32_t getDstIPValue(pcpp::Packet& packet)
{
if (packet.isPacketOfType(pcpp::IPv4))
return packet.getLayerOfType<pcpp::IPv4Layer>()->getDstIPv4Address().toInt();
else if (packet.isPacketOfType(pcpp::IPv6))
return pcpp::fnvHash((uint8_t*)packet.getLayerOfType<pcpp::IPv6Layer>()->getDstIPv6Address().toBytes(), 16);
else
return 0;
}
/**
* An auxiliary method for extracting packet's IPv4/IPv6 source address as string
*/
std::string getSrcIPString(pcpp::Packet& packet)
{
if (packet.isPacketOfType(pcpp::IP))
return packet.getLayerOfType<pcpp::IPLayer>()->getSrcIPAddress().toString();
return "miscellaneous";
}
/**
* An auxiliary method for extracting packet's IPv4/IPv6 dest address string
*/
std::string getDstIPString(pcpp::Packet& packet)
{
if (packet.isPacketOfType(pcpp::IP))
return packet.getLayerOfType<pcpp::IPLayer>()->getDstIPAddress().toString();
return "miscellaneous";
}
/**
* An auxiliary method to indicate whether an IPv4/IPv6 source address is multicast or not
*/
bool isSrcIPMulticast(pcpp::Packet& packet)
{
if (packet.isPacketOfType(pcpp::IP))
return packet.getLayerOfType<pcpp::IPLayer>()->getSrcIPAddress().isMulticast();
return false;
}
/**
* An auxiliary method to indicate whether an IPv4/IPv6 dest address is multicast or not
*/
bool isDstIPMulticast(pcpp::Packet& packet)
{
if (packet.isPacketOfType(pcpp::IP))
return packet.getLayerOfType<pcpp::IPLayer>()->getDstIPAddress().isMulticast();
return false;
}
/**
* An auxiliary method for replacing '.' and ':' in IPv4/IPv6 addresses with '-'
*/
std::string hyphenIP(std::string ipVal)
{
// for IPv4 - replace '.' with '-'
int loc = ipVal.find(".");
while (loc >= 0)
{
ipVal.replace(loc, 1, "-");
loc = ipVal.find(".");
}
// for IPv6 - replace ':' with '-'
loc = ipVal.find(":");
while (loc >= 0)
{
ipVal.replace(loc, 1, "-");
loc = ipVal.find(":");
}
return ipVal;
}
};
/**
* Splits a pcap file by client IP. This means that all flows with a certain client IP will be written to the same
* file. The client IP for each flow is determined as follows: 1) if it's a TCP flow and we have the SYN packet - the
* client IP is the source IP of the SYN packet 2) if it's a TCP flow and we only have the SYN/ACK packet - the
* client IP is the dest IP of the SYN/ACK packet 3) if it's a partial TCP flow and don't have the SYN or SYN/ACK packets,
* the client IP will be determined by the port: the higher port is considered the client side 4) if it's a UDP multicast
* flow - the client IP will be determined by the port: the port corresponding to the multicast address is the client side
* 5) If it's a non-multicast UDP flow - the client IP will be determined by the port: the higher port is considered the
* client side
*/
class ClientIPSplitter : public IPPortSplitter
{
public:
/**
* C'tor for this class, does nothing but calling its ancestor
*/
ClientIPSplitter(int maxFiles) : IPPortSplitter(maxFiles) {}
protected:
/**
* Implementation of the abstract method of IPPortSplitter. This method returns the client IP for a certain flow
* by the logic written at the description of this class
*/
uint32_t getValue(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
switch (packetType)
{
case SYN:
return getSrcIPValue(packet);
case SYN_ACK:
return getDstIPValue(packet);
case UDP:
if(isSrcIPMulticast(packet)) return getSrcIPValue(packet);
else if(isDstIPMulticast(packet)) return getDstIPValue(packet);
else return srcPort >= dstPort ? getSrcIPValue(packet) : getDstIPValue(packet);
// other TCP packet
default:
if (srcPort >= dstPort)
return getSrcIPValue(packet);
else
return getDstIPValue(packet);
}
}
std::string getValueString(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
std::string prefix = "client-ip-";
switch (packetType)
{
case SYN:
return prefix + hyphenIP(getSrcIPString(packet));
case SYN_ACK:
return prefix + hyphenIP(getDstIPString(packet));
case UDP:
if(isSrcIPMulticast(packet)) return prefix + hyphenIP(getSrcIPString(packet));
else if(isDstIPMulticast(packet)) return prefix + hyphenIP(getDstIPString(packet));
else return srcPort >= dstPort ? prefix + hyphenIP(getSrcIPString(packet)) : prefix + hyphenIP(getDstIPString(packet));
// other TCP packet
default:
if (srcPort >= dstPort)
return prefix + hyphenIP(getSrcIPString(packet));
else
return prefix + hyphenIP(getDstIPString(packet));
}
}
};
/**
* Splits a pcap file by server IP. This means that all flows with a certain server IP will be written to the same
* file. The server IP for each flow is determined as follows: 1) if it's a TCP flow and we have the SYN packet - the
* server IP is the dest IP of the SYN packet 2) if it's a TCP flow and we only have the SYN/ACK packet - the
* server IP is the source IP of the SYN/ACK packet 3) if it's a partial TCP flow and don't have the SYN or SYN/ACK packets,
* the server IP will be determined by the port: the lower port is considered the server side 4) if it's a multicast UDP flow -
* the server IP will be determined by the port: the port corresponding to the non-multicast address is consdered as server side
* 5) if i's a non-multicast UDP flow - the server IP will be determined by the port: the lower port is considered the
* server side
*/
class ServerIPSplitter : public IPPortSplitter
{
public:
/**
* C'tor for this class, does nothing but calling its ancestor
*/
ServerIPSplitter(int maxFiles) : IPPortSplitter(maxFiles) {}
protected:
/**
* Implementation of the abstract method of IPPortSplitter. This method returns the server IP for a certain flow
* by the logic written at the description of this class
*/
uint32_t getValue(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
switch (packetType)
{
case SYN:
return getDstIPValue(packet);
case SYN_ACK:
return getSrcIPValue(packet);
case UDP:
if(isSrcIPMulticast(packet)) return getDstIPValue(packet);
else if(isDstIPMulticast(packet)) return getSrcIPValue(packet);
else return srcPort >= dstPort ? getDstIPValue(packet) : getSrcIPValue(packet);
// other TCP packet
default:
if (srcPort >= dstPort)
return getDstIPValue(packet);
else
return getSrcIPValue(packet);
}
}
std::string getValueString(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
std::string prefix = "server-ip-";
switch (packetType)
{
case SYN:
return prefix + hyphenIP(getDstIPString(packet));
case SYN_ACK:
return prefix + hyphenIP(getSrcIPString(packet));
case UDP:
if(isSrcIPMulticast(packet)) return prefix + hyphenIP(getDstIPString(packet));
else if(isDstIPMulticast(packet)) return prefix + hyphenIP(getSrcIPString(packet));
else return srcPort >= dstPort ? prefix + hyphenIP(getDstIPString(packet)) : prefix + hyphenIP(getSrcIPString(packet));
// other TCP packet
default:
if (srcPort >= dstPort)
return prefix + hyphenIP(getDstIPString(packet));
else
return prefix + hyphenIP(getSrcIPString(packet));
}
}
};
/**
* Splits a pcap file by server port (most of the time is similar to protocol). This means that all flows with a certain
* server port will be written to the same file. The server port for each flow is determined as follows: 1) if it's a TCP
* flow and we have the SYN packet - the server port is the dest port of the SYN packet 2) if it's a TCP flow and we only
* have the SYN/ACK packet - the server port is the source port of the SYN/ACK packet 3) if it's a partial TCP flow and
* we don't have the SYN or SYN/ACK packets, the server port will be determined by the port: the lower port is considered
* the server side 4) if it's a UDP multicast flow - if the sourceIP is a multicast address, the dest port is considered
* as a server port, otherwise if the destIP is a multicast address, the source port is considered as a server port 5) if
* it's a UDP flow - the server port will be determined by the port: the lower port is considered as server port
*/
class ServerPortSplitter : public IPPortSplitter
{
public:
/**
* C'tor for this class, does nothing but calling its ancestor
*/
ServerPortSplitter(int maxFiles) : IPPortSplitter(maxFiles) {}
protected:
/**
* Implementation of the abstract method of IPPortSplitter. This method returns the server port for a certain flow
* by the logic written at the description of this class
*/
uint32_t getValue(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
switch (packetType)
{
case SYN:
return dstPort;
case SYN_ACK:
return srcPort;
case UDP:
if(isSrcIPMulticast(packet)) return dstPort;
else if(isDstIPMulticast(packet)) return srcPort;
else return std::min<uint16_t>(srcPort, dstPort);
// other TCP packet
default:
return std::min<uint16_t>(srcPort, dstPort);
}
}
std::string getValueString(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
std::string prefix = "server-port-";
uint16_t res = 0;
switch (packetType)
{
case SYN:
res = dstPort;
break;
case SYN_ACK:
res = srcPort;
break;
case UDP:
if(isSrcIPMulticast(packet)) res = dstPort;
else if(isDstIPMulticast(packet)) res = srcPort;
else res = std::min<uint16_t>(srcPort, dstPort);
break;
// other TCP packet
default:
res = std::min<uint16_t>(srcPort, dstPort);
break;
}
std::ostringstream sstream;
sstream << res;
return prefix + sstream.str();
}
};
/**
* Splits a pcap file by server client (most of the time is similar to protocol). This means that all flows with a certain
* client port will be written to the same file. The client port for each flow is determined as follows: 1) if it's a TCP
* flow and we have the SYN packet - the client port is the source port of the SYN packet 2) if it's a TCP flow and we only
* have the SYN/ACK packet - the client port is the dest port of the SYN/ACK packet 3) if it's a partial TCP flow and
* we don't have the SYN or SYN/ACK packets, the server port will be determined by the port: the higher port is considered
* the client side 4) if it's a UDP multicast flow - if the sourceIP is a multicast address, the source port is considered
* as a client port, otherwise if the destIP is a multicast address, the dest port is considered as a client port 5) if
* it's a UDP flow - the client port will be determined by the port: the higher port is considered as client port
*/
class ClientPortSplitter : public IPPortSplitter
{
public:
/**
* C'tor for this class, does nothing but calling its ancestor
*/
ClientPortSplitter(int maxFiles) : IPPortSplitter(maxFiles) {}
protected:
/**
* Implementation of the abstract method of IPPortSplitter. This method returns the client port for a certain flow
* by the logic written at the description of this class
*/
uint32_t getValue(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
switch (packetType)
{
case SYN:
return srcPort;
case SYN_ACK:
return dstPort;
case UDP:
if(isSrcIPMulticast(packet)) return srcPort;
else if(isDstIPMulticast(packet)) return dstPort;
else return std::max<uint16_t>(srcPort, dstPort);
// other TCP packet
default:
return std::max<uint16_t>(srcPort, dstPort);
}
}
std::string getValueString(pcpp::Packet& packet, PacketType packetType, uint16_t srcPort, uint16_t dstPort)
{
std::string prefix = "client-port-";
uint16_t res = 0;
switch (packetType)
{
case SYN:
res = srcPort;
break;
case SYN_ACK:
res = dstPort;
break;
case UDP:
if(isSrcIPMulticast(packet)) res = srcPort;
else if(isDstIPMulticast(packet)) res = dstPort;
else res = std::max<uint16_t>(srcPort, dstPort);
break;
// other TCP packet
default:
res = std::max<uint16_t>(srcPort, dstPort);
break;
}
std::ostringstream sstream;
sstream << res;
return prefix + sstream.str();
}
};
| 33.801047 | 129 | 0.687371 | [
"vector"
] |
325d8b6704b345fb4a053a2c7e392f4e0bef6510 | 5,573 | h | C | src/Disks/DiskDecorator.h | metahys/ClickHouse | 74f5301225b0870d7cd3f3bed93312962aece3cd | [
"Apache-2.0"
] | 1 | 2019-07-04T22:46:28.000Z | 2019-07-04T22:46:28.000Z | src/Disks/DiskDecorator.h | metahys/ClickHouse | 74f5301225b0870d7cd3f3bed93312962aece3cd | [
"Apache-2.0"
] | null | null | null | src/Disks/DiskDecorator.h | metahys/ClickHouse | 74f5301225b0870d7cd3f3bed93312962aece3cd | [
"Apache-2.0"
] | 1 | 2020-05-28T07:29:23.000Z | 2020-05-28T07:29:23.000Z | #pragma once
#include "Disks/IDisk.h"
namespace DB
{
/** Forwards all methods to another disk.
* Methods can be overridden by descendants.
*/
class DiskDecorator : public IDisk
{
public:
explicit DiskDecorator(const DiskPtr & delegate_);
const String & getName() const override;
ReservationPtr reserve(UInt64 bytes) override;
~DiskDecorator() override = default;
const String & getPath() const override;
UInt64 getTotalSpace() const override;
UInt64 getAvailableSpace() const override;
UInt64 getUnreservedSpace() const override;
UInt64 getKeepingFreeSpace() const override;
bool exists(const String & path) const override;
bool isFile(const String & path) const override;
bool isDirectory(const String & path) const override;
size_t getFileSize(const String & path) const override;
void createDirectory(const String & path) override;
void createDirectories(const String & path) override;
void clearDirectory(const String & path) override;
void moveDirectory(const String & from_path, const String & to_path) override;
DiskDirectoryIteratorPtr iterateDirectory(const String & path) override;
void createFile(const String & path) override;
void moveFile(const String & from_path, const String & to_path) override;
void replaceFile(const String & from_path, const String & to_path) override;
void copy(const String & from_path, const std::shared_ptr<IDisk> & to_disk, const String & to_path) override;
void copyDirectoryContent(const String & from_dir, const std::shared_ptr<IDisk> & to_disk, const String & to_dir) override;
void listFiles(const String & path, std::vector<String> & file_names) override;
std::unique_ptr<ReadBufferFromFileBase> readFile(
const String & path,
const ReadSettings & settings,
std::optional<size_t> read_hint,
std::optional<size_t> file_size) const override;
std::unique_ptr<WriteBufferFromFileBase> writeFile(
const String & path,
size_t buf_size,
WriteMode mode,
const WriteSettings & settings) override;
void removeFile(const String & path) override;
void removeFileIfExists(const String & path) override;
void removeDirectory(const String & path) override;
void removeRecursive(const String & path) override;
void removeSharedFile(const String & path, bool keep_s3) override;
void removeSharedRecursive(const String & path, bool keep_all_batch_data, const NameSet & file_names_remove_metadata_only) override;
void removeSharedFiles(const RemoveBatchRequest & files, bool keep_all_batch_data, const NameSet & file_names_remove_metadata_only) override;
void setLastModified(const String & path, const Poco::Timestamp & timestamp) override;
Poco::Timestamp getLastModified(const String & path) override;
void setReadOnly(const String & path) override;
void createHardLink(const String & src_path, const String & dst_path) override;
void truncateFile(const String & path, size_t size) override;
int open(const String & path, mode_t mode) const;
void close(int fd) const;
void sync(int fd) const;
String getUniqueId(const String & path) const override { return delegate->getUniqueId(path); }
bool checkUniqueId(const String & id) const override { return delegate->checkUniqueId(id); }
DiskType getType() const override { return delegate->getType(); }
bool isRemote() const override { return delegate->isRemote(); }
bool supportZeroCopyReplication() const override { return delegate->supportZeroCopyReplication(); }
void onFreeze(const String & path) override;
SyncGuardPtr getDirectorySyncGuard(const String & path) const override;
void shutdown() override;
void startup() override;
void applyNewSettings(const Poco::Util::AbstractConfiguration & config, ContextPtr context, const String & config_prefix, const DisksMap & map) override;
String getCacheBasePath() const override { return delegate->getCacheBasePath(); }
std::vector<String> getRemotePaths(const String & path) const override { return delegate->getRemotePaths(path); }
void getRemotePathsRecursive(const String & path, std::vector<LocalPathWithRemotePaths> & paths_map) override { return delegate->getRemotePathsRecursive(path, paths_map); }
DiskPtr getMetadataDiskIfExistsOrSelf() override { return delegate->getMetadataDiskIfExistsOrSelf(); }
std::unordered_map<String, String> getSerializedMetadata(const std::vector<String> & file_paths) const override { return delegate->getSerializedMetadata(file_paths); }
UInt32 getRefCount(const String & path) const override { return delegate->getRefCount(path); }
protected:
Executor & getExecutor() override;
DiskPtr delegate;
};
/// TODO: Current reservation mechanism leaks IDisk abstraction details.
/// This hack is needed to return proper disk pointer (wrapper instead of implementation) from reservation object.
class ReservationDelegate : public IReservation
{
public:
ReservationDelegate(ReservationPtr delegate_, DiskPtr wrapper_) : delegate(std::move(delegate_)), wrapper(wrapper_) { }
UInt64 getSize() const override { return delegate->getSize(); }
UInt64 getUnreservedSpace() const override { return delegate->getUnreservedSpace(); }
DiskPtr getDisk(size_t) const override { return wrapper; }
Disks getDisks() const override { return {wrapper}; }
void update(UInt64 new_size) override { delegate->update(new_size); }
private:
ReservationPtr delegate;
DiskPtr wrapper;
};
}
| 50.207207 | 176 | 0.747353 | [
"object",
"vector"
] |
326282b877b6c60c1a3051ea9f3cb8676ff5c6e4 | 6,058 | c | C | src/third_party/wiredtiger/test/csuite/wt1965_col_efficiency/main.c | SunguckLee/real-mongodb | fef0e44fafc6d3709a84101327e7d2f54dd18d88 | [
"Apache-2.0"
] | 4 | 2018-02-06T01:53:12.000Z | 2018-02-20T01:47:36.000Z | src/third_party/wiredtiger/test/csuite/wt1965_col_efficiency/main.c | SunguckLee/real-mongodb | fef0e44fafc6d3709a84101327e7d2f54dd18d88 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/csuite/wt1965_col_efficiency/main.c | SunguckLee/real-mongodb | fef0e44fafc6d3709a84101327e7d2f54dd18d88 | [
"Apache-2.0"
] | 3 | 2018-02-06T01:53:18.000Z | 2021-07-28T09:48:15.000Z | /*-
* Public Domain 2014-2016 MongoDB, Inc.
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "test_util.h"
/*
* JIRA ticket reference: WT-1965
* Test case description: The reported issue was that column store tables
* exhibit high CPU usage when populated with sparse record IDs.
* Failure mode: It isn't simple to make this test case failure explicit since
* it is demonstrating an inefficiency rather than a correctness bug.
*/
/* If changing field count also need to change set_value and get_value calls */
#define NR_FIELDS 8
#define NR_OBJECTS 100
#define NR_THREADS 4
static uint64_t g_ts = 0;
/*
* Each thread inserts a set of keys into the record store database. The keys
* are generated in such a way that there are large gaps in the key range.
*/
static void *
thread_func(void *arg)
{
TEST_OPTS *opts;
WT_CURSOR *cursor, *idx_cursor;
WT_SESSION *session;
uint64_t i, ins_rotor, ins_thr_idx, thr_idx, ts;
uint64_t *obj_data;
opts = (TEST_OPTS *)arg;
thr_idx = __wt_atomic_fetch_addv64(&opts->next_threadid, 1);
ts = g_ts;
obj_data = dcalloc(
(NR_OBJECTS/NR_THREADS + 1) * NR_FIELDS, sizeof(*obj_data));
testutil_check(opts->conn->open_session(
opts->conn, NULL, NULL, &session));
testutil_check(session->open_cursor(
session, opts->uri, NULL, NULL, &cursor));
testutil_check(session->open_cursor(
session, "table:index", NULL, NULL, &idx_cursor));
for (ins_rotor = 1; ins_rotor < 10; ++ins_rotor) {
for (ins_thr_idx = thr_idx, i = 0; ins_thr_idx < NR_OBJECTS;
ins_thr_idx += NR_THREADS, i += NR_FIELDS) {
testutil_check(
session->begin_transaction(session, "sync=false"));
cursor->set_key(cursor, ins_thr_idx << 40 | ins_rotor);
cursor->set_value(cursor, ts,
obj_data[i+0], obj_data[i+1], obj_data[i+2],
obj_data[i+3], obj_data[i+4], obj_data[i+5],
obj_data[i+6], obj_data[i+7]);
testutil_check(cursor->insert(cursor));
idx_cursor->set_key(
idx_cursor, ins_thr_idx << 40 | ts);
idx_cursor->set_value(idx_cursor, ins_rotor);
testutil_check(idx_cursor->insert(idx_cursor));
testutil_check(
session->commit_transaction(session, NULL));
/* change object fields */
++obj_data[i + ((ins_thr_idx + ins_rotor) % NR_FIELDS)];
++obj_data[i +
((ins_thr_idx + ins_rotor + 1) % NR_FIELDS)];
++g_ts;
/* 5K updates/sec */
(void)usleep(1000000ULL * NR_THREADS / 5000);
}
}
testutil_check(session->close(session, NULL));
free(obj_data);
return (NULL);
}
int
main(int argc, char *argv[])
{
TEST_OPTS *opts, _opts;
WT_CURSOR *cursor;
WT_SESSION *session;
pthread_t thr[NR_THREADS];
size_t t;
uint64_t f[NR_FIELDS], r, ts;
int i, ret;
char table_format[256];
opts = &_opts;
memset(opts, 0, sizeof(*opts));
testutil_check(testutil_parse_opts(argc, argv, opts));
testutil_make_work_dir(opts->home);
testutil_check(wiredtiger_open(opts->home, NULL,
"create,cache_size=1G,checkpoint=(wait=30),"
"eviction_trigger=80,eviction_target=64,eviction_dirty_target=65,"
"log=(enabled,file_max=10M),"
"transaction_sync=(enabled=true,method=none)", &opts->conn));
testutil_check(opts->conn->open_session(
opts->conn, NULL, NULL, &session));
testutil_check(__wt_snprintf(
table_format, sizeof(table_format), "key_format=r,value_format="));
for (i = 0; i < NR_FIELDS; i++)
strcat(table_format, "Q");
/* recno -> timestamp + NR_FIELDS * Q */
testutil_check(session->create(
session, opts->uri, table_format));
/* timestamp -> recno */
testutil_check(session->create(session,
"table:index", "key_format=Q,value_format=Q"));
testutil_check(session->close(session, NULL));
for (t = 0; t < NR_THREADS; ++t)
testutil_check(pthread_create(
&thr[t], NULL, thread_func, (void *)opts));
for (t = 0; t < NR_THREADS; ++t)
(void)pthread_join(thr[t], NULL);
testutil_check(opts->conn->open_session(
opts->conn, NULL, NULL, &session));
/* recno -> timestamp + NR_FIELDS * Q */
testutil_check(session->create(session, opts->uri, table_format));
testutil_check(session->open_cursor(
session, opts->uri, NULL, NULL, &cursor));
while ((ret = cursor->next(cursor)) == 0) {
testutil_check(cursor->get_key(cursor, &r));
testutil_check(cursor->get_value(cursor, &ts,
&f[0], &f[1], &f[2], &f[3], &f[4], &f[5], &f[6], &f[7]));
if (!opts->verbose)
continue;
printf("(%" PRIu64 ",%llu)\t\t%" PRIu64,
(r >> 40), r & ((1ULL << 40) - 1), ts);
for (i = 0; i < NR_FIELDS; i++)
printf("\t%" PRIu64, f[i]);
printf("\n");
}
testutil_assert(ret == WT_NOTFOUND);
testutil_cleanup(opts);
return (EXIT_SUCCESS);
}
| 32.745946 | 80 | 0.671839 | [
"object"
] |
3263e484c698a8d660366d2439c3f5998617b090 | 7,768 | h | C | samples/utils/cl_utils.h | piepernh/pti-gpu | b82f4a31db42ee09d49ae513986cc725c9a44844 | [
"MIT"
] | null | null | null | samples/utils/cl_utils.h | piepernh/pti-gpu | b82f4a31db42ee09d49ae513986cc725c9a44844 | [
"MIT"
] | null | null | null | samples/utils/cl_utils.h | piepernh/pti-gpu | b82f4a31db42ee09d49ae513986cc725c9a44844 | [
"MIT"
] | null | null | null | //==============================================================
// Copyright (C) Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#ifndef PTI_SAMPLES_UTILS_CL_UTILS_H_
#define PTI_SAMPLES_UTILS_CL_UTILS_H_
#include <string.h>
#include <string>
#include <vector>
#include <CL/cl.h>
#include "utils.h"
namespace utils {
namespace cl {
inline cl_device_id GetIntelDevice(cl_device_type type) {
cl_int status = CL_SUCCESS;
cl_uint platform_count = 0;
status = clGetPlatformIDs(0, nullptr, &platform_count);
if (status != CL_SUCCESS || platform_count == 0) return nullptr;
std::vector<cl_platform_id> platform_list(platform_count, nullptr);
status = clGetPlatformIDs(platform_count, platform_list.data(), nullptr);
PTI_ASSERT(status == CL_SUCCESS);
cl_device_id target = nullptr;
for (cl_uint i = 0; i < platform_count; ++i) {
cl_uint device_count = 0;
status = clGetDeviceIDs(platform_list[i], type, 0, nullptr,
&device_count);
if (status != CL_SUCCESS || device_count == 0) continue;
std::vector<cl_device_id> device_list(device_count, nullptr);
status = clGetDeviceIDs(platform_list[i], type, device_count,
device_list.data(), nullptr);
PTI_ASSERT(status == CL_SUCCESS);
char vendor[MAX_STR_SIZE] = { 0 };
for (cl_uint j = 0; j < device_count; ++j) {
status = clGetDeviceInfo(device_list[j], CL_DEVICE_VENDOR,
MAX_STR_SIZE, vendor, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
if (strstr(vendor, "Intel") != nullptr) {
target = device_list[j];
break;
}
}
if (target != nullptr) {
break;
}
}
return target;
}
inline std::string GetKernelName(cl_kernel kernel) {
PTI_ASSERT(kernel != nullptr);
char name[MAX_STR_SIZE] = { 0 };
cl_int status = CL_SUCCESS;
status = clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME,
MAX_STR_SIZE, name, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return name;
}
inline std::string GetDeviceName(cl_device_id device) {
PTI_ASSERT(device != nullptr);
char name[MAX_STR_SIZE] = { 0 };
cl_int status = clGetDeviceInfo(
device, CL_DEVICE_NAME, MAX_STR_SIZE, name, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return name;
}
inline cl_device_type GetDeviceType(cl_device_id device) {
PTI_ASSERT(device != nullptr);
cl_device_type type = CL_DEVICE_TYPE_ALL;
cl_int status = clGetDeviceInfo(
device, CL_DEVICE_TYPE, sizeof(type), &type, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
PTI_ASSERT(type != CL_DEVICE_TYPE_ALL);
return type;
}
inline cl_program GetProgram(cl_kernel kernel) {
PTI_ASSERT(kernel != nullptr);
cl_int status = CL_SUCCESS;
cl_program program = nullptr;
status = clGetKernelInfo(kernel, CL_KERNEL_PROGRAM, sizeof(cl_program),
&program, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return program;
}
inline cl_context GetContext(cl_kernel kernel) {
PTI_ASSERT(kernel != nullptr);
cl_int status = CL_SUCCESS;
cl_context context = nullptr;
status = clGetKernelInfo(kernel, CL_KERNEL_CONTEXT, sizeof(cl_context),
&context, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return context;
}
inline std::vector<cl_device_id> GetDeviceList(cl_program program) {
PTI_ASSERT(program != nullptr);
cl_int status = CL_SUCCESS;
cl_uint device_count = 0;
status = clGetProgramInfo(program, CL_PROGRAM_NUM_DEVICES, sizeof(cl_uint),
&device_count, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
if (device_count == 0) {
return std::vector<cl_device_id>();
}
std::vector<cl_device_id> device_list(device_count);
status = clGetProgramInfo(program, CL_PROGRAM_DEVICES,
device_count * sizeof(cl_device_id),
device_list.data(), nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return device_list;
}
inline cl_queue_properties* EnableQueueProfiling(
const cl_queue_properties* props) {
cl_queue_properties* props_with_prof = nullptr;
if (props == nullptr) {
props_with_prof = new cl_queue_properties[3];
props_with_prof[0] = CL_QUEUE_PROPERTIES;
props_with_prof[1] = CL_QUEUE_PROFILING_ENABLE;
props_with_prof[2] = 0;
} else {
int queue_props_id = -1;
int props_count = 0;
while (props[props_count] != 0) {
if (props[props_count] == CL_QUEUE_PROPERTIES) {
queue_props_id = props_count;
++props_count;
} else if (props[props_count] == CL_QUEUE_SIZE) {
++props_count;
}
++props_count;
}
PTI_ASSERT(props[props_count] == 0);
if (queue_props_id >= 0 && queue_props_id + 1 < props_count) {
props_with_prof = new cl_queue_properties[props_count + 1];
for (int i = 0; i < props_count; ++i) {
props_with_prof[i] = props[i];
}
props_with_prof[queue_props_id + 1] |=
static_cast<unsigned long>(CL_QUEUE_PROFILING_ENABLE);
props_with_prof[props_count] = 0;
} else {
props_with_prof = new cl_queue_properties[props_count + 3];
for (int i = 0; i < props_count; ++i) {
props_with_prof[i] = props[i];
}
props_with_prof[props_count] = CL_QUEUE_PROPERTIES;
props_with_prof[props_count + 1] = CL_QUEUE_PROFILING_ENABLE;
props_with_prof[props_count + 2] = 0;
}
}
return props_with_prof;
}
inline size_t GetSimdWidth(cl_device_id device, cl_kernel kernel) {
PTI_ASSERT(device != nullptr && kernel != nullptr);
cl_int status = CL_SUCCESS;
size_t simd_width = 0;
status =
clGetKernelWorkGroupInfo(kernel, device,
CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
sizeof(size_t), &simd_width, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return simd_width;
}
inline cl_command_queue GetCommandQueue(cl_event event) {
PTI_ASSERT(event != nullptr);
cl_int status = CL_SUCCESS;
cl_command_queue queue = nullptr;
status = clGetEventInfo(event, CL_EVENT_COMMAND_QUEUE,
sizeof(cl_command_queue), &queue, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return queue;
}
inline cl_device_id GetDevice(cl_command_queue queue) {
PTI_ASSERT(queue != nullptr);
cl_int status = CL_SUCCESS;
cl_device_id device = nullptr;
status = clGetCommandQueueInfo(queue, CL_QUEUE_DEVICE,
sizeof(cl_device_id), &device, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return device;
}
inline cl_ulong GetEventTimestamp(cl_event event, cl_profiling_info info) {
PTI_ASSERT(event != nullptr);
cl_int status = CL_SUCCESS;
cl_ulong start = 0;
status = clGetEventProfilingInfo(
event, info, sizeof(cl_ulong), &start, nullptr);
PTI_ASSERT(status == CL_SUCCESS);
return start;
}
inline cl_ulong GetGpuTimestamp() {
cl_ulong timestamp = 0;
#if defined(_WIN32)
BOOL success = QueryPerformanceCounter(×tamp);
PTI_ASSERT(success);
#else
timespec tp{0, 0};
int status = clock_gettime(CLOCK_MONOTONIC_RAW, &tp);
PTI_ASSERT(status == 0);
timestamp = NSEC_IN_SEC * tp.tv_sec + tp.tv_nsec;
#endif
return timestamp;
}
inline cl_ulong GetCpuTimestamp() {
cl_ulong timestamp = 0;
#if defined(_WIN32)
BOOL success = QueryPerformanceCounter(×tamp);
PTI_ASSERT(success);
#else
timespec tp{0, 0};
int status = clock_gettime(CLOCK_MONOTONIC, &tp);
PTI_ASSERT(status == 0);
timestamp = NSEC_IN_SEC * tp.tv_sec + tp.tv_nsec;
#endif
return timestamp;
}
} // namespace cl
} // namespace utils
#endif // PTI_SAMPLES_UTILS_CL_UTILS_H_ | 28.247273 | 77 | 0.664392 | [
"vector"
] |
3266da6d2a69b1d553cf41986378744b0336f1ac | 2,412 | h | C | Sources/SPTPersistentCacheGarbageCollector.h | turlodales/SPTPersistentCache | 130c2310401c9e9675f29932b07079da03d351fb | [
"Apache-2.0"
] | 1,312 | 2016-02-19T13:49:12.000Z | 2022-02-08T07:27:27.000Z | Sources/SPTPersistentCacheGarbageCollector.h | turlodales/SPTPersistentCache | 130c2310401c9e9675f29932b07079da03d351fb | [
"Apache-2.0"
] | 125 | 2016-02-19T14:20:18.000Z | 2021-12-02T14:23:57.000Z | Sources/SPTPersistentCacheGarbageCollector.h | isabella232/SPTPersistentCache | 130c2310401c9e9675f29932b07079da03d351fb | [
"Apache-2.0"
] | 103 | 2016-02-19T13:49:15.000Z | 2022-03-18T20:00:52.000Z | /*
Copyright (c) 2015-2021 Spotify AB.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <Foundation/Foundation.h>
@class SPTPersistentCache;
@class SPTPersistentCacheOptions;
@interface SPTPersistentCacheGarbageCollector : NSObject
/**
Persistent Cache that will be used for garbage collection operations.
*/
@property (nonatomic, weak, readonly) SPTPersistentCache *cache;
/**
Dispatch queue where the operations will take place.
*/
@property (nonatomic, strong, readonly) NSOperationQueue *queue;
/**
Returns YES if the internal timer of proxy is scheduled to perform garbage collection of the cache.
*/
@property (nonatomic, readonly, getter=isGarbageCollectionScheduled) BOOL garbageCollectionScheduled;
/**
Initializes the timer proxy on a specific queue using a specific data cache.
@param cache Persistent Cache that will be used for garbage collection operations.
@param options Cache options to configure this garbage collector.
@param queue NSOperation queue where the operations will take place.
*/
- (instancetype)initWithCache:(SPTPersistentCache *)cache
options:(SPTPersistentCacheOptions *)options
queue:(NSOperationQueue *)queue;
/**
Schedules the garbage collection operation.
@warning The owner of the reference to this object should call
unscheduleGarbageCollection on its dealloc method to prevent a retain cycle
caused by an internal timer.
*/
- (void)schedule;
/**
Unschedules the garbage collection operation.
@warning Ensure the garbage collector is unscheduled to break the retain
cycle that could be caused by the internal timer in this class.
*/
- (void)unschedule;
@end
| 33.5 | 101 | 0.77073 | [
"object"
] |
326b25961875841a3bc05b222a4fbfeabf2ca2cb | 41,088 | h | C | src/google_breakpad/common/minidump_format.h | slipher/breakpad | a0280fc81d4e89be5d0bc554853ca5ed484afe24 | [
"BSD-3-Clause"
] | null | null | null | src/google_breakpad/common/minidump_format.h | slipher/breakpad | a0280fc81d4e89be5d0bc554853ca5ed484afe24 | [
"BSD-3-Clause"
] | null | null | null | src/google_breakpad/common/minidump_format.h | slipher/breakpad | a0280fc81d4e89be5d0bc554853ca5ed484afe24 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2006, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* minidump_format.h: A cross-platform reimplementation of minidump-related
* portions of DbgHelp.h from the Windows Platform SDK.
*
* (This is C99 source, please don't corrupt it with C++.)
*
* Structures that are defined by Microsoft to contain a zero-length array
* are instead defined here to contain an array with one element, as
* zero-length arrays are forbidden by standard C and C++. In these cases,
* *_minsize constants are provided to be used in place of sizeof. For a
* cleaner interface to these sizes when using C++, see minidump_size.h.
*
* These structures are also sufficient to populate minidump files.
*
* These definitions may be extended to support handling minidump files
* for other CPUs and other operating systems.
*
* Because precise data type sizes are crucial for this implementation to
* function properly and portably in terms of interoperability with minidumps
* produced by DbgHelp on Windows, a set of primitive types with known sizes
* are used as the basis of each structure defined by this file. DbgHelp
* on Windows is assumed to be the reference implementation; this file
* seeks to provide a cross-platform compatible implementation. To avoid
* collisions with the types and values defined and used by DbgHelp in the
* event that this implementation is used on Windows, each type and value
* defined here is given a new name, beginning with "MD". Names of the
* equivalent types and values in the Windows Platform SDK are given in
* comments.
*
* Author: Mark Mentovai */
#ifndef GOOGLE_BREAKPAD_COMMON_MINIDUMP_FORMAT_H__
#define GOOGLE_BREAKPAD_COMMON_MINIDUMP_FORMAT_H__
#include <stddef.h>
#include "google_breakpad/common/breakpad_types.h"
#if defined(_MSC_VER)
/* Disable "zero-sized array in struct/union" warnings when compiling in
* MSVC. DbgHelp.h does this too. */
#pragma warning(push)
#pragma warning(disable:4200)
#endif /* _MSC_VER */
/*
* guiddef.h
*/
typedef struct {
uint32_t data1;
uint16_t data2;
uint16_t data3;
uint8_t data4[8];
} MDGUID; /* GUID */
/*
* WinNT.h
*/
/* Non-x86 CPU identifiers found in the high 24 bits of
* (MDRawContext*).context_flags. These aren't used by Breakpad, but are
* defined here for reference, to avoid assigning values that conflict
* (although some values already conflict). */
#define MD_CONTEXT_IA64 0x00080000 /* CONTEXT_IA64 */
/* Additional values from winnt.h in the Windows CE 5.0 SDK: */
#define MD_CONTEXT_SHX 0x000000c0 /* CONTEXT_SH4 (Super-H, includes SH3) */
#define MD_CONTEXT_ALPHA 0x00020000 /* CONTEXT_ALPHA */
/* As of Windows 7 SP1, the number of flag bits has increased to
* include 0x40 (CONTEXT_XSTATE):
* http://msdn.microsoft.com/en-us/library/hh134238%28v=vs.85%29.aspx */
#define MD_CONTEXT_CPU_MASK 0xffffff00
/* This is a base type for MDRawContextX86 and MDRawContextPPC. This
* structure should never be allocated directly. The actual structure type
* can be determined by examining the context_flags field. */
typedef struct {
uint32_t context_flags;
} MDRawContextBase;
#include "minidump_cpu_amd64.h"
#include "minidump_cpu_arm.h"
#include "minidump_cpu_arm64.h"
#include "minidump_cpu_mips.h"
#include "minidump_cpu_ppc.h"
#include "minidump_cpu_ppc64.h"
#include "minidump_cpu_sparc.h"
#include "minidump_cpu_x86.h"
/*
* WinVer.h
*/
typedef struct {
uint32_t signature;
uint32_t struct_version;
uint32_t file_version_hi;
uint32_t file_version_lo;
uint32_t product_version_hi;
uint32_t product_version_lo;
uint32_t file_flags_mask; /* Identifies valid bits in fileFlags */
uint32_t file_flags;
uint32_t file_os;
uint32_t file_type;
uint32_t file_subtype;
uint32_t file_date_hi;
uint32_t file_date_lo;
} MDVSFixedFileInfo; /* VS_FIXEDFILEINFO */
/* For (MDVSFixedFileInfo).signature */
#define MD_VSFIXEDFILEINFO_SIGNATURE 0xfeef04bd
/* VS_FFI_SIGNATURE */
/* For (MDVSFixedFileInfo).version */
#define MD_VSFIXEDFILEINFO_VERSION 0x00010000
/* VS_FFI_STRUCVERSION */
/* For (MDVSFixedFileInfo).file_flags_mask and
* (MDVSFixedFileInfo).file_flags */
#define MD_VSFIXEDFILEINFO_FILE_FLAGS_DEBUG 0x00000001
/* VS_FF_DEBUG */
#define MD_VSFIXEDFILEINFO_FILE_FLAGS_PRERELEASE 0x00000002
/* VS_FF_PRERELEASE */
#define MD_VSFIXEDFILEINFO_FILE_FLAGS_PATCHED 0x00000004
/* VS_FF_PATCHED */
#define MD_VSFIXEDFILEINFO_FILE_FLAGS_PRIVATEBUILD 0x00000008
/* VS_FF_PRIVATEBUILD */
#define MD_VSFIXEDFILEINFO_FILE_FLAGS_INFOINFERRED 0x00000010
/* VS_FF_INFOINFERRED */
#define MD_VSFIXEDFILEINFO_FILE_FLAGS_SPECIALBUILD 0x00000020
/* VS_FF_SPECIALBUILD */
/* For (MDVSFixedFileInfo).file_os: high 16 bits */
#define MD_VSFIXEDFILEINFO_FILE_OS_UNKNOWN 0 /* VOS_UNKNOWN */
#define MD_VSFIXEDFILEINFO_FILE_OS_DOS (1 << 16) /* VOS_DOS */
#define MD_VSFIXEDFILEINFO_FILE_OS_OS216 (2 << 16) /* VOS_OS216 */
#define MD_VSFIXEDFILEINFO_FILE_OS_OS232 (3 << 16) /* VOS_OS232 */
#define MD_VSFIXEDFILEINFO_FILE_OS_NT (4 << 16) /* VOS_NT */
#define MD_VSFIXEDFILEINFO_FILE_OS_WINCE (5 << 16) /* VOS_WINCE */
/* Low 16 bits */
#define MD_VSFIXEDFILEINFO_FILE_OS__BASE 0 /* VOS__BASE */
#define MD_VSFIXEDFILEINFO_FILE_OS__WINDOWS16 1 /* VOS__WINDOWS16 */
#define MD_VSFIXEDFILEINFO_FILE_OS__PM16 2 /* VOS__PM16 */
#define MD_VSFIXEDFILEINFO_FILE_OS__PM32 3 /* VOS__PM32 */
#define MD_VSFIXEDFILEINFO_FILE_OS__WINDOWS32 4 /* VOS__WINDOWS32 */
/* For (MDVSFixedFileInfo).file_type */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_UNKNOWN 0 /* VFT_UNKNOWN */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_APP 1 /* VFT_APP */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_DLL 2 /* VFT_DLL */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_DRV 3 /* VFT_DLL */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_FONT 4 /* VFT_FONT */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_VXD 5 /* VFT_VXD */
#define MD_VSFIXEDFILEINFO_FILE_TYPE_STATIC_LIB 7 /* VFT_STATIC_LIB */
/* For (MDVSFixedFileInfo).file_subtype */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_UNKNOWN 0
/* VFT2_UNKNOWN */
/* with file_type = MD_VSFIXEDFILEINFO_FILETYPE_DRV */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_PRINTER 1
/* VFT2_DRV_PRINTER */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_KEYBOARD 2
/* VFT2_DRV_KEYBOARD */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_LANGUAGE 3
/* VFT2_DRV_LANGUAGE */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_DISPLAY 4
/* VFT2_DRV_DISPLAY */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_MOUSE 5
/* VFT2_DRV_MOUSE */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_NETWORK 6
/* VFT2_DRV_NETWORK */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_SYSTEM 7
/* VFT2_DRV_SYSTEM */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_INSTALLABLE 8
/* VFT2_DRV_INSTALLABLE */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_SOUND 9
/* VFT2_DRV_SOUND */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_COMM 10
/* VFT2_DRV_COMM */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_INPUTMETHOD 11
/* VFT2_DRV_INPUTMETHOD */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_DRV_VERSIONED_PRINTER 12
/* VFT2_DRV_VERSIONED_PRINTER */
/* with file_type = MD_VSFIXEDFILEINFO_FILETYPE_FONT */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_FONT_RASTER 1
/* VFT2_FONT_RASTER */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_FONT_VECTOR 2
/* VFT2_FONT_VECTOR */
#define MD_VSFIXEDFILEINFO_FILE_SUBTYPE_FONT_TRUETYPE 3
/* VFT2_FONT_TRUETYPE */
/*
* DbgHelp.h
*/
/* An MDRVA is an offset into the minidump file. The beginning of the
* MDRawHeader is at offset 0. */
typedef uint32_t MDRVA; /* RVA */
typedef struct {
uint32_t data_size;
MDRVA rva;
} MDLocationDescriptor; /* MINIDUMP_LOCATION_DESCRIPTOR */
typedef struct {
/* The base address of the memory range on the host that produced the
* minidump. */
uint64_t start_of_memory_range;
MDLocationDescriptor memory;
} MDMemoryDescriptor; /* MINIDUMP_MEMORY_DESCRIPTOR */
typedef struct {
uint32_t signature;
uint32_t version;
uint32_t stream_count;
MDRVA stream_directory_rva; /* A |stream_count|-sized array of
* MDRawDirectory structures. */
uint32_t checksum; /* Can be 0. In fact, that's all that's
* been found in minidump files. */
uint32_t time_date_stamp; /* time_t */
uint64_t flags;
} MDRawHeader; /* MINIDUMP_HEADER */
/* For (MDRawHeader).signature and (MDRawHeader).version. Note that only the
* low 16 bits of (MDRawHeader).version are MD_HEADER_VERSION. Per the
* documentation, the high 16 bits are implementation-specific. */
#define MD_HEADER_SIGNATURE 0x504d444d /* 'PMDM' */
/* MINIDUMP_SIGNATURE */
#define MD_HEADER_VERSION 0x0000a793 /* 42899 */
/* MINIDUMP_VERSION */
/* For (MDRawHeader).flags: */
typedef enum {
/* MD_NORMAL is the standard type of minidump. It includes full
* streams for the thread list, module list, exception, system info,
* and miscellaneous info. A memory list stream is also present,
* pointing to the same stack memory contained in the thread list,
* as well as a 256-byte region around the instruction address that
* was executing when the exception occurred. Stack memory is from
* 4 bytes below a thread's stack pointer up to the top of the
* memory region encompassing the stack. */
MD_NORMAL = 0x00000000,
MD_WITH_DATA_SEGS = 0x00000001,
MD_WITH_FULL_MEMORY = 0x00000002,
MD_WITH_HANDLE_DATA = 0x00000004,
MD_FILTER_MEMORY = 0x00000008,
MD_SCAN_MEMORY = 0x00000010,
MD_WITH_UNLOADED_MODULES = 0x00000020,
MD_WITH_INDIRECTLY_REFERENCED_MEMORY = 0x00000040,
MD_FILTER_MODULE_PATHS = 0x00000080,
MD_WITH_PROCESS_THREAD_DATA = 0x00000100,
MD_WITH_PRIVATE_READ_WRITE_MEMORY = 0x00000200,
MD_WITHOUT_OPTIONAL_DATA = 0x00000400,
MD_WITH_FULL_MEMORY_INFO = 0x00000800,
MD_WITH_THREAD_INFO = 0x00001000,
MD_WITH_CODE_SEGS = 0x00002000,
MD_WITHOUT_AUXILLIARY_SEGS = 0x00004000,
MD_WITH_FULL_AUXILLIARY_STATE = 0x00008000,
MD_WITH_PRIVATE_WRITE_COPY_MEMORY = 0x00010000,
MD_IGNORE_INACCESSIBLE_MEMORY = 0x00020000,
MD_WITH_TOKEN_INFORMATION = 0x00040000
} MDType; /* MINIDUMP_TYPE */
typedef struct {
uint32_t stream_type;
MDLocationDescriptor location;
} MDRawDirectory; /* MINIDUMP_DIRECTORY */
/* For (MDRawDirectory).stream_type */
typedef enum {
MD_UNUSED_STREAM = 0,
MD_RESERVED_STREAM_0 = 1,
MD_RESERVED_STREAM_1 = 2,
MD_THREAD_LIST_STREAM = 3, /* MDRawThreadList */
MD_MODULE_LIST_STREAM = 4, /* MDRawModuleList */
MD_MEMORY_LIST_STREAM = 5, /* MDRawMemoryList */
MD_EXCEPTION_STREAM = 6, /* MDRawExceptionStream */
MD_SYSTEM_INFO_STREAM = 7, /* MDRawSystemInfo */
MD_THREAD_EX_LIST_STREAM = 8,
MD_MEMORY_64_LIST_STREAM = 9,
MD_COMMENT_STREAM_A = 10,
MD_COMMENT_STREAM_W = 11,
MD_HANDLE_DATA_STREAM = 12,
MD_FUNCTION_TABLE_STREAM = 13,
MD_UNLOADED_MODULE_LIST_STREAM = 14,
MD_MISC_INFO_STREAM = 15, /* MDRawMiscInfo */
MD_MEMORY_INFO_LIST_STREAM = 16, /* MDRawMemoryInfoList */
MD_THREAD_INFO_LIST_STREAM = 17,
MD_HANDLE_OPERATION_LIST_STREAM = 18,
MD_LAST_RESERVED_STREAM = 0x0000ffff,
/* Breakpad extension types. 0x4767 = "Gg" */
MD_BREAKPAD_INFO_STREAM = 0x47670001, /* MDRawBreakpadInfo */
MD_ASSERTION_INFO_STREAM = 0x47670002, /* MDRawAssertionInfo */
/* These are additional minidump stream values which are specific to
* the linux breakpad implementation. */
MD_LINUX_CPU_INFO = 0x47670003, /* /proc/cpuinfo */
MD_LINUX_PROC_STATUS = 0x47670004, /* /proc/$x/status */
MD_LINUX_LSB_RELEASE = 0x47670005, /* /etc/lsb-release */
MD_LINUX_CMD_LINE = 0x47670006, /* /proc/$x/cmdline */
MD_LINUX_ENVIRON = 0x47670007, /* /proc/$x/environ */
MD_LINUX_AUXV = 0x47670008, /* /proc/$x/auxv */
MD_LINUX_MAPS = 0x47670009, /* /proc/$x/maps */
MD_LINUX_DSO_DEBUG = 0x4767000A /* MDRawDebug{32,64} */
} MDStreamType; /* MINIDUMP_STREAM_TYPE */
typedef struct {
uint32_t length; /* Length of buffer in bytes (not characters),
* excluding 0-terminator */
uint16_t buffer[1]; /* UTF-16-encoded, 0-terminated */
} MDString; /* MINIDUMP_STRING */
static const size_t MDString_minsize = offsetof(MDString, buffer[0]);
typedef struct {
uint32_t thread_id;
uint32_t suspend_count;
uint32_t priority_class;
uint32_t priority;
uint64_t teb; /* Thread environment block */
MDMemoryDescriptor stack;
MDLocationDescriptor thread_context; /* MDRawContext[CPU] */
} MDRawThread; /* MINIDUMP_THREAD */
typedef struct {
uint32_t number_of_threads;
MDRawThread threads[1];
} MDRawThreadList; /* MINIDUMP_THREAD_LIST */
static const size_t MDRawThreadList_minsize = offsetof(MDRawThreadList,
threads[0]);
typedef struct {
uint64_t base_of_image;
uint32_t size_of_image;
uint32_t checksum; /* 0 if unknown */
uint32_t time_date_stamp; /* time_t */
MDRVA module_name_rva; /* MDString, pathname or filename */
MDVSFixedFileInfo version_info;
/* The next field stores a CodeView record and is populated when a module's
* debug information resides in a PDB file. It identifies the PDB file. */
MDLocationDescriptor cv_record;
/* The next field is populated when a module's debug information resides
* in a DBG file. It identifies the DBG file. This field is effectively
* obsolete with modules built by recent toolchains. */
MDLocationDescriptor misc_record;
/* Alignment problem: reserved0 and reserved1 are defined by the platform
* SDK as 64-bit quantities. However, that results in a structure whose
* alignment is unpredictable on different CPUs and ABIs. If the ABI
* specifies full alignment of 64-bit quantities in structures (as ppc
* does), there will be padding between miscRecord and reserved0. If
* 64-bit quantities can be aligned on 32-bit boundaries (as on x86),
* this padding will not exist. (Note that the structure up to this point
* contains 1 64-bit member followed by 21 32-bit members.)
* As a workaround, reserved0 and reserved1 are instead defined here as
* four 32-bit quantities. This should be harmless, as there are
* currently no known uses for these fields. */
uint32_t reserved0[2];
uint32_t reserved1[2];
} MDRawModule; /* MINIDUMP_MODULE */
/* The inclusion of a 64-bit type in MINIDUMP_MODULE forces the struct to
* be tail-padded out to a multiple of 64 bits under some ABIs (such as PPC).
* This doesn't occur on systems that don't tail-pad in this manner. Define
* this macro to be the usable size of the MDRawModule struct, and use it in
* place of sizeof(MDRawModule). */
#define MD_MODULE_SIZE 108
/* (MDRawModule).cv_record can reference MDCVInfoPDB20 or MDCVInfoPDB70.
* Ref.: http://www.debuginfo.com/articles/debuginfomatch.html
* MDCVInfoPDB70 is the expected structure type with recent toolchains. */
typedef struct {
uint32_t signature;
uint32_t offset; /* Offset to debug data (expect 0 in minidump) */
} MDCVHeader;
typedef struct {
MDCVHeader cv_header;
uint32_t signature; /* time_t debug information created */
uint32_t age; /* revision of PDB file */
uint8_t pdb_file_name[1]; /* Pathname or filename of PDB file */
} MDCVInfoPDB20;
static const size_t MDCVInfoPDB20_minsize = offsetof(MDCVInfoPDB20,
pdb_file_name[0]);
#define MD_CVINFOPDB20_SIGNATURE 0x3031424e /* cvHeader.signature = '01BN' */
typedef struct {
uint32_t cv_signature;
MDGUID signature; /* GUID, identifies PDB file */
uint32_t age; /* Identifies incremental changes to PDB file */
uint8_t pdb_file_name[1]; /* Pathname or filename of PDB file,
* 0-terminated 8-bit character data (UTF-8?) */
} MDCVInfoPDB70;
static const size_t MDCVInfoPDB70_minsize = offsetof(MDCVInfoPDB70,
pdb_file_name[0]);
#define MD_CVINFOPDB70_SIGNATURE 0x53445352 /* cvSignature = 'SDSR' */
typedef struct {
uint32_t data1[2];
uint32_t data2;
uint32_t data3;
uint32_t data4;
uint32_t data5[3];
uint8_t extra[2];
} MDCVInfoELF;
/* In addition to the two CodeView record formats above, used for linking
* to external pdb files, it is possible for debugging data to be carried
* directly in the CodeView record itself. These signature values will
* be found in the first 4 bytes of the CodeView record. Additional values
* not commonly experienced in the wild are given by "Microsoft Symbol and
* Type Information", http://www.x86.org/ftp/manuals/tools/sym.pdf, section
* 7.2. An in-depth description of the CodeView 4.1 format is given by
* "Undocumented Windows 2000 Secrets", Windows 2000 Debugging Support/
* Microsoft Symbol File Internals/CodeView Subsections,
* http://www.rawol.com/features/undocumented/sbs-w2k-1-windows-2000-debugging-support.pdf
*/
#define MD_CVINFOCV41_SIGNATURE 0x3930424e /* '90BN', CodeView 4.10. */
#define MD_CVINFOCV50_SIGNATURE 0x3131424e /* '11BN', CodeView 5.0,
* MS C7-format (/Z7). */
#define MD_CVINFOUNKNOWN_SIGNATURE 0xffffffff /* An unlikely value. */
/* (MDRawModule).miscRecord can reference MDImageDebugMisc. The Windows
* structure is actually defined in WinNT.h. This structure is effectively
* obsolete with modules built by recent toolchains. */
typedef struct {
uint32_t data_type; /* IMAGE_DEBUG_TYPE_*, not defined here because
* this debug record type is mostly obsolete. */
uint32_t length; /* Length of entire MDImageDebugMisc structure */
uint8_t unicode; /* True if data is multibyte */
uint8_t reserved[3];
uint8_t data[1];
} MDImageDebugMisc; /* IMAGE_DEBUG_MISC */
static const size_t MDImageDebugMisc_minsize = offsetof(MDImageDebugMisc,
data[0]);
typedef struct {
uint32_t number_of_modules;
MDRawModule modules[1];
} MDRawModuleList; /* MINIDUMP_MODULE_LIST */
static const size_t MDRawModuleList_minsize = offsetof(MDRawModuleList,
modules[0]);
typedef struct {
uint32_t number_of_memory_ranges;
MDMemoryDescriptor memory_ranges[1];
} MDRawMemoryList; /* MINIDUMP_MEMORY_LIST */
static const size_t MDRawMemoryList_minsize = offsetof(MDRawMemoryList,
memory_ranges[0]);
#define MD_EXCEPTION_MAXIMUM_PARAMETERS 15
typedef struct {
uint32_t exception_code; /* Windows: MDExceptionCodeWin,
* Mac OS X: MDExceptionMac,
* Linux: MDExceptionCodeLinux. */
uint32_t exception_flags; /* Windows: 1 if noncontinuable,
Mac OS X: MDExceptionCodeMac. */
uint64_t exception_record; /* Address (in the minidump-producing host's
* memory) of another MDException, for
* nested exceptions. */
uint64_t exception_address; /* The address that caused the exception.
* Mac OS X: exception subcode (which is
* typically the address). */
uint32_t number_parameters; /* Number of valid elements in
* exception_information. */
uint32_t __align;
uint64_t exception_information[MD_EXCEPTION_MAXIMUM_PARAMETERS];
} MDException; /* MINIDUMP_EXCEPTION */
#include "minidump_exception_linux.h"
#include "minidump_exception_mac.h"
#include "minidump_exception_ps3.h"
#include "minidump_exception_solaris.h"
#include "minidump_exception_win32.h"
typedef struct {
uint32_t thread_id; /* Thread in which the exception
* occurred. Corresponds to
* (MDRawThread).thread_id. */
uint32_t __align;
MDException exception_record;
MDLocationDescriptor thread_context; /* MDRawContext[CPU] */
} MDRawExceptionStream; /* MINIDUMP_EXCEPTION_STREAM */
typedef union {
struct {
uint32_t vendor_id[3]; /* cpuid 0: ebx, edx, ecx */
uint32_t version_information; /* cpuid 1: eax */
uint32_t feature_information; /* cpuid 1: edx */
uint32_t amd_extended_cpu_features; /* cpuid 0x80000001, ebx */
} x86_cpu_info;
struct {
uint32_t cpuid;
uint32_t elf_hwcaps; /* linux specific, 0 otherwise */
} arm_cpu_info;
struct {
uint64_t processor_features[2];
} other_cpu_info;
} MDCPUInformation; /* CPU_INFORMATION */
/* For (MDCPUInformation).arm_cpu_info.elf_hwcaps.
* This matches the Linux kernel definitions from <asm/hwcaps.h> */
typedef enum {
MD_CPU_ARM_ELF_HWCAP_SWP = (1 << 0),
MD_CPU_ARM_ELF_HWCAP_HALF = (1 << 1),
MD_CPU_ARM_ELF_HWCAP_THUMB = (1 << 2),
MD_CPU_ARM_ELF_HWCAP_26BIT = (1 << 3),
MD_CPU_ARM_ELF_HWCAP_FAST_MULT = (1 << 4),
MD_CPU_ARM_ELF_HWCAP_FPA = (1 << 5),
MD_CPU_ARM_ELF_HWCAP_VFP = (1 << 6),
MD_CPU_ARM_ELF_HWCAP_EDSP = (1 << 7),
MD_CPU_ARM_ELF_HWCAP_JAVA = (1 << 8),
MD_CPU_ARM_ELF_HWCAP_IWMMXT = (1 << 9),
MD_CPU_ARM_ELF_HWCAP_CRUNCH = (1 << 10),
MD_CPU_ARM_ELF_HWCAP_THUMBEE = (1 << 11),
MD_CPU_ARM_ELF_HWCAP_NEON = (1 << 12),
MD_CPU_ARM_ELF_HWCAP_VFPv3 = (1 << 13),
MD_CPU_ARM_ELF_HWCAP_VFPv3D16 = (1 << 14),
MD_CPU_ARM_ELF_HWCAP_TLS = (1 << 15),
MD_CPU_ARM_ELF_HWCAP_VFPv4 = (1 << 16),
MD_CPU_ARM_ELF_HWCAP_IDIVA = (1 << 17),
MD_CPU_ARM_ELF_HWCAP_IDIVT = (1 << 18),
} MDCPUInformationARMElfHwCaps;
typedef struct {
/* The next 3 fields and numberOfProcessors are from the SYSTEM_INFO
* structure as returned by GetSystemInfo */
uint16_t processor_architecture;
uint16_t processor_level; /* x86: 5 = 586, 6 = 686, ... */
/* ARM: 6 = ARMv6, 7 = ARMv7 ... */
uint16_t processor_revision; /* x86: 0xMMSS, where MM=model,
* SS=stepping */
/* ARM: 0 */
uint8_t number_of_processors;
uint8_t product_type; /* Windows: VER_NT_* from WinNT.h */
/* The next 5 fields are from the OSVERSIONINFO structure as returned
* by GetVersionEx */
uint32_t major_version;
uint32_t minor_version;
uint32_t build_number;
uint32_t platform_id;
MDRVA csd_version_rva; /* MDString further identifying the
* host OS.
* Windows: name of the installed OS
* service pack.
* Mac OS X: the Apple OS build number
* (sw_vers -buildVersion).
* Linux: uname -srvmo */
uint16_t suite_mask; /* Windows: VER_SUITE_* from WinNT.h */
uint16_t reserved2;
MDCPUInformation cpu;
} MDRawSystemInfo; /* MINIDUMP_SYSTEM_INFO */
/* For (MDRawSystemInfo).processor_architecture: */
typedef enum {
MD_CPU_ARCHITECTURE_X86 = 0, /* PROCESSOR_ARCHITECTURE_INTEL */
MD_CPU_ARCHITECTURE_MIPS = 1, /* PROCESSOR_ARCHITECTURE_MIPS */
MD_CPU_ARCHITECTURE_ALPHA = 2, /* PROCESSOR_ARCHITECTURE_ALPHA */
MD_CPU_ARCHITECTURE_PPC = 3, /* PROCESSOR_ARCHITECTURE_PPC */
MD_CPU_ARCHITECTURE_SHX = 4, /* PROCESSOR_ARCHITECTURE_SHX
* (Super-H) */
MD_CPU_ARCHITECTURE_ARM = 5, /* PROCESSOR_ARCHITECTURE_ARM */
MD_CPU_ARCHITECTURE_IA64 = 6, /* PROCESSOR_ARCHITECTURE_IA64 */
MD_CPU_ARCHITECTURE_ALPHA64 = 7, /* PROCESSOR_ARCHITECTURE_ALPHA64 */
MD_CPU_ARCHITECTURE_MSIL = 8, /* PROCESSOR_ARCHITECTURE_MSIL
* (Microsoft Intermediate Language) */
MD_CPU_ARCHITECTURE_AMD64 = 9, /* PROCESSOR_ARCHITECTURE_AMD64 */
MD_CPU_ARCHITECTURE_X86_WIN64 = 10,
/* PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 (WoW64) */
MD_CPU_ARCHITECTURE_SPARC = 0x8001, /* Breakpad-defined value for SPARC */
MD_CPU_ARCHITECTURE_PPC64 = 0x8002, /* Breakpad-defined value for PPC64 */
MD_CPU_ARCHITECTURE_ARM64 = 0x8003, /* Breakpad-defined value for ARM64 */
MD_CPU_ARCHITECTURE_UNKNOWN = 0xffff /* PROCESSOR_ARCHITECTURE_UNKNOWN */
} MDCPUArchitecture;
/* For (MDRawSystemInfo).platform_id: */
typedef enum {
MD_OS_WIN32S = 0, /* VER_PLATFORM_WIN32s (Windows 3.1) */
MD_OS_WIN32_WINDOWS = 1, /* VER_PLATFORM_WIN32_WINDOWS (Windows 95-98-Me) */
MD_OS_WIN32_NT = 2, /* VER_PLATFORM_WIN32_NT (Windows NT, 2000+) */
MD_OS_WIN32_CE = 3, /* VER_PLATFORM_WIN32_CE, VER_PLATFORM_WIN32_HH
* (Windows CE, Windows Mobile, "Handheld") */
/* The following values are Breakpad-defined. */
MD_OS_UNIX = 0x8000, /* Generic Unix-ish */
MD_OS_MAC_OS_X = 0x8101, /* Mac OS X/Darwin */
MD_OS_IOS = 0x8102, /* iOS */
MD_OS_LINUX = 0x8201, /* Linux */
MD_OS_SOLARIS = 0x8202, /* Solaris */
MD_OS_ANDROID = 0x8203, /* Android */
MD_OS_PS3 = 0x8204, /* PS3 */
MD_OS_NACL = 0x8205 /* Native Client (NaCl) */
} MDOSPlatform;
typedef struct {
uint16_t year;
uint16_t month;
uint16_t day_of_week;
uint16_t day;
uint16_t hour;
uint16_t minute;
uint16_t second;
uint16_t milliseconds;
} MDSystemTime; /* SYSTEMTIME */
typedef struct {
/* Required field. The bias is the difference, in minutes, between
* Coordinated Universal Time (UTC) and local time.
* Formula: UTC = local time + bias */
int32_t bias;
/* A description for standard time. For example, "EST" could indicate Eastern
* Standard Time. In practice this contains the full time zone names. This
* string can be empty. */
uint16_t standard_name[32]; /* UTF-16-encoded, 0-terminated */
/* A MDSystemTime structure that contains a date and local time when the
* transition from daylight saving time to standard time occurs on this
* operating system. If the time zone does not support daylight saving time,
* the month member in the MDSystemTime structure is zero. */
MDSystemTime standard_date;
/* The bias value to be used during local time translations that occur during
* standard time. */
int32_t standard_bias;
/* A description for daylight saving time. For example, "PDT" could indicate
* Pacific Daylight Time. In practice this contains the full time zone names.
* This string can be empty. */
uint16_t daylight_name[32]; /* UTF-16-encoded, 0-terminated */
/* A MDSystemTime structure that contains a date and local time when the
* transition from standard time to daylight saving time occurs on this
* operating system. If the time zone does not support daylight saving time,
* the month member in the MDSystemTime structure is zero.*/
MDSystemTime daylight_date;
/* The bias value to be used during local time translations that occur during
* daylight saving time. */
int32_t daylight_bias;
} MDTimeZoneInformation; /* TIME_ZONE_INFORMATION */
/* MAX_PATH from windef.h */
#define MD_MAX_PATH 260
/* The miscellaneous information stream contains a variety
* of small pieces of information. A member is valid if
* it's within the available size and its corresponding
* bit is set. */
typedef struct {
uint32_t size_of_info; /* Length of entire MDRawMiscInfo structure. */
uint32_t flags1;
/* The next field is only valid if flags1 contains
* MD_MISCINFO_FLAGS1_PROCESS_ID. */
uint32_t process_id;
/* The next 3 fields are only valid if flags1 contains
* MD_MISCINFO_FLAGS1_PROCESS_TIMES. */
uint32_t process_create_time; /* time_t process started */
uint32_t process_user_time; /* seconds of user CPU time */
uint32_t process_kernel_time; /* seconds of kernel CPU time */
/* The following fields are not present in MINIDUMP_MISC_INFO but are
* in MINIDUMP_MISC_INFO_2. When this struct is populated, these values
* may not be set. Use flags1 and size_of_info to determine whether these
* values are present. These are only valid when flags1 contains
* MD_MISCINFO_FLAGS1_PROCESSOR_POWER_INFO. */
uint32_t processor_max_mhz;
uint32_t processor_current_mhz;
uint32_t processor_mhz_limit;
uint32_t processor_max_idle_state;
uint32_t processor_current_idle_state;
/* The following fields are not present in MINIDUMP_MISC_INFO_2 but are
* in MINIDUMP_MISC_INFO_3. When this struct is populated, these values
* may not be set. Use flags1 and size_of_info to determine whether these
* values are present. */
/* The following field is only valid if flags1 contains
* MD_MISCINFO_FLAGS1_PROCESS_INTEGRITY. */
uint32_t process_integrity_level;
/* The following field is only valid if flags1 contains
* MD_MISCINFO_FLAGS1_PROCESS_EXECUTE_FLAGS. */
uint32_t process_execute_flags;
/* The following field is only valid if flags1 contains
* MD_MISCINFO_FLAGS1_PROTECTED_PROCESS. */
uint32_t protected_process;
/* The following 2 fields are only valid if flags1 contains
* MD_MISCINFO_FLAGS1_TIMEZONE. */
uint32_t time_zone_id;
MDTimeZoneInformation time_zone;
/* The following fields are not present in MINIDUMP_MISC_INFO_3 but are
* in MINIDUMP_MISC_INFO_4. When this struct is populated, these values
* may not be set. Use flags1 and size_of_info to determine whether these
* values are present. */
/* The following 2 fields are only valid if flags1 contains
* MD_MISCINFO_FLAGS1_BUILDSTRING. */
uint16_t build_string[MD_MAX_PATH]; /* UTF-16-encoded, 0-terminated */
uint16_t dbg_bld_str[40]; /* UTF-16-encoded, 0-terminated */
} MDRawMiscInfo; /* MINIDUMP_MISC_INFO, MINIDUMP_MISC_INFO_2,
* MINIDUMP_MISC_INFO_3, MINIDUMP_MISC_INFO_4,
* MINIDUMP_MISC_INFO_N */
static const size_t MD_MISCINFO_SIZE =
offsetof(MDRawMiscInfo, processor_max_mhz);
static const size_t MD_MISCINFO2_SIZE =
offsetof(MDRawMiscInfo, process_integrity_level);
static const size_t MD_MISCINFO3_SIZE =
offsetof(MDRawMiscInfo, build_string[0]);
static const size_t MD_MISCINFO4_SIZE = sizeof(MDRawMiscInfo);
/* For (MDRawMiscInfo).flags1. These values indicate which fields in the
* MDRawMiscInfoStructure are valid. */
typedef enum {
MD_MISCINFO_FLAGS1_PROCESS_ID = 0x00000001,
/* MINIDUMP_MISC1_PROCESS_ID */
MD_MISCINFO_FLAGS1_PROCESS_TIMES = 0x00000002,
/* MINIDUMP_MISC1_PROCESS_TIMES */
MD_MISCINFO_FLAGS1_PROCESSOR_POWER_INFO = 0x00000004,
/* MINIDUMP_MISC1_PROCESSOR_POWER_INFO */
MD_MISCINFO_FLAGS1_PROCESS_INTEGRITY = 0x00000010,
/* MINIDUMP_MISC3_PROCESS_INTEGRITY */
MD_MISCINFO_FLAGS1_PROCESS_EXECUTE_FLAGS = 0x00000020,
/* MINIDUMP_MISC3_PROCESS_EXECUTE_FLAGS */
MD_MISCINFO_FLAGS1_TIMEZONE = 0x00000040,
/* MINIDUMP_MISC3_TIMEZONE */
MD_MISCINFO_FLAGS1_PROTECTED_PROCESS = 0x00000080,
/* MINIDUMP_MISC3_PROTECTED_PROCESS */
MD_MISCINFO_FLAGS1_BUILDSTRING = 0x00000100,
/* MINIDUMP_MISC4_BUILDSTRING */
} MDMiscInfoFlags1;
/*
* Around DbgHelp version 6.0, the style of new LIST structures changed
* from including an array of length 1 at the end of the struct to
* represent the variable-length data to including explicit
* "size of header", "size of entry" and "number of entries" fields
* in the header, presumably to allow backwards-compatibly-extending
* the structures in the future. The actual list entries follow the
* header data directly in this case.
*/
typedef struct {
uint32_t size_of_header; /* sizeof(MDRawMemoryInfoList) */
uint32_t size_of_entry; /* sizeof(MDRawMemoryInfo) */
uint64_t number_of_entries;
} MDRawMemoryInfoList; /* MINIDUMP_MEMORY_INFO_LIST */
typedef struct {
uint64_t base_address; /* Base address of a region of pages */
uint64_t allocation_base; /* Base address of a range of pages
* within this region. */
uint32_t allocation_protection; /* Memory protection when this region
* was originally allocated:
* MDMemoryProtection */
uint32_t __alignment1;
uint64_t region_size;
uint32_t state; /* MDMemoryState */
uint32_t protection; /* MDMemoryProtection */
uint32_t type; /* MDMemoryType */
uint32_t __alignment2;
} MDRawMemoryInfo; /* MINIDUMP_MEMORY_INFO */
/* For (MDRawMemoryInfo).state */
typedef enum {
MD_MEMORY_STATE_COMMIT = 0x1000, /* physical storage has been allocated */
MD_MEMORY_STATE_RESERVE = 0x2000, /* reserved, but no physical storage */
MD_MEMORY_STATE_FREE = 0x10000 /* available to be allocated */
} MDMemoryState;
/* For (MDRawMemoryInfo).allocation_protection and .protection */
typedef enum {
MD_MEMORY_PROTECT_NOACCESS = 0x01, /* PAGE_NOACCESS */
MD_MEMORY_PROTECT_READONLY = 0x02, /* PAGE_READONLY */
MD_MEMORY_PROTECT_READWRITE = 0x04, /* PAGE_READWRITE */
MD_MEMORY_PROTECT_WRITECOPY = 0x08, /* PAGE_WRITECOPY */
MD_MEMORY_PROTECT_EXECUTE = 0x10, /* PAGE_EXECUTE */
MD_MEMORY_PROTECT_EXECUTE_READ = 0x20, /* PAGE_EXECUTE_READ */
MD_MEMORY_PROTECT_EXECUTE_READWRITE = 0x40, /* PAGE_EXECUTE_READWRITE */
MD_MEMORY_PROTECT_EXECUTE_WRITECOPY = 0x80, /* PAGE_EXECUTE_WRITECOPY */
/* These options can be combined with the previous flags. */
MD_MEMORY_PROTECT_GUARD = 0x100, /* PAGE_GUARD */
MD_MEMORY_PROTECT_NOCACHE = 0x200, /* PAGE_NOCACHE */
MD_MEMORY_PROTECT_WRITECOMBINE = 0x400, /* PAGE_WRITECOMBINE */
} MDMemoryProtection;
/* Used to mask the mutually exclusive options from the combinable flags. */
const uint32_t MD_MEMORY_PROTECTION_ACCESS_MASK = 0xFF;
/* For (MDRawMemoryInfo).type */
typedef enum {
MD_MEMORY_TYPE_PRIVATE = 0x20000, /* not shared by other processes */
MD_MEMORY_TYPE_MAPPED = 0x40000, /* mapped into the view of a section */
MD_MEMORY_TYPE_IMAGE = 0x1000000 /* mapped into the view of an image */
} MDMemoryType;
/*
* Breakpad extension types
*/
typedef struct {
/* validity is a bitmask with values from MDBreakpadInfoValidity, indicating
* which of the other fields in the structure are valid. */
uint32_t validity;
/* Thread ID of the handler thread. dump_thread_id should correspond to
* the thread_id of an MDRawThread in the minidump's MDRawThreadList if
* a dedicated thread in that list was used to produce the minidump. If
* the MDRawThreadList does not contain a dedicated thread used to produce
* the minidump, this field should be set to 0 and the validity field
* must not contain MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID. */
uint32_t dump_thread_id;
/* Thread ID of the thread that requested the minidump be produced. As
* with dump_thread_id, requesting_thread_id should correspond to the
* thread_id of an MDRawThread in the minidump's MDRawThreadList. For
* minidumps produced as a result of an exception, requesting_thread_id
* will be the same as the MDRawExceptionStream's thread_id field. For
* minidumps produced "manually" at the program's request,
* requesting_thread_id will indicate which thread caused the dump to be
* written. If the minidump was produced at the request of something
* other than a thread in the MDRawThreadList, this field should be set
* to 0 and the validity field must not contain
* MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID. */
uint32_t requesting_thread_id;
} MDRawBreakpadInfo;
/* For (MDRawBreakpadInfo).validity: */
typedef enum {
/* When set, the dump_thread_id field is valid. */
MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID = 1 << 0,
/* When set, the requesting_thread_id field is valid. */
MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID = 1 << 1
} MDBreakpadInfoValidity;
typedef struct {
/* expression, function, and file are 0-terminated UTF-16 strings. They
* may be truncated if necessary, but should always be 0-terminated when
* written to a file.
* Fixed-length strings are used because MiniDumpWriteDump doesn't offer
* a way for user streams to point to arbitrary RVAs for strings. */
uint16_t expression[128]; /* Assertion that failed... */
uint16_t function[128]; /* ...within this function... */
uint16_t file[128]; /* ...in this file... */
uint32_t line; /* ...at this line. */
uint32_t type;
} MDRawAssertionInfo;
/* For (MDRawAssertionInfo).type: */
typedef enum {
MD_ASSERTION_INFO_TYPE_UNKNOWN = 0,
/* Used for assertions that would be raised by the MSVC CRT but are
* directed to an invalid parameter handler instead. */
MD_ASSERTION_INFO_TYPE_INVALID_PARAMETER,
/* Used for assertions that would be raised by the MSVC CRT but are
* directed to a pure virtual call handler instead. */
MD_ASSERTION_INFO_TYPE_PURE_VIRTUAL_CALL
} MDAssertionInfoData;
/* These structs are used to store the DSO debug data in Linux minidumps,
* which is necessary for converting minidumps to usable coredumps.
* Because of a historical accident, several fields are variably encoded
* according to client word size, so tools potentially need to support both. */
typedef struct {
uint32_t addr;
MDRVA name;
uint32_t ld;
} MDRawLinkMap32;
typedef struct {
uint32_t version;
MDRVA map; /* array of MDRawLinkMap32 */
uint32_t dso_count;
uint32_t brk;
uint32_t ldbase;
uint32_t dynamic;
} MDRawDebug32;
typedef struct {
uint64_t addr;
MDRVA name;
uint64_t ld;
} MDRawLinkMap64;
typedef struct {
uint32_t version;
MDRVA map; /* array of MDRawLinkMap64 */
uint32_t dso_count;
uint64_t brk;
uint64_t ldbase;
uint64_t dynamic;
} MDRawDebug64;
#if defined(_MSC_VER)
#pragma warning(pop)
#endif /* _MSC_VER */
#endif /* GOOGLE_BREAKPAD_COMMON_MINIDUMP_FORMAT_H__ */
| 42.22816 | 90 | 0.689715 | [
"model"
] |
326c7687f6385e2042a0cb82e9af1697435c9e29 | 5,653 | h | C | cpp/src/constraints.h | kn65op/cli-toolkit | f31a9d738cb7e262abb3162dae3d77d78602ea67 | [
"BSD-3-Clause"
] | null | null | null | cpp/src/constraints.h | kn65op/cli-toolkit | f31a9d738cb7e262abb3162dae3d77d78602ea67 | [
"BSD-3-Clause"
] | null | null | null | cpp/src/constraints.h | kn65op/cli-toolkit | f31a9d738cb7e262abb3162dae3d77d78602ea67 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2006-2013, Alexis Royer, http://alexis.royer.free.fr/CLI
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the CLI library project nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//! @file
//! @author Alexis Royer
//! @brief Object consistency insurance.
#ifndef _CLI_CONSTRAINTS_H_
#define _CLI_CONSTRAINTS_H_
#include "cli/namespace.h"
CLI_NS_BEGIN(cli)
// General.
//! Maximum length of resource strings, for each language.
#ifndef CLI_MAX_RESOURCE_LENGTH
static const unsigned int MAX_RESOURCE_LENGTH = 256;
#else
static const unsigned int MAX_RESOURCE_LENGTH = CLI_MAX_RESOURCE_LENGTH;
#endif
//! Maximum file path length.
#ifndef CLI_MAX_FILE_PATH_LENGTH
static const unsigned int MAX_FILE_PATH_LENGTH = 256;
#else
static const unsigned int MAX_FILE_PATH_LENGTH = CLI_MAX_FILE_PATH_LENGTH;
#endif
// CLI structures.
//! Maximum number of menus per cli.
#ifndef CLI_MAX_MENU_PER_CLI
static const unsigned int MAX_MENU_PER_CLI = 50;
#else
static const unsigned int MAX_MENU_PER_CLI = CLI_MAX_MENU_PER_CLI;
#endif
//! Maximum number of words per syntax node.
#ifndef CLI_MAX_WORDS_PER_NODE
static const unsigned int MAX_WORDS_PER_NODE = 256;
#else
static const unsigned int MAX_WORDS_PER_NODE = CLI_MAX_WORDS_PER_NODE;
#endif
// Command lines.
//! Maximum string length for command lines.
#ifndef CLI_MAX_CMD_LINE_LENGTH
static const unsigned int MAX_CMD_LINE_LENGTH = 2048;
#else
static const unsigned int MAX_CMD_LINE_LENGTH = CLI_MAX_CMD_LINE_LENGTH;
#endif
//! Maximum number of words in a command line.
#ifndef CLI_MAX_CMD_LINE_WORD_COUNT
static const unsigned int MAX_CMD_LINE_WORD_COUNT = 256;
#else
static const unsigned int MAX_CMD_LINE_WORD_COUNT = CLI_MAX_CMD_LINE_WORD_COUNT;
#endif
//! Maximum length for each word in a command line.
#ifndef CLI_MAX_WORD_LENGTH
static const unsigned int MAX_WORD_LENGTH = 256;
#else
static const unsigned int MAX_WORD_LENGTH = CLI_MAX_WORD_LENGTH;
#endif
// Traces / debug.
//! Maximum number of devices that the traces system can stack.
#ifndef CLI_MAX_TRACE_DEVICE_COUNT
static const unsigned int MAX_TRACE_DEVICE_COUNT = 128;
#else
static const unsigned int MAX_TRACE_DEVICE_COUNT = CLI_MAX_TRACE_DEVICE_COUNT;
#endif
//! Maximum number of trace classes that the traces system manages.
#ifndef CLI_MAX_TRACE_CLASS_COUNT
static const unsigned int MAX_TRACE_CLASS_COUNT = 1024;
#else
static const unsigned int MAX_TRACE_CLASS_COUNT = CLI_MAX_TRACE_CLASS_COUNT;
#endif
//! Maximum length of a trace class name.
#ifndef CLI_MAX_TRACE_CLASS_NAME_LENGTH
static const unsigned int MAX_TRACE_CLASS_NAME_LENGTH = MAX_WORD_LENGTH;
#else
static const unsigned int MAX_TRACE_CLASS_NAME_LENGTH = CLI_MAX_TRACE_CLASS_NAME_LENGTH;
#endif
//! Maximum length of a device name (for debug purpose).
#ifndef CLI_MAX_DEVICE_NAME_LENGTH
static const unsigned int MAX_DEVICE_NAME_LENGTH = 256;
#else
static const unsigned int MAX_DEVICE_NAME_LENGTH = CLI_MAX_DEVICE_NAME_LENGTH;
#endif
// Misc
//! Maximum number of cli instances that the cli registry manages.
#ifndef CLI_MAX_CLI_REGISTRY_COUNT
static const unsigned int MAX_CLI_REGISTRY_COUNT = 10;
#else
static const unsigned int MAX_CLI_REGISTRY_COUNT = MAX_CLI_CLI_REGISTRY_COUNT;
#endif
//! Maximum number of input devices that an IOMux instance manages.
#ifndef CLI_MAX_IO_MUX_INPUTS
static const unsigned int MAX_IO_MUX_INPUTS = 100;
#else
static const unsigned int MAX_IO_MUX_INPUTS = CLI_MAX_IO_MUX_INPUTS;
#endif
//! Maximum number of execution contexts.
#ifndef CLI_MAX_EXECUTION_CONTEXTS
static const unsigned int MAX_EXECUTION_CONTEXTS = 10;
#else
static const unsigned int MAX_EXECUTION_CONTEXTS = CLI_MAX_EXECUTION_CONTEXTS;
#endif
CLI_NS_END(cli)
#endif // _CLI_CONSTRAINTS_H_
| 37.437086 | 158 | 0.729347 | [
"object"
] |
32731d23379c3ebba8b42ee0bc7d630c42ba6055 | 2,266 | h | C | System/Library/Frameworks/SoundAnalysis.framework/SNLogMelBasedFeatureExtractorConfiguration.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | System/Library/Frameworks/SoundAnalysis.framework/SNLogMelBasedFeatureExtractorConfiguration.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | System/Library/Frameworks/SoundAnalysis.framework/SNLogMelBasedFeatureExtractorConfiguration.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:10:14 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/Frameworks/SoundAnalysis.framework/SoundAnalysis
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <libobjc.A.dylib/SNProcessorCreating.h>
@protocol SNMLModel;
@class NSString;
@interface SNLogMelBasedFeatureExtractorConfiguration : NSObject <SNProcessorCreating> {
id<SNMLModel> _model;
unsigned _windowLengthFrames;
unsigned _stepSizeFrames;
unsigned _logMelStepSize;
int _outputFeatureSize;
double _sampleRate;
}
@property (readonly) id<SNMLModel> model; //@synthesize model=_model - In the implementation block
@property (readonly) double sampleRate; //@synthesize sampleRate=_sampleRate - In the implementation block
@property (readonly) unsigned windowLengthFrames; //@synthesize windowLengthFrames=_windowLengthFrames - In the implementation block
@property (readonly) unsigned stepSizeFrames; //@synthesize stepSizeFrames=_stepSizeFrames - In the implementation block
@property (readonly) unsigned logMelStepSize; //@synthesize logMelStepSize=_logMelStepSize - In the implementation block
@property (readonly) int outputFeatureSize; //@synthesize outputFeatureSize=_outputFeatureSize - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id<SNMLModel>)model;
-(double)sampleRate;
-(unsigned)windowLengthFrames;
-(unsigned)stepSizeFrames;
-(id)initWithModel:(id)arg1 approximateOverlapFactor:(double)arg2 ;
-(BOOL)isEqualToLogMelBasedFeatureExtractorConfiguration:(id)arg1 ;
-(id)createProcessorWithError:(id*)arg1 ;
-(unsigned)logMelStepSize;
-(int)outputFeatureSize;
@end
| 47.208333 | 150 | 0.704325 | [
"model"
] |
327434edd85e141488bc929f6f30ea48abe42231 | 473 | h | C | src/util/asmap.h | joynicoferna/carpinchocoin | 987284642d94e26c2b3b884c14846068d124a24a | [
"MIT"
] | null | null | null | src/util/asmap.h | joynicoferna/carpinchocoin | 987284642d94e26c2b3b884c14846068d124a24a | [
"MIT"
] | null | null | null | src/util/asmap.h | joynicoferna/carpinchocoin | 987284642d94e26c2b3b884c14846068d124a24a | [
"MIT"
] | null | null | null | // Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CARPINCHO_UTIL_ASMAP_H
#define CARPINCHO_UTIL_ASMAP_H
#include <stdint.h>
#include <vector>
uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip);
bool SanityCheckASMap(const std::vector<bool>& asmap, int bits);
#endif // CARPINCHO_UTIL_ASMAP_H
| 29.5625 | 80 | 0.775899 | [
"vector"
] |
3275c84b3dba1f833b65683cdb518ec9439c92e0 | 3,537 | h | C | include/hw/hx711.h | segwin/beewatch | 59246fc930eab64da1d3abf7f16cb66f3b0b22db | [
"MIT"
] | null | null | null | include/hw/hx711.h | segwin/beewatch | 59246fc930eab64da1d3abf7f16cb66f3b0b22db | [
"MIT"
] | null | null | null | include/hw/hx711.h | segwin/beewatch | 59246fc930eab64da1d3abf7f16cb66f3b0b22db | [
"MIT"
] | null | null | null | //==============================================================================
// Copyright (c) 2018 Eric Seguin, all rights reserved.
//==============================================================================
#pragma once
#include "io/io.h"
#include "io/gpio.h"
#include "util/patterns.hpp"
#include <memory>
namespace beewatch::hw
{
//==============================================================================
/**
* @class HX711
*
* Models a HX711 ADC for load cell measurements
*/
class HX711 : public unique_ownership_t<HX711>,
public io::Input<double>
{
public:
//==============================================================================
/**
* @brief Sets up communication with an HX711 amplifier
*
* NB: Consumes the given GPIOs. They will be released on object
* destruction.
*
* @param [in] doutPin Pin over which to receive serial data
* @param [in] pdSckPin Pin over which to send clock & power signal
*/
HX711(io::GPIO::Ptr&& doutPin, io::GPIO::Ptr&& pdSckPin);
/**
* @brief Destroy HX711 object
*/
virtual ~HX711();
//==============================================================================
virtual double read() override;
private:
//==============================================================================
static constexpr auto NUM_SAMPLES_PER_READ = 8;
//==============================================================================
/**
* @brief Enable HX711 amplifier
*/
void enable();
/**
* @brief Disable HX711 amplifier
*/
void disable();
/**
* @brief Calibrate scale to obtain scale factor & tare weight
*/
void calibrate();
/**
* @brief Tells us whether we can safely interact with the HX711
*
* @returns True if communication is established, false otherwise
*/
bool isReady();
/**
* @brief Tells us whether object is correctly configured
*
* @returns False if GPIOs are not owned or if HX711 is disabled
*/
bool isValid();
//==============================================================================
/**
* @brief Shift in one byte
*
* Sends a clock pulse to read the next byte over DOUT
*/
inline uint8_t shiftIn();
/**
* @brief Read raw output from HX711
*
* @returns 24-bit signed integer value
*/
int32_t readRaw();
/**
* @brief Read an average of the HX711's raw output
*
* @param [in] numSamples Number of reads to average into result
*
* @returns 24-bit signed integer value
*/
int32_t readRawAvg(size_t numSamples);
//==============================================================================
bool _isOn; // Current power state
int _gainSetting; // Amplifier gain factor
int _tare; // Tare (unladen) weight
double _kgPerVolt; // Scale factor obtained through calibration
io::GPIO::Ptr _dout; // Serial data from HX711
io::GPIO::Ptr _pdSck; // Power down & serial clock to HX711
};
} // namespace beewatch::hw
| 29.974576 | 88 | 0.416172 | [
"object"
] |
32797d96e3fb422c7675789cddfc598bc713701f | 1,229 | h | C | coast/modules/Renderer/AnythingContentRenderer.h | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/Renderer/AnythingContentRenderer.h | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | coast/modules/Renderer/AnythingContentRenderer.h | zer0infinity/CuteForCoast | 37d933c5fe2e0ce9a801f51b2aa27c7a18098511 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
#ifndef _AnythingContentRenderer_H
#define _AnythingContentRenderer_H
#include "Renderer.h"
//---- AnythingContentRenderer -----------------------------------------------------------
//! Render the content of an Anything
/*!
\par Configuration
\code
{
/Input Rendererspec mandatory, RendererSpec used to lookup the Anything in Context
/Pretty long optional, default=1, pretty Print mode
/XmpTags optional, add XMP tags
{
/CSSTag additional style class to be placed within pre tag
/PreTag additional formatting, goes after <xmp> tag
/PostTag additional formatting, goes before </xmp> tag
}
}
\endcode
*/
class AnythingContentRenderer : public Renderer
{
public:
AnythingContentRenderer(const char *name);
~AnythingContentRenderer();
virtual void RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config);
};
#endif //ifndef _AnythingContentRenderer_H
| 29.97561 | 102 | 0.719284 | [
"render"
] |
327d95d5a91a93e0e4f4e467ed9596e32ede4abf | 12,679 | c | C | 3party/gtk+-3.12.1/gdk/broadway/gdkdisplay-broadway.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 1 | 2016-01-02T14:39:07.000Z | 2016-01-02T14:39:07.000Z | 3party/gtk+-3.12.1/gdk/broadway/gdkdisplay-broadway.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 4 | 2019-12-20T06:13:24.000Z | 2021-07-03T16:28:18.000Z | 3party/gtk+-3.12.1/gdk/broadway/gdkdisplay-broadway.c | kongaraju/antkorp | 3453d543d659e3420d5bc4b536016bb1d097d7ec | [
"CC-BY-3.0",
"Apache-2.0"
] | 2 | 2015-09-17T16:40:10.000Z | 2016-11-17T15:56:42.000Z | /* GDK - The GIMP Drawing Kit
* gdkdisplay-broadway.c
*
* Copyright 2001 Sun Microsystems Inc.
* Copyright (C) 2004 Nokia Corporation
*
* Erwann Chenede <erwann.chenede@sun.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "gdkdisplay-broadway.h"
#include "gdkdisplay.h"
#include "gdkeventsource.h"
#include "gdkscreen.h"
#include "gdkscreen-broadway.h"
#include "gdkinternals.h"
#include "gdkdeviceprivate.h"
#include "gdkdevicemanager-broadway.h"
#include <glib.h>
#include <glib/gprintf.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/types.h>
static void gdk_broadway_display_dispose (GObject *object);
static void gdk_broadway_display_finalize (GObject *object);
#if 0
#define DEBUG_WEBSOCKETS 1
#endif
G_DEFINE_TYPE (GdkBroadwayDisplay, gdk_broadway_display, GDK_TYPE_DISPLAY)
static void
gdk_broadway_display_init (GdkBroadwayDisplay *display)
{
display->id_ht = g_hash_table_new (NULL, NULL);
}
static void
gdk_event_init (GdkDisplay *display)
{
GdkBroadwayDisplay *broadway_display;
broadway_display = GDK_BROADWAY_DISPLAY (display);
broadway_display->event_source = _gdk_broadway_event_source_new (display);
}
static void
gdk_broadway_display_init_input (GdkDisplay *display)
{
GdkBroadwayDisplay *broadway_display;
GdkDeviceManager *device_manager;
GdkDevice *device;
GList *list, *l;
broadway_display = GDK_BROADWAY_DISPLAY (display);
device_manager = gdk_display_get_device_manager (display);
/* For backwards compatibility, just add
* floating devices that are not keyboards.
*/
list = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_FLOATING);
for (l = list; l; l = l->next)
{
device = l->data;
if (gdk_device_get_source (device) == GDK_SOURCE_KEYBOARD)
continue;
broadway_display->input_devices = g_list_prepend (broadway_display->input_devices,
g_object_ref (l->data));
}
g_list_free (list);
/* Now set "core" pointer to the first
* master device that is a pointer.
*/
list = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
for (l = list; l; l = l->next)
{
device = l->data;
if (gdk_device_get_source (device) != GDK_SOURCE_MOUSE)
continue;
display->core_pointer = device;
break;
}
/* Add the core pointer to the devices list */
broadway_display->input_devices = g_list_prepend (broadway_display->input_devices,
g_object_ref (display->core_pointer));
g_list_free (list);
}
GdkDisplay *
_gdk_broadway_display_open (const gchar *display_name)
{
GdkDisplay *display;
GdkBroadwayDisplay *broadway_display;
GError *error = NULL;
display = g_object_new (GDK_TYPE_BROADWAY_DISPLAY, NULL);
broadway_display = GDK_BROADWAY_DISPLAY (display);
/* initialize the display's screens */
broadway_display->screens = g_new (GdkScreen *, 1);
broadway_display->screens[0] = _gdk_broadway_screen_new (display, 0);
/* We need to initialize events after we have the screen
* structures in places
*/
_gdk_broadway_screen_events_init (broadway_display->screens[0]);
/*set the default screen */
broadway_display->default_screen = broadway_display->screens[0];
display->device_manager = _gdk_broadway_device_manager_new (display);
gdk_event_init (display);
gdk_broadway_display_init_input (display);
_gdk_broadway_display_init_dnd (display);
_gdk_broadway_screen_setup (broadway_display->screens[0]);
if (display_name == NULL)
display_name = g_getenv ("BROADWAY_DISPLAY");
broadway_display->server = _gdk_broadway_server_new (display_name, &error);
if (broadway_display->server == NULL)
{
g_printerr ("Unable to init server: %s\n", error->message);
g_error_free (error);
return NULL;
}
g_signal_emit_by_name (display, "opened");
return display;
}
static const gchar *
gdk_broadway_display_get_name (GdkDisplay *display)
{
g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
return (gchar *) "Broadway";
}
static GdkScreen *
gdk_broadway_display_get_default_screen (GdkDisplay *display)
{
g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
return GDK_BROADWAY_DISPLAY (display)->default_screen;
}
static void
gdk_broadway_display_beep (GdkDisplay *display)
{
g_return_if_fail (GDK_IS_DISPLAY (display));
}
static void
gdk_broadway_display_sync (GdkDisplay *display)
{
GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (display);
g_return_if_fail (GDK_IS_BROADWAY_DISPLAY (display));
_gdk_broadway_server_sync (broadway_display->server);
}
static void
gdk_broadway_display_flush (GdkDisplay *display)
{
GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (display);
g_return_if_fail (GDK_IS_BROADWAY_DISPLAY (display));
_gdk_broadway_server_flush (broadway_display->server);
}
static gboolean
gdk_broadway_display_has_pending (GdkDisplay *display)
{
return FALSE;
}
static GdkWindow *
gdk_broadway_display_get_default_group (GdkDisplay *display)
{
g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
return NULL;
}
static void
gdk_broadway_display_dispose (GObject *object)
{
GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (object);
g_list_foreach (broadway_display->input_devices, (GFunc) g_object_run_dispose, NULL);
_gdk_screen_close (broadway_display->screens[0]);
if (broadway_display->event_source)
{
g_source_destroy (broadway_display->event_source);
g_source_unref (broadway_display->event_source);
broadway_display->event_source = NULL;
}
G_OBJECT_CLASS (gdk_broadway_display_parent_class)->dispose (object);
}
static void
gdk_broadway_display_finalize (GObject *object)
{
GdkBroadwayDisplay *broadway_display = GDK_BROADWAY_DISPLAY (object);
/* Keymap */
if (broadway_display->keymap)
g_object_unref (broadway_display->keymap);
_gdk_broadway_cursor_display_finalize (GDK_DISPLAY_OBJECT(broadway_display));
/* input GdkDevice list */
g_list_free_full (broadway_display->input_devices, g_object_unref);
/* Free all GdkScreens */
g_object_unref (broadway_display->screens[0]);
g_free (broadway_display->screens);
G_OBJECT_CLASS (gdk_broadway_display_parent_class)->finalize (object);
}
void
_gdk_broadway_display_make_default (GdkDisplay *display)
{
}
static void
gdk_broadway_display_notify_startup_complete (GdkDisplay *display,
const gchar *startup_id)
{
}
static gboolean
gdk_broadway_display_supports_selection_notification (GdkDisplay *display)
{
return FALSE;
}
static gboolean
gdk_broadway_display_request_selection_notification (GdkDisplay *display,
GdkAtom selection)
{
return FALSE;
}
static gboolean
gdk_broadway_display_supports_clipboard_persistence (GdkDisplay *display)
{
return FALSE;
}
static void
gdk_broadway_display_store_clipboard (GdkDisplay *display,
GdkWindow *clipboard_window,
guint32 time_,
const GdkAtom *targets,
gint n_targets)
{
}
static gboolean
gdk_broadway_display_supports_shapes (GdkDisplay *display)
{
return FALSE;
}
static gboolean
gdk_broadway_display_supports_input_shapes (GdkDisplay *display)
{
return FALSE;
}
static gboolean
gdk_broadway_display_supports_composite (GdkDisplay *display)
{
return FALSE;
}
static GList *
gdk_broadway_display_list_devices (GdkDisplay *display)
{
g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
return GDK_BROADWAY_DISPLAY (display)->input_devices;
}
static gulong
gdk_broadway_display_get_next_serial (GdkDisplay *display)
{
GdkBroadwayDisplay *broadway_display;
broadway_display = GDK_BROADWAY_DISPLAY (display);
return _gdk_broadway_server_get_next_serial (broadway_display->server);
}
static void
gdk_broadway_display_event_data_copy (GdkDisplay *display,
const GdkEvent *src,
GdkEvent *dst)
{
}
static void
gdk_broadway_display_event_data_free (GdkDisplay *display,
GdkEvent *event)
{
}
void
gdk_broadway_display_show_keyboard (GdkBroadwayDisplay *display)
{
g_return_if_fail (GDK_IS_BROADWAY_DISPLAY (display));
_gdk_broadway_server_set_show_keyboard (display->server, TRUE);
}
void
gdk_broadway_display_hide_keyboard (GdkBroadwayDisplay *display)
{
g_return_if_fail (GDK_IS_BROADWAY_DISPLAY (display));
_gdk_broadway_server_set_show_keyboard (display->server, FALSE);
}
static void
gdk_broadway_display_class_init (GdkBroadwayDisplayClass * class)
{
GObjectClass *object_class = G_OBJECT_CLASS (class);
GdkDisplayClass *display_class = GDK_DISPLAY_CLASS (class);
object_class->dispose = gdk_broadway_display_dispose;
object_class->finalize = gdk_broadway_display_finalize;
display_class->window_type = GDK_TYPE_BROADWAY_WINDOW;
display_class->get_name = gdk_broadway_display_get_name;
display_class->get_default_screen = gdk_broadway_display_get_default_screen;
display_class->beep = gdk_broadway_display_beep;
display_class->sync = gdk_broadway_display_sync;
display_class->flush = gdk_broadway_display_flush;
display_class->has_pending = gdk_broadway_display_has_pending;
display_class->queue_events = _gdk_broadway_display_queue_events;
display_class->get_default_group = gdk_broadway_display_get_default_group;
display_class->supports_selection_notification = gdk_broadway_display_supports_selection_notification;
display_class->request_selection_notification = gdk_broadway_display_request_selection_notification;
display_class->supports_clipboard_persistence = gdk_broadway_display_supports_clipboard_persistence;
display_class->store_clipboard = gdk_broadway_display_store_clipboard;
display_class->supports_shapes = gdk_broadway_display_supports_shapes;
display_class->supports_input_shapes = gdk_broadway_display_supports_input_shapes;
display_class->supports_composite = gdk_broadway_display_supports_composite;
display_class->list_devices = gdk_broadway_display_list_devices;
display_class->get_cursor_for_type = _gdk_broadway_display_get_cursor_for_type;
display_class->get_cursor_for_name = _gdk_broadway_display_get_cursor_for_name;
display_class->get_cursor_for_surface = _gdk_broadway_display_get_cursor_for_surface;
display_class->get_default_cursor_size = _gdk_broadway_display_get_default_cursor_size;
display_class->get_maximal_cursor_size = _gdk_broadway_display_get_maximal_cursor_size;
display_class->supports_cursor_alpha = _gdk_broadway_display_supports_cursor_alpha;
display_class->supports_cursor_color = _gdk_broadway_display_supports_cursor_color;
display_class->before_process_all_updates = _gdk_broadway_display_before_process_all_updates;
display_class->after_process_all_updates = _gdk_broadway_display_after_process_all_updates;
display_class->get_next_serial = gdk_broadway_display_get_next_serial;
display_class->notify_startup_complete = gdk_broadway_display_notify_startup_complete;
display_class->event_data_copy = gdk_broadway_display_event_data_copy;
display_class->event_data_free = gdk_broadway_display_event_data_free;
display_class->create_window_impl = _gdk_broadway_display_create_window_impl;
display_class->get_keymap = _gdk_broadway_display_get_keymap;
display_class->get_selection_owner = _gdk_broadway_display_get_selection_owner;
display_class->set_selection_owner = _gdk_broadway_display_set_selection_owner;
display_class->send_selection_notify = _gdk_broadway_display_send_selection_notify;
display_class->get_selection_property = _gdk_broadway_display_get_selection_property;
display_class->convert_selection = _gdk_broadway_display_convert_selection;
display_class->text_property_to_utf8_list = _gdk_broadway_display_text_property_to_utf8_list;
display_class->utf8_to_string_target = _gdk_broadway_display_utf8_to_string_target;
}
| 30.260143 | 104 | 0.784762 | [
"object"
] |
327ed3bd6040624fb4af9b9831fb42e8ee759a6b | 1,753 | h | C | src/databases/lata/avtlataWriter.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 226 | 2018-12-29T01:13:49.000Z | 2022-03-30T19:16:31.000Z | src/databases/lata/avtlataWriter.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 5,100 | 2019-01-14T18:19:25.000Z | 2022-03-31T23:08:36.000Z | src/databases/lata/avtlataWriter.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 84 | 2019-01-24T17:41:50.000Z | 2022-03-10T10:01:46.000Z | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
// ************************************************************************* //
// avtlataWriter.h //
// ************************************************************************* //
#ifndef AVT_lata_WRITER_H
#define AVT_lata_WRITER_H
#include <avtDatabaseWriter.h>
#include <string>
// ****************************************************************************
// Class: avtlataWriter
//
// Purpose:
// A module that writes out lata files.
//
// Programmer: fauchet -- generated by xml2avt
//
// ****************************************************************************
class
avtlataWriter : public avtDatabaseWriter
{
public:
avtlataWriter();
virtual ~avtlataWriter() {;};
protected:
std::string stem;
vector<string> filenames_var;
const avtDatabaseMetaData *md_;
// deux methodes OpenFile (car changement d'interface entre 16 et 161
double ftime;
virtual void OpenFile(const std::string &);
virtual void OpenFile(const std::string &, int nb);
virtual void WriteHeaders(const avtDatabaseMetaData *,
const std::vector<std::string> &,
const std::vector<std::string> &,
const std::vector<std::string> &);
virtual void WriteChunk(vtkDataSet *, int);
virtual void CloseFile(void);
void write_data(vtkDataArray *arr,const string& pos,string& filename);
};
#endif
| 32.462963 | 79 | 0.50656 | [
"vector"
] |
32803cce736b19cc178bd949f0830024f2671d49 | 12,732 | h | C | ogsr_engine/xrGame/ai/monsters/burer/burer_state_attack_tele_inline.h | WarezzK/OGSE-WarezzKCZ-Engine | 9d5a594edd7d8f2edf5e1d831f380bc817400e17 | [
"Apache-2.0"
] | 3 | 2019-09-10T13:37:08.000Z | 2021-05-18T14:53:29.000Z | ogsr_engine/xrGame/ai/monsters/burer/burer_state_attack_tele_inline.h | Rikoshet-234/rebirth_engine | 7ad4e8a711434e8346b7c97b3a82447695418344 | [
"Apache-2.0"
] | null | null | null | ogsr_engine/xrGame/ai/monsters/burer/burer_state_attack_tele_inline.h | Rikoshet-234/rebirth_engine | 7ad4e8a711434e8346b7c97b3a82447695418344 | [
"Apache-2.0"
] | 2 | 2020-06-26T11:50:59.000Z | 2020-12-30T11:07:31.000Z | #pragma once
#include "../../../level.h"
#define GOOD_DISTANCE_FOR_TELE 15.f
#define MAX_TIME_CHECK_FAILURE 6000
template <typename Object>
CStateBurerAttackTele<Object>::CStateBurerAttackTele(Object *obj) : inherited(obj)
{
m_anim_end_tick = 0;
m_last_grenade_scan = 0;
}
template <typename Object>
void CStateBurerAttackTele<Object>::initialize()
{
inherited::initialize ();
m_action = ACTION_TELE_STARTED;
selected_object = 0;
SelectObjects ();
time_started = 0;
m_anim_end_tick = 0;
m_last_grenade_scan = 0;
m_initial_health = object->conditions().GetHealth();
m_end_tick = current_time() + object->m_tele_max_time;
object->set_script_capture (false);
}
template <typename Object>
void CStateBurerAttackTele<Object>::execute()
{
HandleGrenades ();
// if ( object->EnemyMan.see_enemy_now() )
// {
// m_last_saw_enemy_tick = current_time();
// }
switch ( m_action )
{
case ACTION_TELE_STARTED:
object->anim().set_override_animation (eAnimTelekinesis, 0);
if ( !time_started )
{
float const time = object->anim().get_animation_length (eAnimTelekinesis, 0);
m_anim_end_tick = current_time() + TTime(time*1000);
time_started = Device.dwTimeGlobal;
}
else
{
if ( current_time() > m_anim_end_tick )
{
m_action = ACTION_TELE_CONTINUE;
}
}
break;
case ACTION_TELE_CONTINUE:
object->anim().set_override_animation (eAnimTelekinesis, 1);
ExecuteTeleContinue ();
break;
case ACTION_TELE_FIRE:
{
object->anim().set_override_animation (eAnimTeleFire, 0);
ExecuteTeleFire ();
float const time = object->anim().get_animation_length (eAnimTeleFire, 0);
m_anim_end_tick = current_time() + TTime(time*1000);
m_action = ACTION_WAIT_FIRE_END;
break;
}
case ACTION_WAIT_FIRE_END:
object->anim().set_override_animation (eAnimTeleFire, 0);
if ( current_time() > m_anim_end_tick )
{
if ( IsActiveObjects() )
{
m_action = ACTION_TELE_CONTINUE;
}
else
{
m_action = ACTION_COMPLETED;
}
}
case ACTION_COMPLETED:
break;
}
object->face_enemy ();
}
template <typename Object>
void CStateBurerAttackTele<Object>::deactivate()
{
tele_objects.clear ();
// clear particles on active objects
if ( object->CTelekinesis::is_active() )
{
for (u32 i=0; i<object->CTelekinesis::get_objects_total_count(); i++)
{
CPhysicsShellHolder* cur_object = object->CTelekinesis::get_object_by_index(i).get_object();
if ( !cur_object || !cur_object->m_pPhysicsShell || !cur_object->m_pPhysicsShell->isActive() )
{
continue;
}
if ( CGrenade* grenade = smart_cast<CGrenade*>(cur_object) )
{
grenade->set_destroy_callback (NULL);
}
}
}
for ( u32 i=0; i<object->CTelekinesis::get_objects_total_count(); ++i )
{
CPhysicsShellHolder* const cur_object = object->CTelekinesis::get_object_by_index(i).object;
if ( !cur_object || !cur_object->m_pPhysicsShell || !cur_object->m_pPhysicsShell->isActive() )
{
continue;
}
object->StopTeleObjectParticle (cur_object);
}
FireAllToEnemy ();
object->CTelekinesis::deactivate ();
object->set_script_capture (true);
}
template <typename Object>
void CStateBurerAttackTele<Object>::finalize()
{
deactivate ();
inherited::finalize ();
}
template <typename Object>
void CStateBurerAttackTele<Object>::critical_finalize()
{
deactivate ();
inherited::critical_finalize ();
}
template <typename Object>
bool CStateBurerAttackTele<Object>::check_start_conditions()
{
return CheckTeleStart();
}
template <typename Object>
bool CStateBurerAttackTele<Object>::check_completion()
{
float dist = object->EnemyMan.get_enemy()->Position().distance_to(object->Position());
if ( dist < object->m_tele_min_distance )
{
return true;
}
if ( dist > object->m_tele_max_distance )
{
return true;
}
if ( object->conditions().GetHealth() < m_initial_health )
{
return true;
}
if ( current_time() > m_end_tick )
{
return true;
}
if ( m_action == ACTION_COMPLETED )
{
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
template <typename Object>
void CStateBurerAttackTele<Object>::FindFreeObjects(xr_vector<CObject*> &tpObjects, const Fvector &pos)
{
Level().ObjectSpace.GetNearest (tpObjects, pos, object->m_tele_find_radius, NULL);
for (u32 i=0;i<tpObjects.size();i++) {
CPhysicsShellHolder *obj = smart_cast<CPhysicsShellHolder *>(tpObjects[i]);
CCustomMonster *custom_monster = smart_cast<CCustomMonster *>(tpObjects[i]);
CGrenade *grenade = smart_cast<CGrenade *>(tpObjects[i]);
if (grenade || // grenades are handled by HandleGrenades function
!obj ||
!obj->PPhysicsShell() ||
!obj->PPhysicsShell()->isActive()||
custom_monster ||
(obj->spawn_ini() && obj->spawn_ini()->section_exist("ph_heavy")) ||
(obj->m_pPhysicsShell->getMass() < object->m_tele_object_min_mass) ||
(obj->m_pPhysicsShell->getMass() > object->m_tele_object_max_mass) ||
(obj == object) ||
object->CTelekinesis::is_active_object(obj) ||
( pSettings->line_exist( obj->cNameSect().c_str(), "ph_heavy" ) && pSettings->r_bool( obj->cNameSect().c_str(), "ph_heavy" ) ) ||
obj->hasFixedBones() ||
!obj->m_pPhysicsShell->get_ApplyByGravity()) continue;
tele_objects.push_back(obj);
}
}
template <typename Object>
void CStateBurerAttackTele<Object>::FindObjects()
{
const size_t res_size = tele_objects.size();
tele_objects.clear ();
m_nearest.clear();
m_nearest.reserve(res_size);
FindFreeObjects(m_nearest, object->EnemyMan.get_enemy()->Position());
FindFreeObjects (m_nearest, object->Position());
float dist = object->EnemyMan.get_enemy()->Position().distance_to(object->Position());
Fvector dir;
dir.sub(object->EnemyMan.get_enemy()->Position(), object->Position());
dir.normalize();
Fvector pos;
pos.mad (object->Position(), dir, dist / 2.f);
FindFreeObjects (m_nearest, pos);
tele_objects.erase(std::unique(tele_objects.begin(), tele_objects.end()), tele_objects.end());
}
template <typename Object>
void CStateBurerAttackTele<Object>::FireAllToEnemy()
{
if ( !object->CTelekinesis::is_active() )
{
return;
}
if ( !object->EnemyMan.get_enemy() )
{
return;
}
Fvector enemy_pos;
enemy_pos = get_head_position(const_cast<CEntityAlive*>(object->EnemyMan.get_enemy()));
for ( u32 i=0; i<object->CTelekinesis::get_objects_count(); ++i )
{
u32 const prev_num_objects = object->CTelekinesis::get_objects_count();
CPhysicsShellHolder* const cur_object = object->CTelekinesis::get_object_by_index(i).object;
if ( !cur_object )
{
continue;
}
float const dist_to_enemy = cur_object->Position().distance_to(enemy_pos);
float const fire_time = dist_to_enemy / object->m_tele_fly_velocity;
object->CTelekinesis::fire_t (cur_object, enemy_pos, fire_time);
u32 const new_num_objects = object->CTelekinesis::get_objects_count();
if ( new_num_objects < prev_num_objects )
{
VERIFY (new_num_objects == prev_num_objects-1);
--i;
}
}
//object->CTelekinesis::fire_all(enemy_pos);
object->sound().play (CBurer::eMonsterSoundTeleAttack);
}
template <typename Object>
void CStateBurerAttackTele<Object>::ExecuteTeleContinue()
{
if (time_started + object->m_tele_time_to_hold > Device.dwTimeGlobal) return;
if (!object->EnemyMan.see_enemy_now()) return;
bool object_found = false;
CTelekineticObject tele_object;
u32 i=0;
while (i < object->CTelekinesis::get_objects_count()) {
tele_object = object->CTelekinesis::get_object_by_index(i);
if ((tele_object.get_state() == TS_Keep) && (tele_object.time_keep_started + 1500 < Device.dwTimeGlobal)) {
object_found = true;
break;
} else i++;
}
if (object_found) {
m_action = ACTION_TELE_FIRE;
selected_object = tele_object.get_object();
} else {
if (!IsActiveObjects() || (time_started + MAX_TIME_CHECK_FAILURE < Device.dwTimeGlobal)) {
m_action = ACTION_COMPLETED;
}
}
}
#define HEAD_OFFSET_INDOOR 1.f
#define HEAD_OFFSET_OUTDOOR 5.f
template <typename Object>
void CStateBurerAttackTele<Object>::ExecuteTeleFire()
{
Fvector enemy_pos;
enemy_pos = get_head_position(const_cast<CEntityAlive*>(object->EnemyMan.get_enemy()));
float const dist_to_enemy = selected_object->Position().distance_to(enemy_pos);
float const fire_time = dist_to_enemy / object->m_tele_fly_velocity;
object->CTelekinesis::fire_t (selected_object,enemy_pos, fire_time);
object->StopTeleObjectParticle (selected_object);
object->sound().play (CBurer::eMonsterSoundTeleAttack);
}
template <typename Object>
bool CStateBurerAttackTele<Object>::IsActiveObjects()
{
return (object->CTelekinesis::get_objects_count() > 0);
}
template <typename Object>
bool CStateBurerAttackTele<Object>::CheckTeleStart()
{
if (IsActiveObjects()) return false;
float dist = object->Position().distance_to(object->EnemyMan.get_enemy()->Position());
if ( dist < object->m_tele_min_distance ) return false;
if ( dist > object->m_tele_max_distance ) return false;
FindObjects();
if (tele_objects.empty()) return false;
return true;
}
class best_object_predicate {
Fvector enemy_pos;
Fvector monster_pos;
public:
best_object_predicate(const Fvector &m_pos, const Fvector &pos) {
monster_pos = m_pos;
enemy_pos = pos;
}
bool operator() (const CGameObject *tpObject1, const CGameObject *tpObject2) const
{
float dist1 = monster_pos.distance_to(tpObject1->Position());
float dist2 = enemy_pos.distance_to(tpObject2->Position());
float dist3 = enemy_pos.distance_to(monster_pos);
return ((dist1 < dist3) && (dist2 > dist3));
};
};
class best_object_predicate2 {
Fvector enemy_pos;
Fvector monster_pos;
public:
best_object_predicate2(const Fvector &m_pos, const Fvector &pos) {
monster_pos = m_pos;
enemy_pos = pos;
}
bool operator() (const CGameObject *tpObject1, const CGameObject *tpObject2) const
{
float dist1 = enemy_pos.distance_to(tpObject1->Position());
float dist2 = enemy_pos.distance_to(tpObject2->Position());
return dist1 < dist2;
}
};
template <typename Object>
void CStateBurerAttackTele<Object>::SelectObjects()
{
std::sort(tele_objects.begin(),tele_objects.end(),best_object_predicate2(object->Position(), object->EnemyMan.get_enemy()->Position()));
for ( u32 i=0; i<tele_objects.size(); ++i )
{
CPhysicsShellHolder *obj = tele_objects[i];
float height = object->m_tele_object_height;
if ( object->m_monster_type == CBaseMonster::eMonsterTypeIndoor )
{
height *= 0.7f;
}
bool const rotate = object->m_monster_type != CBaseMonster::eMonsterTypeIndoor;
CTelekineticObject *tele_obj = object->CTelekinesis::activate(obj,
object->m_tele_raise_speed,
height,
10000,
rotate);
tele_obj->set_sound (object->sound_tele_hold,object->sound_tele_throw);
object->StartTeleObjectParticle (obj);
tele_objects[i] = tele_objects[tele_objects.size()-1];
tele_objects.pop_back ();
if ( object->CTelekinesis::get_objects_count() >= object->m_tele_max_handled_objects )
{
break;
}
}
}
template <typename Object>
void xr_stdcall CStateBurerAttackTele<Object>::OnGrenadeDestroyed (CGrenade* const grenade)
{
object->CTelekinesis::remove_links (grenade);
}
template <typename Object>
void CStateBurerAttackTele<Object>::HandleGrenades ()
{
if ( current_time() < m_last_grenade_scan + 1000 )
{
return;
}
m_nearest.clear();
Level().ObjectSpace.GetNearest (m_nearest, object->Position(), object->m_tele_find_radius, NULL);
for ( u32 i=0; i<m_nearest.size(); ++i )
{
CGrenade* grenade = smart_cast<CGrenade *>(m_nearest[i]);
if ( !grenade ||
!grenade->PPhysicsShell() ||
!grenade->PPhysicsShell()->isActive() ||
object->CTelekinesis::is_active_object(grenade) ||
!grenade->m_pPhysicsShell->get_ApplyByGravity() )
{
continue;
}
grenade->set_destroy_callback ( CGrenade::destroy_callback(this,
&CStateBurerAttackTele<Object>::OnGrenadeDestroyed) );
float const height = 2.5f;
bool const rotate = false;
CTelekineticObject* tele_obj= object->CTelekinesis::activate(grenade, 3.f, height, 10000, rotate);
tele_obj->set_sound (object->sound_tele_hold, object->sound_tele_throw);
object->StartTeleObjectParticle (grenade);
if ( object->CTelekinesis::get_objects_count() >= object->m_tele_max_handled_objects + 1 )
{
break;
}
}
}
| 26.469854 | 137 | 0.693999 | [
"object"
] |
32824802c4c309634a36febe782fffed09b4fcac | 5,293 | h | C | libs/Microsoft.MixedReality.WebRTC.Native/src/media/external_video_track_source.h | rabbit-go/MixedReality-WebRTC | d0433bb8da75c7bd585e17ba1769072f55c7d115 | [
"MIT"
] | null | null | null | libs/Microsoft.MixedReality.WebRTC.Native/src/media/external_video_track_source.h | rabbit-go/MixedReality-WebRTC | d0433bb8da75c7bd585e17ba1769072f55c7d115 | [
"MIT"
] | null | null | null | libs/Microsoft.MixedReality.WebRTC.Native/src/media/external_video_track_source.h | rabbit-go/MixedReality-WebRTC | d0433bb8da75c7bd585e17ba1769072f55c7d115 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "mrs_errors.h"
#include "refptr.h"
#include "tracked_object.h"
#include "video_frame.h"
#include "external_video_track_source_interop.h"
namespace Microsoft::MixedReality::WebRTC {
class ExternalVideoTrackSource;
/// Frame request for an external video source producing video frames encoded in
/// I420 format, with optional Alpha (opacity) plane.
struct I420AVideoFrameRequest {
/// Video track source the request is related to.
ExternalVideoTrackSource& track_source_;
/// Video frame timestamp, in milliseconds.
std::int64_t timestamp_ms_;
/// Unique identifier of the request.
const std::uint32_t request_id_;
/// Complete the request by making the track source consume the given video
/// frame and have it deliver the frame to all its video tracks.
Result CompleteRequest(const I420AVideoFrame& frame_view);
};
/// Custom video source producing video frames encoded in I420 format, with
/// optional Alpha (opacity) plane.
class I420AExternalVideoSource : public RefCountedBase {
public:
/// Produce a video frame for a request initiated by an external track source.
///
/// This callback is invoked automatically by the track source whenever a new
/// video frame is needed (pull model). The custom video source implementation
/// must either return an error, or produce a new video frame and call the
/// |CompleteRequest()| request on the |frame_request| object.
virtual Result FrameRequested(I420AVideoFrameRequest& frame_request) = 0;
};
/// Frame request for an external video source producing video frames encoded in
/// ARGB 32-bit-per-pixel format.
struct Argb32VideoFrameRequest {
/// Video track source the request is related to.
ExternalVideoTrackSource& track_source_;
/// Video frame timestamp, in milliseconds.
std::int64_t timestamp_ms_;
/// Unique identifier of the request.
const std::uint32_t request_id_;
/// Complete the request by making the track source consume the given video
/// frame and have it deliver the frame to all its video tracks.
Result CompleteRequest(const Argb32VideoFrame& frame_view);
};
/// Custom video source producing vidoe frames encoded in ARGB 32-bit-per-pixel
/// format.
class Argb32ExternalVideoSource : public RefCountedBase {
public:
/// Produce a video frame for a request initiated by an external track source.
///
/// This callback is invoked automatically by the track source whenever a new
/// video frame is needed (pull model). The custom video source implementation
/// must either return an error, or produce a new video frame and call the
/// |CompleteRequest()| request on the |track_source| object, passing the
/// |request_id| of the current request being completed.
virtual Result FrameRequested(Argb32VideoFrameRequest& frame_request) = 0;
};
/// Video track source acting as an adapter for an external source of raw
/// frames.
class ExternalVideoTrackSource : public TrackedObject {
public:
/// Helper to create an external video track source from a custom I420A video
/// frame request callback.
static RefPtr<ExternalVideoTrackSource> createFromI420A(
RefPtr<I420AExternalVideoSource> video_source);
/// Helper to create an external video track source from a custom ARGB32 video
/// frame request callback.
static RefPtr<ExternalVideoTrackSource> createFromArgb32(
RefPtr<Argb32ExternalVideoSource> video_source);
/// Start the video capture. This will begin to produce video frames and start
/// calling the video frame callback.
virtual void StartCapture() = 0;
/// Complete a given video frame request with the provided I420A frame.
/// The caller must know the source expects an I420A frame; there is no check
/// to confirm the source is I420A-based or ARGB32-based.
virtual Result CompleteRequest(uint32_t request_id,
int64_t timestamp_ms,
const I420AVideoFrame& frame) = 0;
/// Complete a given video frame request with the provided ARGB32 frame.
/// The caller must know the source expects an ARGB32 frame; there is no check
/// to confirm the source is I420A-based or ARGB32-based.
virtual Result CompleteRequest(uint32_t request_id,
int64_t timestamp_ms,
const Argb32VideoFrame& frame) = 0;
/// Stop the video capture. This will stop producing video frames.
virtual void StopCapture() = 0;
/// Shutdown the source and release the buffer adapter and its callback.
virtual void Shutdown() noexcept = 0;
};
namespace detail {
//
// Helpers
//
/// Create an I420A external video track source wrapping the given interop
/// callback.
RefPtr<ExternalVideoTrackSource> ExternalVideoTrackSourceCreateFromI420A(
mrsRequestExternalI420AVideoFrameCallback callback,
void* user_data);
/// Create an ARGB32 external video track source wrapping the given interop
/// callback.
RefPtr<ExternalVideoTrackSource> ExternalVideoTrackSourceCreateFromArgb32(
mrsRequestExternalArgb32VideoFrameCallback callback,
void* user_data);
} // namespace detail
} // namespace Microsoft::MixedReality::WebRTC
| 38.919118 | 80 | 0.739845 | [
"object",
"model"
] |
32868cc8d41fbdc1e90d42f934cbed2bc986ef28 | 45,397 | h | C | libc/libgloss/m68k/fido.h | The0x539/wasp | 5f83aab7bf0c0915b1d3491034d35b091c7aebdf | [
"MIT"
] | 453 | 2016-07-29T23:26:30.000Z | 2022-02-21T01:09:13.000Z | libc/libgloss/m68k/fido.h | The0x539/wasp | 5f83aab7bf0c0915b1d3491034d35b091c7aebdf | [
"MIT"
] | 175 | 2018-05-30T03:06:15.000Z | 2019-02-06T23:54:24.000Z | libc/libgloss/m68k/fido.h | The0x539/wasp | 5f83aab7bf0c0915b1d3491034d35b091c7aebdf | [
"MIT"
] | 57 | 2016-07-29T23:34:09.000Z | 2021-07-13T18:17:02.000Z | /**
******************************************************************************
* @defgroup FIDOmemmap.h Memory map include file for Fido
****************************************************************************@{
*
* @par COPYRIGHT:
* COPYRIGHT 2005-2006 INNOVASIC SEMICONDUCTOR, ALL RIGHTS RESERVED.\n
* Part of the FIDO REALTIME SUPPORT LIBRARY
*
* @par Created:
* Wed, 1 June 2005 David L. Deis [DD]
*
* @par CVS-Info:
* $Revision$
* $Author$
* $Date$
*
* @par Description:
* Contains board-specific and onchip memory-mapped register and internal
* memory definitions.
*/
#ifndef FIDOmemmap_h
#define FIDOmemmap_h
/******************************************************************************
* Board-specific definitions specify the location and size of all external
* memories and the board operating frequency. These values must be specified
* based upon the physical board design. These definitions are used by the
* software libraries.
******************************************************************************
*/
/**
* External memory base addresses controlled by chip selects 0,1, and 2.
* Specify -1 for any absent memories. The defaults are for the Innovasic
* development board.
*/
#define FLASH_BASE_ADDR 0x00000000
#define FLASH_SIZE (8 * 1024 * 1024L)
#define SDRAM_BASE_ADDR 0x02000000
#define SDRAM_SIZE (8 * 1024 * 1024L)
#define SRAM_BASE_ADDR 0x03000000
#define SRAM_SIZE (1 * 1024 * 1024L)
/**
* System clock frequency
*/
#define FIDO_CLOCK_FREQUENCY (66 * (1000 * 1000))
/******************************************************************************
* Onchip memory-mapped register and internal memory definitions.
******************************************************************************
*/
/**
* Memory offset register value loaded during crt0. This offset applies to
* the onchip SRAM, cache, and frame buffer memories and all memory-mapped
* registers and cannot conflict with any external memory regions.
*/
#define FIDO_MEM_OFFSET 0x01000000
/**
* Onchip SRAM
*/
#define FIDO_SRAM_BASE_ADDR (0x00000000 + FIDO_MEM_OFFSET)
#define FIDO_SRAM_SIZE ((6 * 1024) * sizeof (unsigned long))
/**
* Onchip relocatable cache RAM
*/
#define FIDO_CACHE_BASE_ADDR (0x00080000 + FIDO_MEM_OFFSET)
#define FIDO_CACHE_BLOCK_SIZE (2 * 1024)
#define FIDO_CACHE_BLOCK_MAX 16
#define FIDO_CACHE_SIZE (FIDO_CACHE_BLOCK_SIZE * FIDO_CACHE_BLOCK_MAX)
#define FIDO_CACHE_BLOCK_ENABLE (1 << 0)
/**
* Memory-mapped registers
*/
#ifndef __ASSEMBLER__
typedef unsigned long volatile FIDO_Register_t;
#define FIDO_REGISTER_DEF (FIDO_Register_t*)
#else
#define FIDO_REGISTER_DEF
#endif /* __ASSEMBLER__ */
/* CPU DMA channel 0 and channel 1 registers */
#define FIDO_DMACH0_CONTROL FIDO_REGISTER_DEF(0xA0000 + FIDO_MEM_OFFSET)
#define FIDO_DMACH0_COUNT FIDO_REGISTER_DEF(0xA0004 + FIDO_MEM_OFFSET)
#define FIDO_DMACH0_DEST FIDO_REGISTER_DEF(0xA0008 + FIDO_MEM_OFFSET)
#define FIDO_DMACH0_SOURCE FIDO_REGISTER_DEF(0xA000C + FIDO_MEM_OFFSET)
#define FIDO_DMACH1_CONTROL FIDO_REGISTER_DEF(0xA0010 + FIDO_MEM_OFFSET)
#define FIDO_DMACH1_COUNT FIDO_REGISTER_DEF(0xA0014 + FIDO_MEM_OFFSET)
#define FIDO_DMACH1_DEST FIDO_REGISTER_DEF(0xA0018 + FIDO_MEM_OFFSET)
#define FIDO_DMACH1_SOURCE FIDO_REGISTER_DEF(0xA001C + FIDO_MEM_OFFSET)
#define FIDO_DMACH_MAX 2
/* Timer-Counter unit 0 registers */
#define FIDO_TCU00_STATUS FIDO_REGISTER_DEF(0xA0280 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_MODE FIDO_REGISTER_DEF(0xA0284 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_COUNTER FIDO_REGISTER_DEF(0xA0288 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH0_IOMODE FIDO_REGISTER_DEF(0xA0290 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH1_IOMODE FIDO_REGISTER_DEF(0xA0294 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH2_IOMODE FIDO_REGISTER_DEF(0xA0298 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH3_IOMODE FIDO_REGISTER_DEF(0xA029C + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH0_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02A0 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH1_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02A4 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH2_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02A8 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH3_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02AC + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH0_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02B0 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH1_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02B4 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH2_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02B8 + FIDO_MEM_OFFSET)
#define FIDO_TCU00_CH3_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02BC + FIDO_MEM_OFFSET)
/* Timer-Counter unit 1 registers */
#define FIDO_TCU01_STATUS FIDO_REGISTER_DEF(0xA02C0 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_MODE FIDO_REGISTER_DEF(0xA02C4 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_COUNTER FIDO_REGISTER_DEF(0xA02C8 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH0_IOMODE FIDO_REGISTER_DEF(0xA02D0 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH1_IOMODE FIDO_REGISTER_DEF(0xA02D4 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH2_IOMODE FIDO_REGISTER_DEF(0xA02D8 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH3_IOMODE FIDO_REGISTER_DEF(0xA02DC + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH0_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02E0 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH1_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02E4 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH2_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02E8 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH3_INPUTCAPTURE FIDO_REGISTER_DEF(0xA02EC + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH0_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02F0 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH1_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02F4 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH2_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02F8 + FIDO_MEM_OFFSET)
#define FIDO_TCU01_CH3_OUTPUTCOMPARE FIDO_REGISTER_DEF(0xA02FC + FIDO_MEM_OFFSET)
/* SystemTimer interrupt control registers, main ctrl reg, and prescale */
#define FIDO_SYSTIMER_INT00CONTROL FIDO_REGISTER_DEF(0xA0300 + FIDO_MEM_OFFSET)
#define FIDO_SYSTIMER_INT01CONTROL FIDO_REGISTER_DEF(0xA0304 + FIDO_MEM_OFFSET)
#define FIDO_SYSTIMER_INT02CONTROL FIDO_REGISTER_DEF(0xA0308 + FIDO_MEM_OFFSET)
#define FIDO_SYSTIMER_INT03CONTROL FIDO_REGISTER_DEF(0xA030C + FIDO_MEM_OFFSET)
#define FIDO_SYSTIMER_INT04CONTROL FIDO_REGISTER_DEF(0xA0310 + FIDO_MEM_OFFSET)
#define FIDO_SYSTIMER_CONTROL FIDO_REGISTER_DEF(0xA0314 + FIDO_MEM_OFFSET)
#define FIDO_SYSTIMER_PRESCALE FIDO_REGISTER_DEF(0xA0318 + FIDO_MEM_OFFSET)
/* Watchdog timer control and reload registers */
#define FIDO_WDTTIMER_CONTROL FIDO_REGISTER_DEF(0xA0340 + FIDO_MEM_OFFSET)
#define FIDO_WDTTIMER_RELOAD FIDO_REGISTER_DEF(0xA0344 + FIDO_MEM_OFFSET)
#define FIDO_WDTTIMER_CONTROL_RELOAD (1 << 0)
#define FIDO_WDTTIMER_CONTROL_ENABLE (1 << 1)
#define FIDO_WDTTIMER_CONTROL_INTENABLE (1 << 2)
/* Power on reset register */
#define FIDO_POR_REG FIDO_REGISTER_DEF(0xA0360 + FIDO_MEM_OFFSET)
/* Clock mask register, fixed at 0x00003F0F */
#define FIDO_CLOCK_MASK_REGISTER FIDO_REGISTER_DEF(0xA0380 + FIDO_MEM_OFFSET)
#define FIDO_CLOCK_MASK_TCU1 (unsigned long)(1 << 13)
#define FIDO_CLOCK_MASK_TCU0 (unsigned long)(1 << 12)
#define FIDO_CLOCK_MASK_SYSTIMER (unsigned long)(1 << 11)
#define FIDO_CLOCK_MASK_SDRAM (unsigned long)(1 << 10)
#define FIDO_CLOCK_MASK_ATOD (unsigned long)(1 << 9)
#define FIDO_CLOCK_MASK_PMU (unsigned long)(1 << 8)
#define FIDO_CLOCK_MASK_UIC3 (unsigned long)(1 << 3)
#define FIDO_CLOCK_MASK_UIC2 (unsigned long)(1 << 2)
#define FIDO_CLOCK_MASK_UIC1 (unsigned long)(1 << 1)
#define FIDO_CLOCK_MASK_UIC0 (unsigned long)(1 << 0)
/* Device ID register, fixed at 0x29811000 */
#define FIDO_DEVICE_ID_REGISTER FIDO_REGISTER_DEF(0xA0400 + FIDO_MEM_OFFSET)
/* Debug control registers for use by GDB and ROM monitor */
#define FIDO_DBG_CTRL FIDO_REGISTER_DEF(0xA0404 + FIDO_MEM_OFFSET)
#define FIDO_TRCBUF_CTRL FIDO_REGISTER_DEF(0xA0408 + FIDO_MEM_OFFSET)
#define FIDO_TRCBUF_BASE FIDO_REGISTER_DEF(0xA040C + FIDO_MEM_OFFSET)
#define FIDO_BRK00_BASE FIDO_REGISTER_DEF(0xA0410 + FIDO_MEM_OFFSET)
#define FIDO_BRK00_DATA FIDO_REGISTER_DEF(0xA0414 + FIDO_MEM_OFFSET)
#define FIDO_BRK00_DATAMASK FIDO_REGISTER_DEF(0xA0418 + FIDO_MEM_OFFSET)
#define FIDO_BRK00_CTRL FIDO_REGISTER_DEF(0xA041C + FIDO_MEM_OFFSET)
#define FIDO_BRK01_BASE FIDO_REGISTER_DEF(0xA0420 + FIDO_MEM_OFFSET)
#define FIDO_BRK01_DATA FIDO_REGISTER_DEF(0xA0424 + FIDO_MEM_OFFSET)
#define FIDO_BRK01_DATAMASK FIDO_REGISTER_DEF(0xA0428 + FIDO_MEM_OFFSET)
#define FIDO_BRK01_CTRL FIDO_REGISTER_DEF(0xA042C + FIDO_MEM_OFFSET)
#define FIDO_BRK02_BASE FIDO_REGISTER_DEF(0xA0430 + FIDO_MEM_OFFSET)
#define FIDO_BRK02_DATA FIDO_REGISTER_DEF(0xA0434 + FIDO_MEM_OFFSET)
#define FIDO_BRK02_DATAMASK FIDO_REGISTER_DEF(0xA0438 + FIDO_MEM_OFFSET)
#define FIDO_BRK02_CTRL FIDO_REGISTER_DEF(0xA043C + FIDO_MEM_OFFSET)
#define FIDO_BRK03_BASE FIDO_REGISTER_DEF(0xA0440 + FIDO_MEM_OFFSET)
#define FIDO_BRK03_DATA FIDO_REGISTER_DEF(0xA0444 + FIDO_MEM_OFFSET)
#define FIDO_BRK03_DATAMASK FIDO_REGISTER_DEF(0xA0448 + FIDO_MEM_OFFSET)
#define FIDO_BRK03_CTRL FIDO_REGISTER_DEF(0xA044C + FIDO_MEM_OFFSET)
#define FIDO_BRK04_BASE FIDO_REGISTER_DEF(0xA0450 + FIDO_MEM_OFFSET)
#define FIDO_BRK04_DATA FIDO_REGISTER_DEF(0xA0454 + FIDO_MEM_OFFSET)
#define FIDO_BRK04_DATAMASK FIDO_REGISTER_DEF(0xA0458 + FIDO_MEM_OFFSET)
#define FIDO_BRK04_CTRL FIDO_REGISTER_DEF(0xA045C + FIDO_MEM_OFFSET)
#define FIDO_BRK05_BASE FIDO_REGISTER_DEF(0xA0460 + FIDO_MEM_OFFSET)
#define FIDO_BRK05_DATA FIDO_REGISTER_DEF(0xA0464 + FIDO_MEM_OFFSET)
#define FIDO_BRK05_DATAMASK FIDO_REGISTER_DEF(0xA0468 + FIDO_MEM_OFFSET)
#define FIDO_BRK05_CTRL FIDO_REGISTER_DEF(0xA046C + FIDO_MEM_OFFSET)
#define FIDO_BRK06_BASE FIDO_REGISTER_DEF(0xA0470 + FIDO_MEM_OFFSET)
#define FIDO_BRK06_DATA FIDO_REGISTER_DEF(0xA0474 + FIDO_MEM_OFFSET)
#define FIDO_BRK06_DATAMASK FIDO_REGISTER_DEF(0xA0478 + FIDO_MEM_OFFSET)
#define FIDO_BRK06_CTRL FIDO_REGISTER_DEF(0xA047C + FIDO_MEM_OFFSET)
#define FIDO_BRK07_BASE FIDO_REGISTER_DEF(0xA0480 + FIDO_MEM_OFFSET)
#define FIDO_BRK07_DATA FIDO_REGISTER_DEF(0xA0484 + FIDO_MEM_OFFSET)
#define FIDO_BRK07_DATAMASK FIDO_REGISTER_DEF(0xA0488 + FIDO_MEM_OFFSET)
#define FIDO_BRK07_CTRL FIDO_REGISTER_DEF(0xA048C + FIDO_MEM_OFFSET)
/* A/D registers */
#define FIDO_A2D0_REG00 FIDO_REGISTER_DEF(0xA0600 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG01 FIDO_REGISTER_DEF(0xA0604 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG02 FIDO_REGISTER_DEF(0xA0608 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG03 FIDO_REGISTER_DEF(0xA060C + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG04 FIDO_REGISTER_DEF(0xA0610 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG05 FIDO_REGISTER_DEF(0xA0614 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG06 FIDO_REGISTER_DEF(0xA0618 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG07 FIDO_REGISTER_DEF(0xA061C + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG08 FIDO_REGISTER_DEF(0xA0620 + FIDO_MEM_OFFSET)
#define FIDO_A2D0_REG09 FIDO_REGISTER_DEF(0xA0624 + FIDO_MEM_OFFSET)
/* Chip select control&timing register pairs */
#define FIDO_BIU_CS0_CONTROL FIDO_REGISTER_DEF(0xA0680 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS0_TIMING FIDO_REGISTER_DEF(0xA0684 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS1_CONTROL FIDO_REGISTER_DEF(0xA0688 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS1_TIMING FIDO_REGISTER_DEF(0xA068C + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS2_CONTROL FIDO_REGISTER_DEF(0xA0690 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS2_TIMING FIDO_REGISTER_DEF(0xA0694 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS3_CONTROL FIDO_REGISTER_DEF(0xA0698 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS3_TIMING FIDO_REGISTER_DEF(0xA069C + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS4_CONTROL FIDO_REGISTER_DEF(0xA06A0 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS4_TIMING FIDO_REGISTER_DEF(0xA06A4 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS5_CONTROL FIDO_REGISTER_DEF(0xA06A8 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS5_TIMING FIDO_REGISTER_DEF(0xA06AC + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS6_CONTROL FIDO_REGISTER_DEF(0xA06B0 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS6_TIMING FIDO_REGISTER_DEF(0xA06B4 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS7_CONTROL FIDO_REGISTER_DEF(0xA06B8 + FIDO_MEM_OFFSET)
#define FIDO_BIU_CS7_TIMING FIDO_REGISTER_DEF(0xA06BC + FIDO_MEM_OFFSET)
#define FIDO_BIU_PRIORITY FIDO_REGISTER_DEF(0xA0700 + FIDO_MEM_OFFSET)
#define FIDO_BIU_DEF_TIMING FIDO_REGISTER_DEF(0xA0704 + FIDO_MEM_OFFSET)
/* SDRAM timing, control, and bank select registers */
#define FIDO_SDRAM_TIMING_0 FIDO_REGISTER_DEF(0xA0800 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_TIMING_1 FIDO_REGISTER_DEF(0xA0804 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_CONFIG_0 FIDO_REGISTER_DEF(0xA0808 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_CONFIG_1 FIDO_REGISTER_DEF(0xA080C + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_0 FIDO_REGISTER_DEF(0xA0810 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_1 FIDO_REGISTER_DEF(0xA0814 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_2 FIDO_REGISTER_DEF(0xA0818 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_3 FIDO_REGISTER_DEF(0xA081C + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_4 FIDO_REGISTER_DEF(0xA0820 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_5 FIDO_REGISTER_DEF(0xA0824 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_6 FIDO_REGISTER_DEF(0xA0828 + FIDO_MEM_OFFSET)
#define FIDO_SDRAM_EXT_BANK_7 FIDO_REGISTER_DEF(0xA082C + FIDO_MEM_OFFSET)
/* External interrupt control registers */
#define FIDO_INTCONTROLCH0 FIDO_REGISTER_DEF(0xA0900 + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH1 FIDO_REGISTER_DEF(0xA0904 + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH2 FIDO_REGISTER_DEF(0xA0908 + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH3 FIDO_REGISTER_DEF(0xA090C + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH4 FIDO_REGISTER_DEF(0xA0910 + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH5 FIDO_REGISTER_DEF(0xA0914 + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH6 FIDO_REGISTER_DEF(0xA0918 + FIDO_MEM_OFFSET)
#define FIDO_INTCONTROLCH7 FIDO_REGISTER_DEF(0xA091C + FIDO_MEM_OFFSET)
/* Software interrupt control registers */
#define FIDO_CTX0_INT_CTRL FIDO_REGISTER_DEF(0xA0980 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_INT_CTRL FIDO_REGISTER_DEF(0xA0984 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_INT_CTRL FIDO_REGISTER_DEF(0xA0988 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_INT_CTRL FIDO_REGISTER_DEF(0xA098C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_INT_CTRL FIDO_REGISTER_DEF(0xA0990 + FIDO_MEM_OFFSET)
#define FIDO_PMU_MAC_FILTER_MODE FIDO_REGISTER_DEF(0xA0A00 + FIDO_MEM_OFFSET)
#define FIDO_PMU_FILTER_DATA_HEAD FIDO_REGISTER_DEF(0xA0A04 + FIDO_MEM_OFFSET)
#define FIDO_PMU_FILTER_RDDATA_HEAD FIDO_REGISTER_DEF(0xA0A08 + FIDO_MEM_OFFSET)
/* PMU channel 0 (tied to UIC 0) registers */
#define FIDO_PMUCH0A_CONTROL FIDO_REGISTER_DEF(0xA0A40 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_STATUS FIDO_REGISTER_DEF(0xA0A44 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0A48 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0A4C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0A50 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_XMITFBUFEND FIDO_REGISTER_DEF(0xA0A54 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0A58 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0A5C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0A60 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_RCVFBUFEND FIDO_REGISTER_DEF(0xA0A64 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0A68 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0A6C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_XMITDATA FIDO_REGISTER_DEF(0xA0A70 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0A_RCVDATA FIDO_REGISTER_DEF(0xA0A74 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_CONTROL FIDO_REGISTER_DEF(0xA0A80 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_STATUS FIDO_REGISTER_DEF(0xA0A84 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0A88 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0A8C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0A90 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_XMITFBUFEND FIDO_REGISTER_DEF(0xA0A94 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0A98 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0A9C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0AA0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_RCVFBUFEND FIDO_REGISTER_DEF(0xA0AA4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0AA8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0AAC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_XMITDATA FIDO_REGISTER_DEF(0xA0AB0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH0B_RCVDATA FIDO_REGISTER_DEF(0xA0AB4 + FIDO_MEM_OFFSET)
/* PMU channel 1 (tied to UIC 1) registers */
#define FIDO_PMUCH1A_CONTROL FIDO_REGISTER_DEF(0xA0AC0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_STATUS FIDO_REGISTER_DEF(0xA0AC4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0AC8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0ACC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0AD0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_XMITFBUFEND FIDO_REGISTER_DEF(0xA0AD4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0AD8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0ADC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0AE0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_RCVFBUFEND FIDO_REGISTER_DEF(0xA0AE4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0AE8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0AEC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_XMITDATA FIDO_REGISTER_DEF(0xA0AF0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1A_RCVDATA FIDO_REGISTER_DEF(0xA0AF4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_CONTROL FIDO_REGISTER_DEF(0xA0B00 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_STATUS FIDO_REGISTER_DEF(0xA0B04 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0B08 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0B0C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0B10 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_XMITFBUFEND FIDO_REGISTER_DEF(0xA0B14 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0B18 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0B1C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0B20 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_RCVFBUFEND FIDO_REGISTER_DEF(0xA0B24 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0B28 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0B2C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_XMITDATA FIDO_REGISTER_DEF(0xA0B30 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH1B_RCVDATA FIDO_REGISTER_DEF(0xA0B34 + FIDO_MEM_OFFSET)
/* PMU channel 2 (tied to UIC 2) registers */
#define FIDO_PMUCH2A_CONTROL FIDO_REGISTER_DEF(0xA0B40 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_STATUS FIDO_REGISTER_DEF(0xA0B44 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0B48 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0B4C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0B50 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_XMITFBUFEND FIDO_REGISTER_DEF(0xA0B54 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0B58 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0B5C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0B60 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_RCVFBUFEND FIDO_REGISTER_DEF(0xA0B64 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0B68 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0B6C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_XMITDATA FIDO_REGISTER_DEF(0xA0B70 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2A_RCVDATA FIDO_REGISTER_DEF(0xA0B74 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_CONTROL FIDO_REGISTER_DEF(0xA0B80 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_STATUS FIDO_REGISTER_DEF(0xA0B84 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0B88 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0B8C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0B90 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_XMITFBUFEND FIDO_REGISTER_DEF(0xA0B94 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0B98 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0B9C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0BA0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_RCVFBUFEND FIDO_REGISTER_DEF(0xA0BA4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0BA8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0BAC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_XMITDATA FIDO_REGISTER_DEF(0xA0BB0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH2B_RCVDATA FIDO_REGISTER_DEF(0xA0BB4 + FIDO_MEM_OFFSET)
/* PMU channel 3 (tied to UIC 3) registers */
#define FIDO_PMUCH3A_CONTROL FIDO_REGISTER_DEF(0xA0BC0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_STATUS FIDO_REGISTER_DEF(0xA0BC4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0BC8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0BCC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0BD0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_XMITFBUFEND FIDO_REGISTER_DEF(0xA0BD4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0BD8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0BDC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0BE0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_RCVFBUFEND FIDO_REGISTER_DEF(0xA0BE4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0BE8 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0BEC + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_XMITDATA FIDO_REGISTER_DEF(0xA0BF0 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3A_RCVDATA FIDO_REGISTER_DEF(0xA0BF4 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_CONTROL FIDO_REGISTER_DEF(0xA0C00 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_STATUS FIDO_REGISTER_DEF(0xA0C04 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_PCKXMITSIZE FIDO_REGISTER_DEF(0xA0C08 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_PCKRCVSIZE FIDO_REGISTER_DEF(0xA0C0C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_XMITFBUFSTART FIDO_REGISTER_DEF(0xA0C10 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_XMITFBUFEND FIDO_REGISTER_DEF(0xA0C14 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_XMITFBUFRDPTR FIDO_REGISTER_DEF(0xA0C18 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_XMITFBUFWRPTR FIDO_REGISTER_DEF(0xA0C1C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_RCVFBUFSTART FIDO_REGISTER_DEF(0xA0C20 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_RCVFBUFEND FIDO_REGISTER_DEF(0xA0C24 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_RCVFBUFRDPTR FIDO_REGISTER_DEF(0xA0C28 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_RCVFBUFWRPTR FIDO_REGISTER_DEF(0xA0C2C + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_XMITDATA FIDO_REGISTER_DEF(0xA0C30 + FIDO_MEM_OFFSET)
#define FIDO_PMUCH3B_RCVDATA FIDO_REGISTER_DEF(0xA0C34 + FIDO_MEM_OFFSET)
/* 4 PMU/UICs with 2 UIC channels (A and B) each */
#define FIDO_PMUCH_MAX 4
#define FIDO_UIC_MAX FIDO_PMUCH_MAX
#define FIDO_UICCH_MAX 2
/* FIDO_PMUCHXX_Control register definitions */
#define FIDO_PMU_RCV_PACKET_SIZE_EN ( 1 << 18)
#define FIDO_PMU_UIC_INT_EN ( 1 << 17)
#define FIDO_PMU_PMU_INT_EN ( 1 << 16)
#define FIDO_PMU_PRI_SHIFT 13
#define FIDO_PMU_PRI_MASK ( 7 << FIDO_PMU_PRI_SHIFT)
#define FIDO_PMU_CONTEXT_SHIFT 8
#define FIDO_PMU_CONTEXT_MASK ( 7 << FIDO_PMU_CONTEXT_SHIFT)
#define FIDO_PMU_CHANNEL_EN ( 1 << 7)
#define FIDO_PMU_XMIT_START ( 1 << 6)
#define FIDO_PMU_XMIT_IRQ_EN ( 1 << 4)
#define FIDO_PMU_RCV_IRQ_EN ( 1 << 3)
#define FIDO_PMU_ERROR_IRQ_EN ( 1 << 2)
#define FIDO_PMU_MODE_FIFO ( 0 << 0)
#define FIDO_PMU_MODE_RANDOM ( 1 << 0)
#define FIDO_PMU_MODE_MASK ( 3 << 0)
/* FIDO_PMUCHXX_Status register definitions */
#define FIDO_PMU_RCV_FIFO_FULL ( 1 << 11)
#define FIDO_PMU_RCV_FIFO_EMPTY ( 1 << 10)
#define FIDO_PMU_XMIT_FIFO_FULL ( 1 << 9)
#define FIDO_PMU_XMIT_FIFO_EMPTY ( 1 << 8)
#define FIDO_PMU_INTERRUPT ( 1 << 7)
#define FIDO_PMU_RCV_BUFF_OVERFLOW ( 1 << 3)
#define FIDO_PMU_UIC_ERROR ( 1 << 2)
#define FIDO_PMU_RCV_COMPLETE ( 1 << 1)
#define FIDO_PMU_XMIT_COMPLETE ( 1 << 0)
/* PMU interrupt vector definitions */
#define FIDO_PMU0_INT_VECTOR 77
#define FIDO_PMU1_INT_VECTOR 78
#define FIDO_PMU2_INT_VECTOR 79
#define FIDO_PMU3_INT_VECTOR 80
/* Context claim and software interrupt registers */
#define FIDO_SWINTACT0 FIDO_REGISTER_DEF(0xA110C + FIDO_MEM_OFFSET)
#define FIDO_CTX1_CLAIM FIDO_REGISTER_DEF(0xA1110 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_PENDING FIDO_REGISTER_DEF(0xA1114 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_PRI_INHER FIDO_REGISTER_DEF(0xA1118 + FIDO_MEM_OFFSET)
#define FIDO_SWINTACT1 FIDO_REGISTER_DEF(0xA111C + FIDO_MEM_OFFSET)
#define FIDO_CTX2_CLAIM FIDO_REGISTER_DEF(0xA1120 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_PENDING FIDO_REGISTER_DEF(0xA1124 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_PRI_INHER FIDO_REGISTER_DEF(0xA1128 + FIDO_MEM_OFFSET)
#define FIDO_SWINTACT2 FIDO_REGISTER_DEF(0xA112C + FIDO_MEM_OFFSET)
#define FIDO_CTX3_CLAIM FIDO_REGISTER_DEF(0xA1130 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_PENDING FIDO_REGISTER_DEF(0xA1134 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_PRI_INHER FIDO_REGISTER_DEF(0xA1138 + FIDO_MEM_OFFSET)
#define FIDO_SWINTACT3 FIDO_REGISTER_DEF(0xA113C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_CLAIM FIDO_REGISTER_DEF(0xA1140 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_PENDING FIDO_REGISTER_DEF(0xA1144 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_PRI_INHER FIDO_REGISTER_DEF(0xA1148 + FIDO_MEM_OFFSET)
#define FIDO_SWINTACT4 FIDO_REGISTER_DEF(0xA114C + FIDO_MEM_OFFSET)
/* Context0 data registers and address registers */
#define FIDO_CTX0_D0 FIDO_REGISTER_DEF(0xA8100 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D1 FIDO_REGISTER_DEF(0xA8104 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D2 FIDO_REGISTER_DEF(0xA8108 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D3 FIDO_REGISTER_DEF(0xA810C + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D4 FIDO_REGISTER_DEF(0xA8110 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D5 FIDO_REGISTER_DEF(0xA8114 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D6 FIDO_REGISTER_DEF(0xA8118 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_D7 FIDO_REGISTER_DEF(0xA811C + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A0 FIDO_REGISTER_DEF(0xA8120 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A1 FIDO_REGISTER_DEF(0xA8124 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A2 FIDO_REGISTER_DEF(0xA8128 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A3 FIDO_REGISTER_DEF(0xA812C + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A4 FIDO_REGISTER_DEF(0xA8130 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A5 FIDO_REGISTER_DEF(0xA8134 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A6 FIDO_REGISTER_DEF(0xA8138 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A7 FIDO_REGISTER_DEF(0xA813C + FIDO_MEM_OFFSET)
#define FIDO_CTX0_A7S FIDO_REGISTER_DEF(0xA8140 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_PC FIDO_REGISTER_DEF(0xA8144 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_SR FIDO_REGISTER_DEF(0xA8148 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_VBR FIDO_REGISTER_DEF(0xA814C + FIDO_MEM_OFFSET)
#define FIDO_CTX0_SFC FIDO_REGISTER_DEF(0xA8150 + FIDO_MEM_OFFSET)
#define FIDO_CTX0_DFC FIDO_REGISTER_DEF(0xA8154 + FIDO_MEM_OFFSET)
/* Context1 data registers and address registers */
#define FIDO_CTX1_D0 FIDO_REGISTER_DEF(0xA8180 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D1 FIDO_REGISTER_DEF(0xA8184 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D2 FIDO_REGISTER_DEF(0xA8188 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D3 FIDO_REGISTER_DEF(0xA818C + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D4 FIDO_REGISTER_DEF(0xA8190 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D5 FIDO_REGISTER_DEF(0xA8194 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D6 FIDO_REGISTER_DEF(0xA8198 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_D7 FIDO_REGISTER_DEF(0xA819C + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A0 FIDO_REGISTER_DEF(0xA81A0 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A1 FIDO_REGISTER_DEF(0xA81A4 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A2 FIDO_REGISTER_DEF(0xA81A8 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A3 FIDO_REGISTER_DEF(0xA81AC + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A4 FIDO_REGISTER_DEF(0xA81B0 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A5 FIDO_REGISTER_DEF(0xA81B4 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A6 FIDO_REGISTER_DEF(0xA81B8 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A7 FIDO_REGISTER_DEF(0xA81BC + FIDO_MEM_OFFSET)
#define FIDO_CTX1_A7S FIDO_REGISTER_DEF(0xA81C0 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_PC FIDO_REGISTER_DEF(0xA81C4 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_SR FIDO_REGISTER_DEF(0xA81C8 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_VBR FIDO_REGISTER_DEF(0xA81CC + FIDO_MEM_OFFSET)
#define FIDO_CTX1_SFC FIDO_REGISTER_DEF(0xA81D0 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_DFC FIDO_REGISTER_DEF(0xA81D4 + FIDO_MEM_OFFSET)
/* Context2 data registers and address registers */
#define FIDO_CTX2_D0 FIDO_REGISTER_DEF(0xA8200 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D1 FIDO_REGISTER_DEF(0xA8204 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D2 FIDO_REGISTER_DEF(0xA8208 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D3 FIDO_REGISTER_DEF(0xA820C + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D4 FIDO_REGISTER_DEF(0xA8210 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D5 FIDO_REGISTER_DEF(0xA8214 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D6 FIDO_REGISTER_DEF(0xA8218 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_D7 FIDO_REGISTER_DEF(0xA812C + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A0 FIDO_REGISTER_DEF(0xA8220 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A1 FIDO_REGISTER_DEF(0xA8224 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A2 FIDO_REGISTER_DEF(0xA8228 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A3 FIDO_REGISTER_DEF(0xA822C + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A4 FIDO_REGISTER_DEF(0xA8230 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A5 FIDO_REGISTER_DEF(0xA8234 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A6 FIDO_REGISTER_DEF(0xA8238 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A7 FIDO_REGISTER_DEF(0xA823C + FIDO_MEM_OFFSET)
#define FIDO_CTX2_A7S FIDO_REGISTER_DEF(0xA8240 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_PC FIDO_REGISTER_DEF(0xA8244 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_SR FIDO_REGISTER_DEF(0xA8248 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_VBR FIDO_REGISTER_DEF(0xA824C + FIDO_MEM_OFFSET)
#define FIDO_CTX2_SFC FIDO_REGISTER_DEF(0xA8250 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_DFC FIDO_REGISTER_DEF(0xA8254 + FIDO_MEM_OFFSET)
/* Context3 data registers and address registers */
#define FIDO_CTX3_D0 FIDO_REGISTER_DEF(0xA8280 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D1 FIDO_REGISTER_DEF(0xA8284 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D2 FIDO_REGISTER_DEF(0xA8288 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D3 FIDO_REGISTER_DEF(0xA828C + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D4 FIDO_REGISTER_DEF(0xA8290 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D5 FIDO_REGISTER_DEF(0xA8294 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D6 FIDO_REGISTER_DEF(0xA8298 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_D7 FIDO_REGISTER_DEF(0xA829C + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A0 FIDO_REGISTER_DEF(0xA82A0 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A1 FIDO_REGISTER_DEF(0xA82A4 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A2 FIDO_REGISTER_DEF(0xA82A8 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A3 FIDO_REGISTER_DEF(0xA82AC + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A4 FIDO_REGISTER_DEF(0xA82B0 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A5 FIDO_REGISTER_DEF(0xA82B4 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A6 FIDO_REGISTER_DEF(0xA82B8 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A7 FIDO_REGISTER_DEF(0xA82BC + FIDO_MEM_OFFSET)
#define FIDO_CTX3_A7S FIDO_REGISTER_DEF(0xA82C0 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_PC FIDO_REGISTER_DEF(0xA82C4 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_SR FIDO_REGISTER_DEF(0xA82C8 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_VBR FIDO_REGISTER_DEF(0xA82CC + FIDO_MEM_OFFSET)
#define FIDO_CTX3_SFC FIDO_REGISTER_DEF(0xA82D0 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_DFC FIDO_REGISTER_DEF(0xA82D4 + FIDO_MEM_OFFSET)
/* Context4 data registers and address registers */
#define FIDO_CTX4_D0 FIDO_REGISTER_DEF(0xA8300 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D1 FIDO_REGISTER_DEF(0xA8304 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D2 FIDO_REGISTER_DEF(0xA8308 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D3 FIDO_REGISTER_DEF(0xA830C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D4 FIDO_REGISTER_DEF(0xA8310 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D5 FIDO_REGISTER_DEF(0xA8314 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D6 FIDO_REGISTER_DEF(0xA8318 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_D7 FIDO_REGISTER_DEF(0xA831C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A0 FIDO_REGISTER_DEF(0xA8320 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A1 FIDO_REGISTER_DEF(0xA8324 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A2 FIDO_REGISTER_DEF(0xA8328 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A3 FIDO_REGISTER_DEF(0xA832C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A4 FIDO_REGISTER_DEF(0xA8330 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A5 FIDO_REGISTER_DEF(0xA8334 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A6 FIDO_REGISTER_DEF(0xA8338 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A7 FIDO_REGISTER_DEF(0xA833C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_A7S FIDO_REGISTER_DEF(0xA8340 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_PC FIDO_REGISTER_DEF(0xA8344 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_SR FIDO_REGISTER_DEF(0xA8348 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_VBR FIDO_REGISTER_DEF(0xA834C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_SFC FIDO_REGISTER_DEF(0xA8350 + FIDO_MEM_OFFSET)
#define FIDO_CTX4_DFC FIDO_REGISTER_DEF(0xA8354 + FIDO_MEM_OFFSET)
#define FIDO_CTX_MAX 5
/* MPU Block control register */
#define FIDO_MPU_BLK00CTRL FIDO_REGISTER_DEF(0xAA000 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK01CTRL FIDO_REGISTER_DEF(0xAA004 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK02CTRL FIDO_REGISTER_DEF(0xAA008 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK03CTRL FIDO_REGISTER_DEF(0xAA00C + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK04CTRL FIDO_REGISTER_DEF(0xAA010 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK05CTRL FIDO_REGISTER_DEF(0xAA014 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK06CTRL FIDO_REGISTER_DEF(0xAA018 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK07CTRL FIDO_REGISTER_DEF(0xAA01C + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK08CTRL FIDO_REGISTER_DEF(0xAA020 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK09CTRL FIDO_REGISTER_DEF(0xAA024 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK10CTRL FIDO_REGISTER_DEF(0xAA028 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK11CTRL FIDO_REGISTER_DEF(0xAA02C + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK12CTRL FIDO_REGISTER_DEF(0xAA030 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK13CTRL FIDO_REGISTER_DEF(0xAA034 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK14CTRL FIDO_REGISTER_DEF(0xAA038 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK15CTRL FIDO_REGISTER_DEF(0xAA03C + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLOCK_MAX 16
#define FIDO_MPU_BLOCK_BASE_ALIGN 64
/* MPU Block attribute register */
#define FIDO_MPU_BLK00ATTRIB FIDO_REGISTER_DEF(0xAA080 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK01ATTRIB FIDO_REGISTER_DEF(0xAA084 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK02ATTRIB FIDO_REGISTER_DEF(0xAA088 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK03ATTRIB FIDO_REGISTER_DEF(0xAA08C + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK04ATTRIB FIDO_REGISTER_DEF(0xAA090 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK05ATTRIB FIDO_REGISTER_DEF(0xAA094 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK06ATTRIB FIDO_REGISTER_DEF(0xAA098 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK07ATTRIB FIDO_REGISTER_DEF(0xAA09C + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK08ATTRIB FIDO_REGISTER_DEF(0xAA0A0 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK09ATTRIB FIDO_REGISTER_DEF(0xAA0A4 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK10ATTRIB FIDO_REGISTER_DEF(0xAA0A8 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK11ATTRIB FIDO_REGISTER_DEF(0xAA0AC + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK12ATTRIB FIDO_REGISTER_DEF(0xAA0B0 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK13ATTRIB FIDO_REGISTER_DEF(0xAA0B4 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK14ATTRIB FIDO_REGISTER_DEF(0xAA0B8 + FIDO_MEM_OFFSET)
#define FIDO_MPU_BLK15ATTRIB FIDO_REGISTER_DEF(0xAA0BC + FIDO_MEM_OFFSET)
#define FIDO_MPU_ATTRIB_SIZE_SHIFT 2
#define FIDO_MPU_ATTRIB_ENABLE (1 << 0)
#define FIDO_MPU_ATTRIB_READONLY (1 << 1)
/* MPU allocation registers */
#define FIDO_CTX0_MPUALLOCATION FIDO_REGISTER_DEF(0xAA100 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_MPUALLOCATION FIDO_REGISTER_DEF(0xAA104 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_MPUALLOCATION FIDO_REGISTER_DEF(0xAA108 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_MPUALLOCATION FIDO_REGISTER_DEF(0xAA10C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_MPUALLOCATION FIDO_REGISTER_DEF(0xAA110 + FIDO_MEM_OFFSET)
/* DCACHE relocatable registers */
#define FIDO_DCACHE_RELOCATBLK00 FIDO_REGISTER_DEF(0xAA180 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK01 FIDO_REGISTER_DEF(0xAA184 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK02 FIDO_REGISTER_DEF(0xAA188 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK03 FIDO_REGISTER_DEF(0xAA18C + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK04 FIDO_REGISTER_DEF(0xAA190 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK05 FIDO_REGISTER_DEF(0xAA194 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK06 FIDO_REGISTER_DEF(0xAA198 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK07 FIDO_REGISTER_DEF(0xAA19C + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK08 FIDO_REGISTER_DEF(0xAA1A0 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK09 FIDO_REGISTER_DEF(0xAA1A4 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK10 FIDO_REGISTER_DEF(0xAA1A8 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK11 FIDO_REGISTER_DEF(0xAA1AC + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK12 FIDO_REGISTER_DEF(0xAA1B0 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK13 FIDO_REGISTER_DEF(0xAA1B4 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK14 FIDO_REGISTER_DEF(0xAA1B8 + FIDO_MEM_OFFSET)
#define FIDO_DCACHE_RELOCATBLK15 FIDO_REGISTER_DEF(0xAA1BC + FIDO_MEM_OFFSET)
/* Context control registers */
#define FIDO_CTX0_CONTROL FIDO_REGISTER_DEF(0xAA400 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_CONTROL FIDO_REGISTER_DEF(0xAA404 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_CONTROL FIDO_REGISTER_DEF(0xAA408 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_CONTROL FIDO_REGISTER_DEF(0xAA40C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_CONTROL FIDO_REGISTER_DEF(0xAA410 + FIDO_MEM_OFFSET)
#define FIDO_CTX_CONTROL_STATE_MASK ( 3 << 0)
#define FIDO_CTX_CONTROL_STATE_HALTED ( 0 << 0)
#define FIDO_CTX_CONTROL_STATE_NOTREADY ( 1 << 0)
#define FIDO_CTX_CONTROL_STATE_READY ( 2 << 0)
#define FIDO_CTX_CONTROL_PRIORITY_MASK 7
#define FIDO_CTX_CONTROL_PRIORITY_SHIFT 8
#define FIDO_CTX_CONTROL_MODE_MASK ( 3 << 13)
#define FIDO_CTX_CONTROL_MODE_STANDARD ( 0 << 13)
#define FIDO_CTX_CONTROL_MODE_FAST ( 1 << 13)
#define FIDO_CTX_CONTROL_MODE_FAST_ST ( 3 << 13)
#define FIDO_CTX0_MAXTIME FIDO_REGISTER_DEF(0xAA480 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_MAXTIME FIDO_REGISTER_DEF(0xAA484 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_MAXTIME FIDO_REGISTER_DEF(0xAA488 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_MAXTIME FIDO_REGISTER_DEF(0xAA48C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_MAXTIME FIDO_REGISTER_DEF(0xAA490 + FIDO_MEM_OFFSET)
/* Context timer registers */
#define FIDO_CTX0_TIME FIDO_REGISTER_DEF(0xAA500 + FIDO_MEM_OFFSET)
#define FIDO_CTX1_TIME FIDO_REGISTER_DEF(0xAA504 + FIDO_MEM_OFFSET)
#define FIDO_CTX2_TIME FIDO_REGISTER_DEF(0xAA508 + FIDO_MEM_OFFSET)
#define FIDO_CTX3_TIME FIDO_REGISTER_DEF(0xAA50C + FIDO_MEM_OFFSET)
#define FIDO_CTX4_TIME FIDO_REGISTER_DEF(0xAA510 + FIDO_MEM_OFFSET)
#define FIDO_CTXN_TIMECLR FIDO_REGISTER_DEF(0xAA580 + FIDO_MEM_OFFSET)
#define FIDO_CTX_IDLETIME FIDO_REGISTER_DEF(0xAA584 + FIDO_MEM_OFFSET)
#define FIDO_CTXN_TIMEEN FIDO_REGISTER_DEF(0xAA588 + FIDO_MEM_OFFSET)
#define FIDO_CTX_FAULTID FIDO_REGISTER_DEF(0xAA600 + FIDO_MEM_OFFSET)
/* Current context register, contains id of currently executing context */
#define FIDO_CURRENT_CONTEXT_REGISTER FIDO_REGISTER_DEF(0xAA604 + FIDO_MEM_OFFSET)
/* UIC Frame Buffer transmit and receive memory */
#define FIDO_FB_XMIT_BASE_ADDR (0xB0000 + FIDO_MEM_OFFSET)
#define FIDO_FB_XMIT_SIZE ((1 * 1024) * sizeof (unsigned long))
#define FIDO_FB_RCV_BASE_ADDR (0xB4000 + FIDO_MEM_OFFSET)
#define FIDO_FB_RCV_SIZE ((2 * 1024) * sizeof (unsigned long))
/* UIC register file base addresses */
#define FIDO_UIC0_BASE (0x00B8000 + FIDO_MEM_OFFSET)
#define FIDO_UIC1_BASE (0x00B8200 + FIDO_MEM_OFFSET)
#define FIDO_UIC2_BASE (0x00B8400 + FIDO_MEM_OFFSET)
#define FIDO_UIC3_BASE (0x00B8600 + FIDO_MEM_OFFSET)
#endif /* FIDOmemmap_h */
///@}
| 64.392908 | 83 | 0.749983 | [
"vector"
] |
3288311369b8fc7e763a98f8328d6feb75c81b15 | 1,163 | h | C | src/decoder-phrasebased/src/native/interpolated-lm/lm/LM.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | src/decoder-phrasebased/src/native/interpolated-lm/lm/LM.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | src/decoder-phrasebased/src/native/interpolated-lm/lm/LM.h | ugermann/MMT | 715ad16b4467f44c8103e16165261d1391a69fb8 | [
"Apache-2.0"
] | null | null | null | //
// Created by Davide Caroselli on 27/07/16.
//
#ifndef ILM_LM_H
#define ILM_LM_H
#include <cstdint>
#include <vector>
#include <map>
#include <mmt/sentence.h>
using namespace std;
namespace mmt {
namespace ilm {
struct HistoryKey {
virtual size_t hash() const = 0;
virtual bool operator==(const HistoryKey &other) const = 0;
virtual size_t length() const = 0;
virtual ~HistoryKey() {};
};
const wid_t kVocabularyStartSymbol = 1;
const wid_t kVocabularyEndSymbol = 2;
class LM {
public:
// Returned value must be le natural log of the ngram probability
virtual float ComputeProbability(const wid_t word, const HistoryKey *historyKey, const context_t *context,
HistoryKey **outHistoryKey) const = 0;
virtual HistoryKey *MakeHistoryKey(const vector <wid_t> &phrase) const = 0;
virtual HistoryKey *MakeEmptyHistoryKey() const = 0;
virtual bool IsOOV(const context_t *context, const wid_t word) const = 0;
};
}
}
#endif //ILM_LM_H
| 23.26 | 118 | 0.603611 | [
"vector"
] |
328a4bb13f0764c01d00879227b27c0ebbb4b36c | 24,533 | c | C | src/glibc-2.23/.pc/hurd-i386/tg-thread-cancel.diff/sysdeps/mach/hurd/spawni.c | wwkenwong/piecewise | 2cecb3f67fd2e1cd5b67102d49f9e16cf9a2e52f | [
"BSD-3-Clause-Clear"
] | 12 | 2018-09-18T19:51:27.000Z | 2022-01-18T15:31:41.000Z | src/glibc-2.23/.pc/hurd-i386/tg-thread-cancel.diff/sysdeps/mach/hurd/spawni.c | wwkenwong/piecewise | 2cecb3f67fd2e1cd5b67102d49f9e16cf9a2e52f | [
"BSD-3-Clause-Clear"
] | null | null | null | src/glibc-2.23/.pc/hurd-i386/tg-thread-cancel.diff/sysdeps/mach/hurd/spawni.c | wwkenwong/piecewise | 2cecb3f67fd2e1cd5b67102d49f9e16cf9a2e52f | [
"BSD-3-Clause-Clear"
] | 3 | 2019-06-12T19:38:54.000Z | 2020-03-05T19:17:23.000Z | /* spawn a new process running an executable. Hurd version.
Copyright (C) 2001-2016 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; see the file COPYING.LIB. If
not, see <http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <spawn.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <hurd.h>
#include <hurd/signal.h>
#include <hurd/fd.h>
#include <hurd/id.h>
#include <hurd/lookup.h>
#include <hurd/resource.h>
#include <assert.h>
#include <argz.h>
#include "spawn_int.h"
/* Spawn a new process executing PATH with the attributes describes in *ATTRP.
Before running the process perform the actions described in FILE-ACTIONS. */
int
__spawni (pid_t *pid, const char *file,
const posix_spawn_file_actions_t *file_actions,
const posix_spawnattr_t *attrp,
char *const argv[], char *const envp[],
int xflags)
{
pid_t new_pid;
char *path, *p, *name;
size_t len;
size_t pathlen;
short int flags;
/* The generic POSIX.1 implementation of posix_spawn uses fork and exec.
In traditional POSIX systems (Unix, Linux, etc), the only way to
create a new process is by fork, which also copies all the things from
the parent process that will be immediately wiped and replaced by the
exec.
This Hurd implementation works by doing an exec on a fresh task,
without ever doing all the work of fork. The only work done by fork
that remains visible after an exec is registration with the proc
server, and the inheritance of various values and ports. All those
inherited values and ports are what get collected up and passed in the
file_exec RPC by an exec call. So we do the proc server registration
here, following the model of fork (see fork.c). We then collect up
the inherited values and ports from this (parent) process following
the model of exec (see hurd/hurdexec.c), modify or replace each value
that fork would (plus the specific changes demanded by ATTRP and
FILE_ACTIONS), and make the file_exec RPC on the requested executable
file with the child process's task port rather than our own. This
should be indistinguishable from the fork + exec implementation,
except that all errors will be detected here (in the parent process)
and return proper errno codes rather than the child dying with 127.
XXX The one exception to this supposed indistinguishableness is that
when posix_spawn_file_actions_addopen has been used, the parent
process can do various filesystem RPCs on the child's behalf, rather
than the child process doing it. If these block due to a broken or
malicious filesystem server or just a blocked network fs or a serial
port waiting for carrier detect (!!), the parent's posix_spawn call
can block arbitrarily rather than just the child blocking. Possible
solutions include:
* punt to plain fork + exec implementation if addopen was used
** easy to do
** gives up all benefits of this implementation in that case
* if addopen was used, don't do any file actions at all here;
instead, exec an installed helper program e.g.:
/libexec/spawn-helper close 3 dup2 1 2 open 0 /file 0x123 0666 exec /bin/foo foo a1 a2
** extra exec might be more or less overhead than fork
* could do some weird half-fork thing where the child would inherit
our vm and run some code here, but not do the full work of fork
XXX Actually, the parent opens the executable file on behalf of
the child, and that has all the same issues.
I am favoring the half-fork solution. That is, we do task_create with
vm inheritance, and we setjmp/longjmp the child like fork does. But
rather than all the fork hair, the parent just packs up init/dtable
ports and does a single IPC to a receive right inserted in the child. */
error_t err;
task_t task;
file_t execfile;
process_t proc;
auth_t auth;
int ints[INIT_INT_MAX];
file_t *dtable;
unsigned int dtablesize, orig_dtablesize, i;
struct hurd_port **dtable_cells;
char *dtable_cloexec;
struct hurd_userlink *ulink_dtable = NULL;
struct hurd_sigstate *ss;
/* For POSIX_SPAWN_RESETIDS, this reauthenticates our root/current
directory ports with the new AUTH port. */
file_t rcrdir = MACH_PORT_NULL, rcwdir = MACH_PORT_NULL;
error_t reauthenticate (int which, file_t *result)
{
error_t err;
mach_port_t ref;
if (*result != MACH_PORT_NULL)
return 0;
ref = __mach_reply_port ();
err = HURD_PORT_USE
(&_hurd_ports[which],
({
err = __io_reauthenticate (port, ref, MACH_MSG_TYPE_MAKE_SEND);
if (!err)
err = __auth_user_authenticate (auth,
ref, MACH_MSG_TYPE_MAKE_SEND,
result);
err;
}));
__mach_port_destroy (__mach_task_self (), ref);
return err;
}
/* Reauthenticate one of our file descriptors for the child. A null
element of DTABLE_CELLS indicates a descriptor that was already
reauthenticated, or was newly opened on behalf of the child. */
error_t reauthenticate_fd (int fd)
{
if (dtable_cells[fd] != NULL)
{
file_t newfile;
mach_port_t ref = __mach_reply_port ();
error_t err = __io_reauthenticate (dtable[fd],
ref, MACH_MSG_TYPE_MAKE_SEND);
if (!err)
err = __auth_user_authenticate (auth,
ref, MACH_MSG_TYPE_MAKE_SEND,
&newfile);
__mach_port_destroy (__mach_task_self (), ref);
if (err)
return err;
_hurd_port_free (dtable_cells[fd], &ulink_dtable[fd], dtable[fd]);
dtable_cells[fd] = NULL;
dtable[fd] = newfile;
}
return 0;
}
/* These callbacks are for looking up file names on behalf of the child. */
error_t child_init_port (int which, error_t (*operate) (mach_port_t))
{
if (flags & POSIX_SPAWN_RESETIDS)
switch (which)
{
case INIT_PORT_AUTH:
return (*operate) (auth);
case INIT_PORT_CRDIR:
return (reauthenticate (INIT_PORT_CRDIR, &rcrdir)
?: (*operate) (rcrdir));
case INIT_PORT_CWDIR:
return (reauthenticate (INIT_PORT_CWDIR, &rcwdir)
?: (*operate) (rcwdir));
}
assert (which != INIT_PORT_PROC);
return _hurd_ports_use (which, operate);
}
file_t child_fd (int fd)
{
if ((unsigned int) fd < dtablesize && dtable[fd] != MACH_PORT_NULL)
{
if (flags & POSIX_SPAWN_RESETIDS)
{
/* Reauthenticate this descriptor right now,
since it is going to be used on behalf of the child. */
errno = reauthenticate_fd (fd);
if (errno)
return MACH_PORT_NULL;
}
__mach_port_mod_refs (__mach_task_self (), dtable[fd],
MACH_PORT_RIGHT_SEND, +1);
return dtable[fd];
}
errno = EBADF;
return MACH_PORT_NULL;
}
inline error_t child_lookup (const char *file, int oflag, mode_t mode,
file_t *result)
{
return __hurd_file_name_lookup (&child_init_port, &child_fd, 0,
file, oflag, mode, result);
}
/* Do this once. */
flags = attrp == NULL ? 0 : attrp->__flags;
/* Generate the new process. We create a task that does not inherit our
memory, and then register it as our child like fork does. See fork.c
for comments about the sequencing of these proc operations. */
err = __task_create (__mach_task_self (),
#ifdef KERN_INVALID_LEDGER
NULL, 0, /* OSF Mach */
#endif
0, &task);
if (err)
return __hurd_fail (err);
// From here down we must deallocate TASK and PROC before returning.
proc = MACH_PORT_NULL;
auth = MACH_PORT_NULL;
err = __USEPORT (PROC, __proc_task2pid (port, task, &new_pid));
if (!err)
err = __USEPORT (PROC, __proc_task2proc (port, task, &proc));
if (!err)
err = __USEPORT (PROC, __proc_child (port, task));
if (err)
goto out;
/* Load up the ints to give the new program. */
memset (ints, 0, sizeof ints);
ints[INIT_UMASK] = _hurd_umask;
ints[INIT_TRACEMASK] = _hurdsig_traced;
ss = _hurd_self_sigstate ();
assert (! __spin_lock_locked (&ss->critical_section_lock));
__spin_lock (&ss->critical_section_lock);
__spin_lock (&ss->lock);
ints[INIT_SIGMASK] = ss->blocked;
ints[INIT_SIGPENDING] = ss->pending;
ints[INIT_SIGIGN] = 0;
/* Unless we were asked to reset all handlers to SIG_DFL,
pass down the set of signals that were set to SIG_IGN. */
if ((flags & POSIX_SPAWN_SETSIGDEF) == 0)
for (i = 1; i < NSIG; ++i)
if (ss->actions[i].sa_handler == SIG_IGN)
ints[INIT_SIGIGN] |= __sigmask (i);
/* We hold the sigstate lock until the exec has failed so that no signal
can arrive between when we pack the blocked and ignored signals, and
when the exec actually happens. A signal handler could change what
signals are blocked and ignored. Either the change will be reflected
in the exec, or the signal will never be delivered. Setting the
critical section flag avoids anything we call trying to acquire the
sigstate lock. */
__spin_unlock (&ss->lock);
/* Set signal mask. */
if ((flags & POSIX_SPAWN_SETSIGMASK) != 0)
ints[INIT_SIGMASK] = attrp->__ss;
#ifdef _POSIX_PRIORITY_SCHEDULING
/* Set the scheduling algorithm and parameters. */
# error implement me
if ((flags & (POSIX_SPAWN_SETSCHEDPARAM | POSIX_SPAWN_SETSCHEDULER))
== POSIX_SPAWN_SETSCHEDPARAM)
{
if (__sched_setparam (0, &attrp->__sp) == -1)
_exit (SPAWN_ERROR);
}
else if ((flags & POSIX_SPAWN_SETSCHEDULER) != 0)
{
if (__sched_setscheduler (0, attrp->__policy,
(flags & POSIX_SPAWN_SETSCHEDPARAM) != 0
? &attrp->__sp : NULL) == -1)
_exit (SPAWN_ERROR);
}
#endif
/* Set the process group ID. */
if (!err && (flags & POSIX_SPAWN_SETPGROUP) != 0)
err = __proc_setpgrp (proc, new_pid, attrp->__pgrp);
/* Set the effective user and group IDs. */
if (!err && (flags & POSIX_SPAWN_RESETIDS) != 0)
{
/* We need a different auth port for the child. */
__mutex_lock (&_hurd_id.lock);
err = _hurd_check_ids (); /* Get _hurd_id up to date. */
if (!err && _hurd_id.rid_auth == MACH_PORT_NULL)
{
/* Set up _hurd_id.rid_auth. This is a special auth server port
which uses the real uid and gid (the first aux uid and gid) as
the only effective uid and gid. */
if (_hurd_id.aux.nuids < 1 || _hurd_id.aux.ngids < 1)
/* We do not have a real UID and GID. Lose, lose, lose! */
err = EGRATUITOUS;
/* Create a new auth port using our real UID and GID (the first
auxiliary UID and GID) as the only effective IDs. */
if (!err)
err = __USEPORT (AUTH,
__auth_makeauth (port,
NULL, MACH_MSG_TYPE_COPY_SEND, 0,
_hurd_id.aux.uids, 1,
_hurd_id.aux.uids,
_hurd_id.aux.nuids,
_hurd_id.aux.gids, 1,
_hurd_id.aux.gids,
_hurd_id.aux.ngids,
&_hurd_id.rid_auth));
}
if (!err)
{
/* Use the real-ID auth port in place of the normal one. */
assert (_hurd_id.rid_auth != MACH_PORT_NULL);
auth = _hurd_id.rid_auth;
__mach_port_mod_refs (__mach_task_self (), auth,
MACH_PORT_RIGHT_SEND, +1);
}
__mutex_unlock (&_hurd_id.lock);
}
else
/* Copy our existing auth port. */
err = __USEPORT (AUTH, __mach_port_mod_refs (__mach_task_self (),
(auth = port),
MACH_PORT_RIGHT_SEND, +1));
if (err)
goto out;
/* Pack up the descriptor table to give the new program.
These descriptors will need to be reauthenticated below
if POSIX_SPAWN_RESETIDS is set. */
__mutex_lock (&_hurd_dtable_lock);
dtablesize = _hurd_dtablesize;
orig_dtablesize = _hurd_dtablesize;
dtable = __alloca (dtablesize * sizeof (dtable[0]));
ulink_dtable = __alloca (dtablesize * sizeof (ulink_dtable[0]));
dtable_cells = __alloca (dtablesize * sizeof (dtable_cells[0]));
dtable_cloexec = __alloca (dtablesize);
for (i = 0; i < dtablesize; ++i)
{
struct hurd_fd *const d = _hurd_dtable[i];
if (d == NULL)
{
dtable[i] = MACH_PORT_NULL;
dtable_cells[i] = NULL;
continue;
}
/* Note that this might return MACH_PORT_NULL. */
dtable[i] = _hurd_port_get (&d->port, &ulink_dtable[i]);
dtable_cells[i] = &d->port;
dtable_cloexec[i] = (d->flags & FD_CLOEXEC) != 0;
}
__mutex_unlock (&_hurd_dtable_lock);
/* Safe to let signals happen now. */
_hurd_critical_section_unlock (ss);
/* Execute the file actions. */
if (file_actions != NULL)
for (i = 0; i < file_actions->__used; ++i)
{
/* Close a file descriptor in the child. */
error_t do_close (int fd)
{
if ((unsigned int)fd < dtablesize
&& dtable[fd] != MACH_PORT_NULL)
{
if (dtable_cells[fd] == NULL)
__mach_port_deallocate (__mach_task_self (), dtable[fd]);
else
{
_hurd_port_free (dtable_cells[fd],
&ulink_dtable[fd], dtable[fd]);
}
dtable_cells[fd] = NULL;
dtable[fd] = MACH_PORT_NULL;
return 0;
}
return EBADF;
}
/* Make sure the dtable can hold NEWFD. */
#define EXPAND_DTABLE(newfd) \
({ \
if ((unsigned int)newfd >= dtablesize \
&& newfd < _hurd_rlimits[RLIMIT_OFILE].rlim_cur) \
{ \
/* We need to expand the dtable for the child. */ \
NEW_TABLE (dtable, newfd); \
NEW_TABLE (ulink_dtable, newfd); \
NEW_TABLE (dtable_cells, newfd); \
dtablesize = newfd + 1; \
} \
((unsigned int)newfd < dtablesize ? 0 : EMFILE); \
})
#define NEW_TABLE(x, newfd) \
do { __typeof (x) new_##x = __alloca ((newfd + 1) * sizeof (x[0])); \
memcpy (new_##x, x, dtablesize * sizeof (x[0])); \
memset (&new_##x[dtablesize], 0, (newfd + 1 - dtablesize) * sizeof (x[0])); \
x = new_##x; } while (0)
struct __spawn_action *action = &file_actions->__actions[i];
switch (action->tag)
{
case spawn_do_close:
err = do_close (action->action.close_action.fd);
break;
case spawn_do_dup2:
if ((unsigned int)action->action.dup2_action.fd < dtablesize
&& dtable[action->action.dup2_action.fd] != MACH_PORT_NULL)
{
const int fd = action->action.dup2_action.fd;
const int newfd = action->action.dup2_action.newfd;
// dup2 always clears any old FD_CLOEXEC flag on the new fd.
if (newfd < orig_dtablesize)
dtable_cloexec[newfd] = 0;
if (fd == newfd)
// Same is same as same was.
break;
err = EXPAND_DTABLE (newfd);
if (!err)
{
/* Close the old NEWFD and replace it with FD's
contents, which can be either an original
descriptor (DTABLE_CELLS[FD] != 0) or a new
right that we acquired in this function. */
do_close (newfd);
dtable_cells[newfd] = dtable_cells[fd];
if (dtable_cells[newfd] != NULL)
dtable[newfd] = _hurd_port_get (dtable_cells[newfd],
&ulink_dtable[newfd]);
else
{
dtable[newfd] = dtable[fd];
err = __mach_port_mod_refs (__mach_task_self (),
dtable[fd],
MACH_PORT_RIGHT_SEND, +1);
}
}
}
else
// The old FD specified was bogus.
err = EBADF;
break;
case spawn_do_open:
/* Open a file on behalf of the child.
XXX note that this can subject the parent to arbitrary
delays waiting for the files to open. I don't know what the
spec says about this. If it's not permissible, then this
whole forkless implementation is probably untenable. */
{
const int fd = action->action.open_action.fd;
do_close (fd);
if (fd < orig_dtablesize)
dtable_cloexec[fd] = 0;
err = EXPAND_DTABLE (fd);
if (err)
break;
err = child_lookup (action->action.open_action.path,
action->action.open_action.oflag,
action->action.open_action.mode,
&dtable[fd]);
dtable_cells[fd] = NULL;
break;
}
}
if (err)
goto out;
}
/* Only now can we perform FD_CLOEXEC. We had to leave the descriptors
unmolested for the file actions to use. Note that the DTABLE_CLOEXEC
array is never expanded by file actions, so it might now have fewer
than DTABLESIZE elements. */
for (i = 0; i < orig_dtablesize; ++i)
if (dtable[i] != MACH_PORT_NULL && dtable_cloexec[i])
{
assert (dtable_cells[i] != NULL);
_hurd_port_free (dtable_cells[i], &ulink_dtable[i], dtable[i]);
dtable[i] = MACH_PORT_NULL;
}
/* Prune trailing null ports from the descriptor table. */
while (dtablesize > 0 && dtable[dtablesize - 1] == MACH_PORT_NULL)
--dtablesize;
if (flags & POSIX_SPAWN_RESETIDS)
{
/* Reauthenticate all the child's ports with its new auth handle. */
mach_port_t ref;
process_t newproc;
/* Reauthenticate with the proc server. */
ref = __mach_reply_port ();
err = __proc_reauthenticate (proc, ref, MACH_MSG_TYPE_MAKE_SEND);
if (!err)
err = __auth_user_authenticate (auth,
ref, MACH_MSG_TYPE_MAKE_SEND,
&newproc);
__mach_port_destroy (__mach_task_self (), ref);
if (!err)
{
__mach_port_deallocate (__mach_task_self (), proc);
proc = newproc;
}
if (!err)
err = reauthenticate (INIT_PORT_CRDIR, &rcrdir);
if (!err)
err = reauthenticate (INIT_PORT_CWDIR, &rcwdir);
/* We must reauthenticate all the fds except those that came from
`spawn_do_open' file actions, which were opened using the child's
auth port to begin with. */
for (i = 0; !err && i < dtablesize; ++i)
err = reauthenticate_fd (i);
}
if (err)
goto out;
/* Now we are ready to open the executable file using the child's ports.
We do this after performing all the file actions so the order of
events is the same as for a fork, exec sequence. This affects things
like the meaning of a /dev/fd file name, as well as which error
conditions are diagnosed first and what side effects (file creation,
etc) can be observed before what errors. */
if ((xflags & SPAWN_XFLAGS_USE_PATH) == 0 || strchr (file, '/') != NULL)
/* The FILE parameter is actually a path. */
err = child_lookup (file, O_EXEC, 0, &execfile);
else
{
/* We have to search for FILE on the path. */
path = getenv ("PATH");
if (path == NULL)
{
/* There is no `PATH' in the environment.
The default search path is the current directory
followed by the path `confstr' returns for `_CS_PATH'. */
len = confstr (_CS_PATH, (char *) NULL, 0);
path = (char *) __alloca (1 + len);
path[0] = ':';
(void) confstr (_CS_PATH, path + 1, len);
}
len = strlen (file) + 1;
pathlen = strlen (path);
name = __alloca (pathlen + len + 1);
/* Copy the file name at the top. */
name = (char *) memcpy (name + pathlen + 1, file, len);
/* And add the slash. */
*--name = '/';
p = path;
do
{
char *startp;
path = p;
p = __strchrnul (path, ':');
if (p == path)
/* Two adjacent colons, or a colon at the beginning or the end
of `PATH' means to search the current directory. */
startp = name + 1;
else
startp = (char *) memcpy (name - (p - path), path, p - path);
/* Try to open this file name. */
err = child_lookup (startp, O_EXEC, 0, &execfile);
switch (err)
{
case EACCES:
case ENOENT:
case ESTALE:
case ENOTDIR:
/* Those errors indicate the file is missing or not executable
by us, in which case we want to just try the next path
directory. */
continue;
case 0: /* Success! */
default:
/* Some other error means we found an executable file, but
something went wrong executing it; return the error to our
caller. */
break;
}
// We only get here when we are done looking for the file.
break;
}
while (*p++ != '\0');
}
if (err)
goto out;
/* Almost there! */
{
mach_port_t ports[_hurd_nports];
struct hurd_userlink ulink_ports[_hurd_nports];
char *args = NULL, *env = NULL;
size_t argslen = 0, envlen = 0;
inline error_t exec (file_t file)
{
return __file_exec (file, task,
(__sigismember (&_hurdsig_traced, SIGKILL)
? EXEC_SIGTRAP : 0),
args, argslen, env, envlen,
dtable, MACH_MSG_TYPE_COPY_SEND, dtablesize,
ports, MACH_MSG_TYPE_COPY_SEND, _hurd_nports,
ints, INIT_INT_MAX,
NULL, 0, NULL, 0);
}
/* Now we are out of things that can fail before the file_exec RPC,
for which everything else must be prepared. The only thing left
to do is packing up the argument and environment strings,
and the array of init ports. */
if (argv != NULL)
err = __argz_create (argv, &args, &argslen);
if (!err && envp != NULL)
err = __argz_create (envp, &env, &envlen);
/* Load up the ports to give to the new program.
Note the loop/switch below must parallel exactly to release refs. */
for (i = 0; i < _hurd_nports; ++i)
{
switch (i)
{
case INIT_PORT_AUTH:
ports[i] = auth;
continue;
case INIT_PORT_PROC:
ports[i] = proc;
continue;
case INIT_PORT_CRDIR:
if (flags & POSIX_SPAWN_RESETIDS)
{
ports[i] = rcrdir;
continue;
}
break;
case INIT_PORT_CWDIR:
if (flags & POSIX_SPAWN_RESETIDS)
{
ports[i] = rcwdir;
continue;
}
break;
}
ports[i] = _hurd_port_get (&_hurd_ports[i], &ulink_ports[i]);
}
/* Finally, try executing the file we opened. */
if (!err)
err = exec (execfile);
__mach_port_deallocate (__mach_task_self (), execfile);
if (err == ENOEXEC)
{
/* The file is accessible but it is not an executable file.
Invoke the shell to interpret it as a script. */
err = __argz_insert (&args, &argslen, args, _PATH_BSHELL);
if (!err)
err = child_lookup (_PATH_BSHELL, O_EXEC, 0, &execfile);
if (!err)
{
err = exec (execfile);
__mach_port_deallocate (__mach_task_self (), execfile);
}
}
/* Release the references just packed up in PORTS.
This switch must always parallel the one above that fills PORTS. */
for (i = 0; i < _hurd_nports; ++i)
{
switch (i)
{
case INIT_PORT_AUTH:
case INIT_PORT_PROC:
continue;
case INIT_PORT_CRDIR:
if (flags & POSIX_SPAWN_RESETIDS)
continue;
break;
case INIT_PORT_CWDIR:
if (flags & POSIX_SPAWN_RESETIDS)
continue;
break;
}
_hurd_port_free (&_hurd_ports[i], &ulink_ports[i], ports[i]);
}
free (args);
free (env);
}
/* We did it! We have a child! */
if (pid != NULL)
*pid = new_pid;
out:
/* Clean up all the references we are now holding. */
if (task != MACH_PORT_NULL)
{
if (err)
/* We failed after creating the task, so kill it. */
__task_terminate (task);
__mach_port_deallocate (__mach_task_self (), task);
}
__mach_port_deallocate (__mach_task_self (), auth);
__mach_port_deallocate (__mach_task_self (), proc);
if (rcrdir != MACH_PORT_NULL)
__mach_port_deallocate (__mach_task_self (), rcrdir);
if (rcwdir != MACH_PORT_NULL)
__mach_port_deallocate (__mach_task_self (), rcwdir);
if (ulink_dtable)
/* Release references to the file descriptor ports. */
for (i = 0; i < dtablesize; ++i)
if (dtable[i] != MACH_PORT_NULL)
{
if (dtable_cells[i] == NULL)
__mach_port_deallocate (__mach_task_self (), dtable[i]);
else
_hurd_port_free (dtable_cells[i], &ulink_dtable[i], dtable[i]);
}
if (err)
/* This hack canonicalizes the error code that we return. */
err = (__hurd_fail (err), errno);
return err;
}
| 32.451058 | 87 | 0.646435 | [
"model"
] |
328b72d338ae927fed1922b4b1a7e659981a587e | 2,282 | h | C | common/thirdparty/jenn3d/polytopes.h | b3sigma/fourd | 8df1300d9820ffa65e0df4519ce3795f1b2e7c9c | [
"MIT"
] | 20 | 2015-05-15T20:46:40.000Z | 2022-02-26T14:30:37.000Z | common/thirdparty/jenn3d/polytopes.h | b3sigma/fourd | 8df1300d9820ffa65e0df4519ce3795f1b2e7c9c | [
"MIT"
] | null | null | null | common/thirdparty/jenn3d/polytopes.h | b3sigma/fourd | 8df1300d9820ffa65e0df4519ce3795f1b2e7c9c | [
"MIT"
] | 3 | 2016-08-13T09:44:49.000Z | 2018-07-29T16:52:41.000Z | /*
This file is part of Jenn.
Copyright 2001-2007 Fritz Obermeyer.
Jenn is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Jenn is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jenn; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef JENN_POLYTOPES_H
#define JENN_POLYTOPES_H
#include "definitions.h"
#include "linalg.h"
#include "todd_coxeter.h"
#include <vector>
namespace jenn {
namespace Polytope
{
const Logging::Logger logger("poly", Logging::INFO);
//conversions
typedef std::vector<int> Word;
typedef std::vector<Word> WordList;
Word int2word(int g);
Word str2word(const char* g);
Vect int2Vect(int w);
ToddCoxeter::Graph* view(const int* coxeter, //upper triang of cox. matrix
const WordList& gens, //subgroup generators
const WordList& v_cogens, //vertex-stabilizing words
const WordList& e_gens, //edge words: origin to ___
const WordList& f_gens, //generator pairs, or empty word for all faces
const Vect& weights); //vertex weights, for positioning center
ToddCoxeter::Graph* select(int code, int edges = 1111, int faces = 111111, int weights = 1111);
ToddCoxeter::Graph* selectNext();
ToddCoxeter::Graph* selectPrev();
//named polytopes
const int the_5_cell = 322323234;
const int the_8_cell = 422323234;
const int the_16_cell = 322324234;
const int the_24_cell = 322423234;
const int the_120_cell = 522323234;
const int the_600_cell = 322325234;
const int graph_torus = 922229000;
const int graph_333 = 322323000;
const int graph_Y = 333222000;
const int graph_334 = 422323000;
const int graph_343 = 322423000;
const int graph_335 = 522323000;
}
}; // namespace jenn
#endif //JENN_POLYTOPES_H
| 30.026316 | 99 | 0.716477 | [
"vector"
] |
328f8b1a0a9eb860201476d727aed024f5b87d36 | 72,552 | c | C | assets/lsd/lsd.c | mvrl/gc-horizon-detector | 5f4ce00165b189a52e9d17181987218ff7f64f1b | [
"MIT"
] | 40 | 2016-06-19T23:02:03.000Z | 2021-12-20T08:35:34.000Z | assets/lsd/lsd.c | mvrl/gc-horizon-detector | 5f4ce00165b189a52e9d17181987218ff7f64f1b | [
"MIT"
] | 2 | 2015-05-20T08:13:07.000Z | 2015-05-20T08:13:07.000Z | Core/src/external/lsd/lsd.c | YabinXuTUD/HRBFFusion3D | 20dbff99782f31844791b09824bbfd9370d4a0c4 | [
"BSD-3-Clause"
] | 17 | 2016-08-29T09:19:15.000Z | 2021-11-18T17:53:10.000Z | /*----------------------------------------------------------------------------
LSD - Line Segment Detector on digital images
Copyright 2007-2010 rafael grompone von gioi (grompone@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** @file lsd.c
LSD module code
@author rafael grompone von gioi (grompone@gmail.com)
*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** @mainpage LSD code documentation
This is an implementation of the Line Segment Detector described
in the paper:
"LSD: A Fast Line Segment Detector with a False Detection Control"
by Rafael Grompone von Gioi, Jeremie Jakubowicz, Jean-Michel Morel,
and Gregory Randall, IEEE Transactions on Pattern Analysis and
Machine Intelligence, vol. 32, no. 4, pp. 722-732, April, 2010.
and in more details in the CMLA Technical Report:
"LSD: A Line Segment Detector, Technical Report",
by Rafael Grompone von Gioi, Jeremie Jakubowicz, Jean-Michel Morel,
Gregory Randall, CMLA, ENS Cachan, 2010.
The version implemented here includes some further improvements
described on the LSD page at www.ipol.im. That same page includes
more information, including this code and an online demo version:
http://www.ipol.im/pub/algo/gjmr_line_segment_detector
The module's main function is lsd().
The source code is contained in two files: lsd.h and lsd.c.
HISTORY:
- version 1.5 - dic 2010: Changes in 'refine', -W option added,
and more comments added.
- version 1.4 - jul 2010: lsd_scale interface added and doxygen doc.
- version 1.3 - feb 2010: Multiple bug correction and improved code.
- version 1.2 - dic 2009: First full Ansi C Language version.
- version 1.1 - sep 2009: Systematic subsampling to scale 0.8 and
correction to partially handle"angle problem".
- version 1.0 - jan 2009: First complete Megawave2 and Ansi C Language
version.
@author rafael grompone von gioi (grompone@gmail.com)
*/
/*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <float.h>
#include "lsd.h"
/** ln(10) */
#ifndef M_LN10
#define M_LN10 2.30258509299404568402
#endif /* !M_LN10 */
/** PI */
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif /* !M_PI */
#ifndef FALSE
#define FALSE 0
#endif /* !FALSE */
#ifndef TRUE
#define TRUE 1
#endif /* !TRUE */
/** Label for pixels with undefined gradient. */
#define NOTDEF -1024.0
/** 3/2 pi */
#define M_3_2_PI 4.71238898038
/** 2 pi */
#define M_2__PI 6.28318530718
/** Label for pixels not used in yet. */
#define NOTUSED 0
/** Label for pixels already used in detection. */
#define USED 1
/*----------------------------------------------------------------------------*/
/** Chained list of coordinates.
*/
struct coorlist
{
int x,y;
struct coorlist * next;
};
/*----------------------------------------------------------------------------*/
/** A point (or pixel).
*/
struct point {int x,y;};
/*----------------------------------------------------------------------------*/
/*------------------------- Miscellaneous functions --------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Fatal error, print a message to standard-error output and exit.
*/
static void error(char * msg)
{
fprintf(stderr,"LSD Error: %s\n",msg);
exit(EXIT_FAILURE);
}
/*----------------------------------------------------------------------------*/
/** Doubles relative error factor
*/
#define RELATIVE_ERROR_FACTOR 100.0
/*----------------------------------------------------------------------------*/
/** Compare doubles by relative error.
The resulting rounding error after floating point computations
depend on the specific operations done. The same number computed by
different algorithms could present different rounding errors. For a
useful comparison, an estimation of the relative rounding error
should be considered and compared to a factor times EPS. The factor
should be related to the cumulated rounding error in the chain of
computation. Here, as a simplification, a fixed factor is used.
*/
static int double_equal(double a, double b)
{
double abs_diff,aa,bb,abs_max;
/* trivial case */
if( a == b ) return TRUE;
abs_diff = fabs(a-b);
aa = fabs(a);
bb = fabs(b);
abs_max = aa > bb ? aa : bb;
/* DBL_MIN is the smallest normalized number, thus, the smallest
number whose relative error is bounded by DBL_EPSILON. For
smaller numbers, the same quantization steps as for DBL_MIN
are used. Then, for smaller numbers, a meaningful "relative"
error should be computed by dividing the difference by DBL_MIN. */
if( abs_max < DBL_MIN ) abs_max = DBL_MIN;
/* equal if relative error <= factor x eps */
return (abs_diff / abs_max) <= (RELATIVE_ERROR_FACTOR * DBL_EPSILON);
}
/*----------------------------------------------------------------------------*/
/** Computes Euclidean distance between point (x1,y1) and point (x2,y2).
*/
static double dist(double x1, double y1, double x2, double y2)
{
return sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
}
/*----------------------------------------------------------------------------*/
/*----------------------- 'list of n-tuple' data type ------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Free memory used in n-tuple 'in'.
*/
void free_ntuple_list(ntuple_list in)
{
if( in == NULL || in->values == NULL )
error("free_ntuple_list: invalid n-tuple input.");
free( (void *) in->values );
free( (void *) in );
}
/*----------------------------------------------------------------------------*/
/** Create an n-tuple list and allocate memory for one element.
@param dim the dimension (n) of the n-tuple.
*/
ntuple_list new_ntuple_list(unsigned int dim)
{
ntuple_list n_tuple;
/* check parameters */
if( dim == 0 ) error("new_ntuple_list: 'dim' must be positive.");
/* get memory for list structure */
n_tuple = (ntuple_list) malloc( sizeof(struct ntuple_list_s) );
if( n_tuple == NULL ) error("not enough memory.");
/* initialize list */
n_tuple->size = 0;
n_tuple->max_size = 1;
n_tuple->dim = dim;
/* get memory for tuples */
n_tuple->values = (double *) malloc( dim*n_tuple->max_size * sizeof(double) );
if( n_tuple->values == NULL ) error("not enough memory.");
return n_tuple;
}
/*----------------------------------------------------------------------------*/
/** Enlarge the allocated memory of an n-tuple list.
*/
static void enlarge_ntuple_list(ntuple_list n_tuple)
{
/* check parameters */
if( n_tuple == NULL || n_tuple->values == NULL || n_tuple->max_size == 0 )
error("enlarge_ntuple_list: invalid n-tuple.");
/* duplicate number of tuples */
n_tuple->max_size *= 2;
/* realloc memory */
n_tuple->values = (double *) realloc( (void *) n_tuple->values,
n_tuple->dim * n_tuple->max_size * sizeof(double) );
if( n_tuple->values == NULL ) error("not enough memory.");
}
/*----------------------------------------------------------------------------*/
/** Add a 5-tuple to an n-tuple list.
*/
static void add_5tuple( ntuple_list out, double v1, double v2,
double v3, double v4, double v5 )
{
/* check parameters */
if( out == NULL ) error("add_5tuple: invalid n-tuple input.");
if( out->dim != 5 ) error("add_5tuple: the n-tuple must be a 5-tuple.");
/* if needed, alloc more tuples to 'out' */
if( out->size == out->max_size ) enlarge_ntuple_list(out);
if( out->values == NULL ) error("add_5tuple: invalid n-tuple input.");
/* add new 5-tuple */
out->values[ out->size * out->dim + 0 ] = v1;
out->values[ out->size * out->dim + 1 ] = v2;
out->values[ out->size * out->dim + 2 ] = v3;
out->values[ out->size * out->dim + 3 ] = v4;
out->values[ out->size * out->dim + 4 ] = v5;
/* update number of tuples counter */
out->size++;
}
/*----------------------------------------------------------------------------*/
/*----------------------------- Image Data Types -----------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Free memory used in image_char 'i'.
*/
void free_image_char(image_char i)
{
if( i == NULL || i->data == NULL )
error("free_image_char: invalid input image.");
free( (void *) i->data );
free( (void *) i );
}
/*----------------------------------------------------------------------------*/
/** Create a new image_char of size 'xsize' times 'ysize'.
*/
image_char new_image_char(unsigned int xsize, unsigned int ysize)
{
image_char image;
/* check parameters */
if( xsize == 0 || ysize == 0 ) error("new_image_char: invalid image size.");
/* get memory */
image = (image_char) malloc( sizeof(struct image_char_s) );
if( image == NULL ) error("not enough memory.");
image->data = (unsigned char *) calloc( (size_t) (xsize*ysize),
sizeof(unsigned char) );
if( image->data == NULL ) error("not enough memory.");
/* set image size */
image->xsize = xsize;
image->ysize = ysize;
return image;
}
/*----------------------------------------------------------------------------*/
/** Create a new image_char of size 'xsize' times 'ysize',
initialized to the value 'fill_value'.
*/
image_char new_image_char_ini( unsigned int xsize, unsigned int ysize,
unsigned char fill_value )
{
image_char image = new_image_char(xsize,ysize); /* create image */
unsigned int N = xsize*ysize;
unsigned int i;
/* check parameters */
if( image == NULL || image->data == NULL )
error("new_image_char_ini: invalid image.");
/* initialize */
for(i=0; i<N; i++) image->data[i] = fill_value;
return image;
}
/*----------------------------------------------------------------------------*/
/** Free memory used in image_int 'i'.
*/
void free_image_int(image_int i)
{
if( i == NULL || i->data == NULL )
error("free_image_int: invalid input image.");
free( (void *) i->data );
free( (void *) i );
}
/*----------------------------------------------------------------------------*/
/** Create a new image_int of size 'xsize' times 'ysize'.
*/
image_int new_image_int(unsigned int xsize, unsigned int ysize)
{
image_int image;
/* check parameters */
if( xsize == 0 || ysize == 0 ) error("new_image_int: invalid image size.");
/* get memory */
image = (image_int) malloc( sizeof(struct image_int_s) );
if( image == NULL ) error("not enough memory.");
image->data = (int *) calloc( (size_t) (xsize*ysize), sizeof(int) );
if( image->data == NULL ) error("not enough memory.");
/* set image size */
image->xsize = xsize;
image->ysize = ysize;
return image;
}
/*----------------------------------------------------------------------------*/
/** Create a new image_int of size 'xsize' times 'ysize',
initialized to the value 'fill_value'.
*/
image_int new_image_int_ini( unsigned int xsize, unsigned int ysize,
int fill_value )
{
image_int image = new_image_int(xsize,ysize); /* create image */
unsigned int N = xsize*ysize;
unsigned int i;
/* initialize */
for(i=0; i<N; i++) image->data[i] = fill_value;
return image;
}
/*----------------------------------------------------------------------------*/
/** Free memory used in image_double 'i'.
*/
void free_image_double(image_double i)
{
if( i == NULL || i->data == NULL )
error("free_image_double: invalid input image.");
free( (void *) i->data );
free( (void *) i );
}
/*----------------------------------------------------------------------------*/
/** Create a new image_double of size 'xsize' times 'ysize'.
*/
image_double new_image_double(unsigned int xsize, unsigned int ysize)
{
image_double image;
/* check parameters */
if( xsize == 0 || ysize == 0 ) error("new_image_double: invalid image size.");
/* get memory */
image = (image_double) malloc( sizeof(struct image_double_s) );
if( image == NULL ) error("not enough memory.");
image->data = (double *) calloc( (size_t) (xsize*ysize), sizeof(double) );
if( image->data == NULL ) error("not enough memory.");
/* set image size */
image->xsize = xsize;
image->ysize = ysize;
return image;
}
/*----------------------------------------------------------------------------*/
/** Create a new image_double of size 'xsize' times 'ysize',
initialized to the value 'fill_value'.
*/
image_double new_image_double_ini( unsigned int xsize, unsigned int ysize,
double fill_value )
{
image_double image = new_image_double(xsize,ysize); /* create image */
unsigned int N = xsize*ysize;
unsigned int i;
/* initialize */
for(i=0; i<N; i++) image->data[i] = fill_value;
return image;
}
/*----------------------------------------------------------------------------*/
/*----------------------------- Gaussian filter ------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Compute a Gaussian kernel of length 'kernel->dim',
standard deviation 'sigma', and centered at value 'mean'.
For example, if mean=0.5, the Gaussian will be centered
in the middle point between values 'kernel->values[0]'
and 'kernel->values[1]'.
*/
static void gaussian_kernel(ntuple_list kernel, double sigma, double mean)
{
double sum = 0.0;
double val;
unsigned int i;
/* check parameters */
if( kernel == NULL || kernel->values == NULL )
error("gaussian_kernel: invalid n-tuple 'kernel'.");
if( sigma <= 0.0 ) error("gaussian_kernel: 'sigma' must be positive.");
/* compute Gaussian kernel */
if( kernel->max_size < 1 ) enlarge_ntuple_list(kernel);
kernel->size = 1;
for(i=0;i<kernel->dim;i++)
{
val = ( (double) i - mean ) / sigma;
kernel->values[i] = exp( -0.5 * val * val );
sum += kernel->values[i];
}
/* normalization */
if( sum >= 0.0 ) for(i=0;i<kernel->dim;i++) kernel->values[i] /= sum;
}
/*----------------------------------------------------------------------------*/
/** Scale the input image 'in' by a factor 'scale' by Gaussian sub-sampling.
For example, scale=0.8 will give a result at 80% of the original size.
The image is convolved with a Gaussian kernel
@f[
G(x,y) = \frac{1}{2\pi\sigma^2} e^{-\frac{x^2+y^2}{2\sigma^2}}
@f]
before the sub-sampling to prevent aliasing.
The standard deviation sigma given by:
- sigma = sigma_scale / scale, if scale < 1.0
- sigma = sigma_scale, if scale >= 1.0
To be able to sub-sample at non-integer steps, some interpolation
is needed. In this implementation, the interpolation is done by
the Gaussian kernel, so both operations (filtering and sampling)
are done at the same time. The Gaussian kernel is computed
centered on the coordinates of the required sample. In this way,
when applied, it gives directly the result of convolving the image
with the kernel and interpolated to that particular position.
A fast algorithm is done using the separability of the Gaussian
kernel. Applying the 2D Gaussian kernel is equivalent to applying
first a horizontal 1D Gaussian kernel and then a vertical 1D
Gaussian kernel (or the other way round). The reason is that
@f[
G(x,y) = G(x) * G(y)
@f]
where
@f[
G(x) = \frac{1}{\sqrt{2\pi}\sigma} e^{-\frac{x^2}{2\sigma^2}}.
@f]
The algorithm first apply a combined Gaussian kernel and sampling
in the x axis, and then the combined Gaussian kernel and sampling
in the y axis.
*/
static image_double gaussian_sampler( image_double in, double scale,
double sigma_scale )
{
image_double aux,out;
ntuple_list kernel;
unsigned int N,M,h,n,x,y,i;
int xc,yc,j,double_x_size,double_y_size;
double sigma,xx,yy,sum,prec;
/* check parameters */
if( in == NULL || in->data == NULL || in->xsize == 0 || in->ysize == 0 )
error("gaussian_sampler: invalid image.");
if( scale <= 0.0 ) error("gaussian_sampler: 'scale' must be positive.");
if( sigma_scale <= 0.0 )
error("gaussian_sampler: 'sigma_scale' must be positive.");
/* get memory for images */
if( in->xsize * scale > (double) UINT_MAX ||
in->ysize * scale > (double) UINT_MAX )
error("gaussian_sampler: the output image size exceeds the handled size.");
N = (unsigned int) floor( in->xsize * scale );
M = (unsigned int) floor( in->ysize * scale );
aux = new_image_double(N,in->ysize);
out = new_image_double(N,M);
/* sigma, kernel size and memory for the kernel */
sigma = scale < 1.0 ? sigma_scale / scale : sigma_scale;
/*
The size of the kernel is selected to guarantee that the
the first discarded term is at least 10^prec times smaller
than the central value. For that, h should be larger than x, with
e^(-x^2/2sigma^2) = 1/10^prec.
Then,
x = sigma * sqrt( 2 * prec * ln(10) ).
*/
prec = 3.0;
h = (unsigned int) ceil( sigma * sqrt( 2.0 * prec * log(10.0) ) );
n = 1+2*h; /* kernel size */
kernel = new_ntuple_list(n);
/* auxiliary double image size variables */
double_x_size = (int) (2 * in->xsize);
double_y_size = (int) (2 * in->ysize);
/* First subsampling: x axis */
for(x=0;x<aux->xsize;x++)
{
/*
x is the coordinate in the new image.
xx is the corresponding x-value in the original size image.
xc is the integer value, the pixel coordinate of xx.
*/
xx = (double) x / scale;
/* coordinate (0.0,0.0) is in the center of pixel (0,0),
so the pixel with xc=0 get the values of xx from -0.5 to 0.5 */
xc = (int) floor( xx + 0.5 );
gaussian_kernel( kernel, sigma, (double) h + xx - (double) xc );
/* the kernel must be computed for each x because the fine
offset xx-xc is different in each case */
for(y=0;y<aux->ysize;y++)
{
sum = 0.0;
for(i=0;i<kernel->dim;i++)
{
j = xc - h + i;
/* symmetry boundary condition */
while( j < 0 ) j += double_x_size;
while( j >= double_x_size ) j -= double_x_size;
if( j >= (int) in->xsize ) j = double_x_size-1-j;
sum += in->data[ j + y * in->xsize ] * kernel->values[i];
}
aux->data[ x + y * aux->xsize ] = sum;
}
}
/* Second subsampling: y axis */
for(y=0;y<out->ysize;y++)
{
/*
y is the coordinate in the new image.
yy is the corresponding x-value in the original size image.
yc is the integer value, the pixel coordinate of xx.
*/
yy = (double) y / scale;
/* coordinate (0.0,0.0) is in the center of pixel (0,0),
so the pixel with yc=0 get the values of yy from -0.5 to 0.5 */
yc = (int) floor( yy + 0.5 );
gaussian_kernel( kernel, sigma, (double) h + yy - (double) yc );
/* the kernel must be computed for each y because the fine
offset yy-yc is different in each case */
for(x=0;x<out->xsize;x++)
{
sum = 0.0;
for(i=0;i<kernel->dim;i++)
{
j = yc - h + i;
/* symmetry boundary condition */
while( j < 0 ) j += double_y_size;
while( j >= double_y_size ) j -= double_y_size;
if( j >= (int) in->ysize ) j = double_y_size-1-j;
sum += aux->data[ x + j * aux->xsize ] * kernel->values[i];
}
out->data[ x + y * out->xsize ] = sum;
}
}
/* free memory */
free_ntuple_list(kernel);
free_image_double(aux);
return out;
}
/*----------------------------------------------------------------------------*/
/*--------------------------------- Gradient ---------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Computes the direction of the level line of 'in' at each point.
The result is:
- an image_double with the angle at each pixel, or NOTDEF if not defined.
- the image_double 'modgrad' (a pointer is passed as argument)
with the gradient magnitude at each point.
- a list of pixels 'list_p' roughly ordered by decreasing
gradient magnitude. (The order is made by classifying points
into bins by gradient magnitude. The parameters 'n_bins' and
'max_grad' specify the number of bins and the gradient modulus
at the highest bin. The pixels in the list would be in
decreasing gradient magnitude, up to a precision of the size of
the bins.)
- a pointer 'mem_p' to the memory used by 'list_p' to be able to
free the memory when it is not used anymore.
*/
static image_double ll_angle( image_double in, double threshold,
struct coorlist ** list_p, void ** mem_p,
image_double * modgrad, unsigned int n_bins,
double max_grad )
{
image_double g;
unsigned int n,p,x,y,adr,i;
double com1,com2,gx,gy,norm,norm2;
/* the rest of the variables are used for pseudo-ordering
the gradient magnitude values */
int list_count = 0;
struct coorlist * list;
struct coorlist ** range_l_s; /* array of pointers to start of bin list */
struct coorlist ** range_l_e; /* array of pointers to end of bin list */
struct coorlist * start;
struct coorlist * end;
/* check parameters */
if( in == NULL || in->data == NULL || in->xsize == 0 || in->ysize == 0 )
error("ll_angle: invalid image.");
if( threshold < 0.0 ) error("ll_angle: 'threshold' must be positive.");
if( list_p == NULL ) error("ll_angle: NULL pointer 'list_p'.");
if( mem_p == NULL ) error("ll_angle: NULL pointer 'mem_p'.");
if( modgrad == NULL ) error("ll_angle: NULL pointer 'modgrad'.");
if( n_bins == 0 ) error("ll_angle: 'n_bins' must be positive.");
if( max_grad <= 0.0 ) error("ll_angle: 'max_grad' must be positive.");
/* image size shortcuts */
n = in->ysize;
p = in->xsize;
/* allocate output image */
g = new_image_double(in->xsize,in->ysize);
/* get memory for the image of gradient modulus */
*modgrad = new_image_double(in->xsize,in->ysize);
/* get memory for "ordered" list of pixels */
list = (struct coorlist *) calloc( (size_t) (n*p), sizeof(struct coorlist) );
*mem_p = (void *) list;
range_l_s = (struct coorlist **) calloc( (size_t) n_bins,
sizeof(struct coorlist *) );
range_l_e = (struct coorlist **) calloc( (size_t) n_bins,
sizeof(struct coorlist *) );
if( list == NULL || range_l_s == NULL || range_l_e == NULL )
error("not enough memory.");
for(i=0;i<n_bins;i++) range_l_s[i] = range_l_e[i] = NULL;
/* 'undefined' on the down and right boundaries */
for(x=0;x<p;x++) g->data[(n-1)*p+x] = NOTDEF;
for(y=0;y<n;y++) g->data[p*y+p-1] = NOTDEF;
/* compute gradient on the remaining pixels */
for(x=0;x<p-1;x++)
for(y=0;y<n-1;y++)
{
adr = y*p+x;
/*
Norm 2 computation using 2x2 pixel window:
A B
C D
and
com1 = D-A, com2 = B-C.
Then
gx = B+D - (A+C) horizontal difference
gy = C+D - (A+B) vertical difference
com1 and com2 are just to avoid 2 additions.
*/
com1 = in->data[adr+p+1] - in->data[adr];
com2 = in->data[adr+1] - in->data[adr+p];
gx = com1+com2; /* gradient x component */
gy = com1-com2; /* gradient y component */
norm2 = gx*gx+gy*gy;
norm = sqrt( norm2 / 4.0 ); /* gradient norm */
(*modgrad)->data[adr] = norm; /* store gradient norm */
if( norm <= threshold ) /* norm too small, gradient no defined */
g->data[adr] = NOTDEF; /* gradient angle not defined */
else
{
/* gradient angle computation */
g->data[adr] = atan2(gx,-gy);
/* store the point in the right bin according to its norm */
i = (unsigned int) (norm * (double) n_bins / max_grad);
if( i >= n_bins ) i = n_bins-1;
if( range_l_e[i] == NULL )
range_l_s[i] = range_l_e[i] = list+list_count++;
else
{
range_l_e[i]->next = list+list_count;
range_l_e[i] = list+list_count++;
}
range_l_e[i]->x = (int) x;
range_l_e[i]->y = (int) y;
range_l_e[i]->next = NULL;
}
}
/* Make the list of pixels (almost) ordered by norm value.
It starts by the larger bin, so the list starts by the
pixels with higher gradient value. Pixels would be ordered
by norm value, up to a precision given by max_grad/n_bins.
*/
for(i=n_bins-1; i>0 && range_l_s[i]==NULL; i--);
start = range_l_s[i];
end = range_l_e[i];
if( start != NULL )
for(i--;i>0; i--)
if( range_l_s[i] != NULL )
{
end->next = range_l_s[i];
end = range_l_e[i];
}
*list_p = start;
/* free memory */
free( (void *) range_l_s );
free( (void *) range_l_e );
return g;
}
/*----------------------------------------------------------------------------*/
/** Is point (x,y) aligned to angle theta, up to precision 'prec'?
*/
static int isaligned( int x, int y, image_double angles, double theta,
double prec )
{
double a;
/* check parameters */
if( angles == NULL || angles->data == NULL )
error("isaligned: invalid image 'angles'.");
if( x < 0 || y < 0 || x >= (int) angles->xsize || y >= (int) angles->ysize )
error("isaligned: (x,y) out of the image.");
if( prec < 0.0 ) error("isaligned: 'prec' must be positive.");
/* angle at pixel (x,y) */
a = angles->data[ x + y * angles->xsize ];
/* pixels whose level-line angle is not defined
are considered as NON-aligned */
if( a == NOTDEF ) return FALSE; /* there is no need to call the function
'double_equal' here because there is
no risk of problems related to the
comparison doubles, we are only
interested in the exact NOTDEF value */
/* it is assumed that 'theta' and 'a' are in the range [-pi,pi] */
theta -= a;
if( theta < 0.0 ) theta = -theta;
if( theta > M_3_2_PI )
{
theta -= M_2__PI;
if( theta < 0.0 ) theta = -theta;
}
return theta < prec;
}
/*----------------------------------------------------------------------------*/
/** Absolute value angle difference.
*/
static double angle_diff(double a, double b)
{
a -= b;
while( a <= -M_PI ) a += M_2__PI;
while( a > M_PI ) a -= M_2__PI;
if( a < 0.0 ) a = -a;
return a;
}
/*----------------------------------------------------------------------------*/
/** Signed angle difference.
*/
static double angle_diff_signed(double a, double b)
{
a -= b;
while( a <= -M_PI ) a += M_2__PI;
while( a > M_PI ) a -= M_2__PI;
return a;
}
/*----------------------------------------------------------------------------*/
/*----------------------------- NFA computation ------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Computes the natural logarithm of the absolute value of
the gamma function of x using the Lanczos approximation.
See http://www.rskey.org/gamma.htm
The formula used is
@f[
\Gamma(x) = \frac{ \sum_{n=0}^{N} q_n x^n }{ \Pi_{n=0}^{N} (x+n) }
(x+5.5)^{x+0.5} e^{-(x+5.5)}
@f]
so
@f[
\log\Gamma(x) = \log\left( \sum_{n=0}^{N} q_n x^n \right)
+ (x+0.5) \log(x+5.5) - (x+5.5) - \sum_{n=0}^{N} \log(x+n)
@f]
and
q0 = 75122.6331530,
q1 = 80916.6278952,
q2 = 36308.2951477,
q3 = 8687.24529705,
q4 = 1168.92649479,
q5 = 83.8676043424,
q6 = 2.50662827511.
*/
static double log_gamma_lanczos(double x)
{
static double q[7] = { 75122.6331530, 80916.6278952, 36308.2951477,
8687.24529705, 1168.92649479, 83.8676043424,
2.50662827511 };
double a = (x+0.5) * log(x+5.5) - (x+5.5);
double b = 0.0;
int n;
for(n=0;n<7;n++)
{
a -= log( x + (double) n );
b += q[n] * pow( x, (double) n );
}
return a + log(b);
}
/*----------------------------------------------------------------------------*/
/** Computes the natural logarithm of the absolute value of
the gamma function of x using Windschitl method.
See http://www.rskey.org/gamma.htm
The formula used is
@f[
\Gamma(x) = \sqrt{\frac{2\pi}{x}} \left( \frac{x}{e}
\sqrt{ x\sinh(1/x) + \frac{1}{810x^6} } \right)^x
@f]
so
@f[
\log\Gamma(x) = 0.5\log(2\pi) + (x-0.5)\log(x) - x
+ 0.5x\log\left( x\sinh(1/x) + \frac{1}{810x^6} \right).
@f]
This formula is a good approximation when x > 15.
*/
static double log_gamma_windschitl(double x)
{
return 0.918938533204673 + (x-0.5)*log(x) - x
+ 0.5*x*log( x*sinh(1/x) + 1/(810.0*pow(x,6.0)) );
}
/*----------------------------------------------------------------------------*/
/** Computes the natural logarithm of the absolute value of
the gamma function of x. When x>15 use log_gamma_windschitl(),
otherwise use log_gamma_lanczos().
*/
#define log_gamma(x) ((x)>15.0?log_gamma_windschitl(x):log_gamma_lanczos(x))
/*----------------------------------------------------------------------------*/
/** Size of the table to store already computed inverse values.
*/
#define TABSIZE 100000
/*----------------------------------------------------------------------------*/
/** Computes -log10(NFA).
NFA stands for Number of False Alarms:
@f[
\mathrm{NFA} = NT \cdot B(n,k,p)
@f]
- NT - number of tests
- B(n,k,p) - tail of binomial distribution with parameters n,k and p:
@f[
B(n,k,p) = \sum_{j=k}^n
\left(\begin{array}{c}n\\j\end{array}\right)
p^{j} (1-p)^{n-j}
@f]
The value -log10(NFA) is equivalent but more intuitive than NFA:
- -1 corresponds to 10 mean false alarms
- 0 corresponds to 1 mean false alarm
- 1 corresponds to 0.1 mean false alarms
- 2 corresponds to 0.01 mean false alarms
- ...
Used this way, the bigger the value, better the detection,
and a logarithmic scale is used.
@param n,k,p binomial parameters.
@param logNT logarithm of Number of Tests
The computation is based in the gamma function by the following
relation:
@f[
\left(\begin{array}{c}n\\k\end{array}\right)
= \frac{ \Gamma(n+1) }{ \Gamma(k+1) \cdot \Gamma(n-k+1) }.
@f]
We use efficient algorithms to compute the logarithm of
the gamma function.
To make the computation faster, not all the sum is computed, part
of the terms are neglected based on a bound to the error obtained
(an error of 10% in the result is accepted).
*/
static double nfa(int n, int k, double p, double logNT)
{
static double inv[TABSIZE]; /* table to keep computed inverse values */
double tolerance = 0.1; /* an error of 10% in the result is accepted */
double log1term,term,bin_term,mult_term,bin_tail,err,p_term;
int i;
/* check parameters */
if( n<0 || k<0 || k>n || p<=0.0 || p>=1.0 )
error("nfa: wrong n, k or p values.");
/* trivial cases */
if( n==0 || k==0 ) return -logNT;
if( n==k ) return -logNT - (double) n * log10(p);
/* probability term */
p_term = p / (1.0-p);
/* compute the first term of the series */
/*
binomial_tail(n,k,p) = sum_{i=k}^n bincoef(n,i) * p^i * (1-p)^{n-i}
where bincoef(n,i) are the binomial coefficients.
But
bincoef(n,k) = gamma(n+1) / ( gamma(k+1) * gamma(n-k+1) ).
We use this to compute the first term. Actually the log of it.
*/
log1term = log_gamma( (double) n + 1.0 ) - log_gamma( (double) k + 1.0 )
- log_gamma( (double) (n-k) + 1.0 )
+ (double) k * log(p) + (double) (n-k) * log(1.0-p);
term = exp(log1term);
/* in some cases no more computations are needed */
if( double_equal(term,0.0) ) /* the first term is almost zero */
{
if( (double) k > (double) n * p ) /* at begin or end of the tail? */
return -log1term / M_LN10 - logNT; /* end: use just the first term */
else
return -logNT; /* begin: the tail is roughly 1 */
}
/* compute more terms if needed */
bin_tail = term;
for(i=k+1;i<=n;i++)
{
/*
As
term_i = bincoef(n,i) * p^i * (1-p)^(n-i)
and
bincoef(n,i)/bincoef(n,i-1) = n-1+1 / i,
then,
term_i / term_i-1 = (n-i+1)/i * p/(1-p)
and
term_i = term_i-1 * (n-i+1)/i * p/(1-p).
1/i is stored in a table as they are computed,
because divisions are expensive.
p/(1-p) is computed only once and stored in 'p_term'.
*/
bin_term = (double) (n-i+1) * ( i<TABSIZE ?
( inv[i]!=0.0 ? inv[i] : ( inv[i] = 1.0 / (double) i ) ) :
1.0 / (double) i );
mult_term = bin_term * p_term;
term *= mult_term;
bin_tail += term;
if(bin_term<1.0)
{
/* When bin_term<1 then mult_term_j<mult_term_i for j>i.
Then, the error on the binomial tail when truncated at
the i term can be bounded by a geometric series of form
term_i * sum mult_term_i^j. */
err = term * ( ( 1.0 - pow( mult_term, (double) (n-i+1) ) ) /
(1.0-mult_term) - 1.0 );
/* One wants an error at most of tolerance*final_result, or:
tolerance * abs(-log10(bin_tail)-logNT).
Now, the error that can be accepted on bin_tail is
given by tolerance*final_result divided by the derivative
of -log10(x) when x=bin_tail. that is:
tolerance * abs(-log10(bin_tail)-logNT) / (1/bin_tail)
Finally, we truncate the tail if the error is less than:
tolerance * abs(-log10(bin_tail)-logNT) * bin_tail */
if( err < tolerance * fabs(-log10(bin_tail)-logNT) * bin_tail ) break;
}
}
return -log10(bin_tail) - logNT;
}
/*----------------------------------------------------------------------------*/
/*--------------------------- Rectangle structure ----------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Rectangle structure: line segment with width.
*/
struct rect
{
double x1,y1,x2,y2; /* first and second point of the line segment */
double width; /* rectangle width */
double x,y; /* center of the rectangle */
double theta; /* angle */
double dx,dy; /* vector with the line segment angle */
double prec; /* tolerance angle */
double p; /* probability of a point with angle within 'prec' */
};
/*----------------------------------------------------------------------------*/
/** Copy one rectangle structure to another.
*/
static void rect_copy(struct rect * in, struct rect * out)
{
/* check parameters */
if( in == NULL || out == NULL ) error("rect_copy: invalid 'in' or 'out'.");
/* copy values */
out->x1 = in->x1;
out->y1 = in->y1;
out->x2 = in->x2;
out->y2 = in->y2;
out->width = in->width;
out->x = in->x;
out->y = in->y;
out->theta = in->theta;
out->dx = in->dx;
out->dy = in->dy;
out->prec = in->prec;
out->p = in->p;
}
/*----------------------------------------------------------------------------*/
/** Rectangle points iterator.
The integer coordinates of pixels inside a rectangle are
iteratively explored. This structure keep track of the process and
functions ri_ini(), ri_inc(), ri_end(), and ri_del() are used in
the process. An example of how to use the iterator is as follows:
\code
struct rect * rec = XXX; // some rectangle
rect_iter * i;
for( i=ri_ini(rec); !ri_end(i); ri_inc(i) )
{
// your code, using 'i->x' and 'i->y' as coordinates
}
ri_del(i); // delete iterator
\endcode
The pixels are explored 'column' by 'column', where we call
'column' a set of pixels with the same x value that are inside the
rectangle. The following is an schematic representation of a
rectangle, the 'column' being explored is marked by colons, and
the current pixel being explored is 'x,y'.
\verbatim
vx[1],vy[1]
* *
* *
* *
* ye
* : *
vx[0],vy[0] : *
* : *
* x,y *
* : *
* : vx[2],vy[2]
* : *
y ys *
^ * *
| * *
| * *
+---> x vx[3],vy[3]
\endverbatim
The first 'column' to be explored is the one with the smaller x
value. Each 'column' is explored starting from the pixel of the
'column' (inside the rectangle) with the smaller y value.
The four corners of the rectangle are stored in order that rotates
around the corners at the arrays 'vx[]' and 'vy[]'. The first
point is always the one with smaller x value.
'x' and 'y' are the coordinates of the pixel being explored. 'ys'
and 'ye' are the start and end values of the current column being
explored. So, 'ys' < 'ye'.
*/
typedef struct
{
double vx[4]; /* rectangle's corner X coordinates in circular order */
double vy[4]; /* rectangle's corner Y coordinates in circular order */
double ys,ye; /* start and end Y values of current 'column' */
int x,y; /* coordinates of currently explored pixel */
} rect_iter;
/*----------------------------------------------------------------------------*/
/** Interpolate y value corresponding to 'x' value given, in
the line 'x1,y1' to 'x2,y2'; if 'x1=x2' return the smaller
of 'y1' and 'y2'.
The following restrictions are required:
- x1 <= x2
- x1 <= x
- x <= x2
*/
static double inter_low(double x, double x1, double y1, double x2, double y2)
{
/* check parameters */
if( x1 > x2 || x < x1 || x > x2 )
error("inter_low: unsuitable input, 'x1>x2' or 'x<x1' or 'x>x2'.");
/* interpolation */
if( double_equal(x1,x2) && y1<y2 ) return y1;
if( double_equal(x1,x2) && y1>y2 ) return y2;
return y1 + (x-x1) * (y2-y1) / (x2-x1);
}
/*----------------------------------------------------------------------------*/
/** Interpolate y value corresponding to 'x' value given, in
the line 'x1,y1' to 'x2,y2'; if 'x1=x2' return the larger
of 'y1' and 'y2'.
The following restrictions are required:
- x1 <= x2
- x1 <= x
- x <= x2
*/
static double inter_hi(double x, double x1, double y1, double x2, double y2)
{
/* check parameters */
if( x1 > x2 || x < x1 || x > x2 )
error("inter_hi: unsuitable input, 'x1>x2' or 'x<x1' or 'x>x2'.");
/* interpolation */
if( double_equal(x1,x2) && y1<y2 ) return y2;
if( double_equal(x1,x2) && y1>y2 ) return y1;
return y1 + (x-x1) * (y2-y1) / (x2-x1);
}
/*----------------------------------------------------------------------------*/
/** Free memory used by a rectangle iterator.
*/
static void ri_del(rect_iter * iter)
{
if( iter == NULL ) error("ri_del: NULL iterator.");
free( (void *) iter );
}
/*----------------------------------------------------------------------------*/
/** Check if the iterator finished the full iteration.
See details in \ref rect_iter
*/
static int ri_end(rect_iter * i)
{
/* check input */
if( i == NULL ) error("ri_end: NULL iterator.");
/* if the current x value is larger than the larger
x value in the rectangle (vx[2]), we know the full
exploration of the rectangle is finished. */
return (double)(i->x) > i->vx[2];
}
/*----------------------------------------------------------------------------*/
/** Increment a rectangle iterator.
See details in \ref rect_iter
*/
static void ri_inc(rect_iter * i)
{
/* check input */
if( i == NULL ) error("ri_inc: NULL iterator.");
/* if not at end of exploration,
increase y value for next pixel in the 'column' */
if( !ri_end(i) ) i->y++;
/* if the end of the current 'column' is reached,
and it is not the end of exploration,
advance to the next 'column' */
while( (double) (i->y) > i->ye && !ri_end(i) )
{
/* increase x, next 'column' */
i->x++;
/* if end of exploration, return */
if( ri_end(i) ) return;
/* update lower y limit (start) for the new 'column'.
We need to interpolate the y value that corresponds to the
lower side of the rectangle. The first thing is to decide if
the corresponding side is
vx[0],vy[0] to vx[3],vy[3] or
vx[3],vy[3] to vx[2],vy[2]
Then, the side is interpolated for the x value of the
'column'. But, if the side is vertical (as it could happen if
the rectangle is vertical and we are dealing with the first
or last 'columns') then we pick the lower value of the side
by using 'inter_low'.
*/
if( (double) i->x < i->vx[3] )
i->ys = inter_low((double)i->x,i->vx[0],i->vy[0],i->vx[3],i->vy[3]);
else
i->ys = inter_low((double)i->x,i->vx[3],i->vy[3],i->vx[2],i->vy[2]);
/* update upper y limit (end) for the new 'column'.
We need to interpolate the y value that corresponds to the
upper side of the rectangle. The first thing is to decide if
the corresponding side is
vx[0],vy[0] to vx[1],vy[1] or
vx[1],vy[1] to vx[2],vy[2]
Then, the side is interpolated for the x value of the
'column'. But, if the side is vertical (as it could happen if
the rectangle is vertical and we are dealing with the first
or last 'columns') then we pick the lower value of the side
by using 'inter_low'.
*/
if( (double)i->x < i->vx[1] )
i->ye = inter_hi((double)i->x,i->vx[0],i->vy[0],i->vx[1],i->vy[1]);
else
i->ye = inter_hi((double)i->x,i->vx[1],i->vy[1],i->vx[2],i->vy[2]);
/* new y */
i->y = (int) ceil(i->ys);
}
}
/*----------------------------------------------------------------------------*/
/** Create and initialize a rectangle iterator.
See details in \ref rect_iter
*/
static rect_iter * ri_ini(struct rect * r)
{
double vx[4],vy[4];
int n,offset;
rect_iter * i;
/* check parameters */
if( r == NULL ) error("ri_ini: invalid rectangle.");
/* get memory */
i = (rect_iter *) malloc(sizeof(rect_iter));
if( i == NULL ) error("ri_ini: Not enough memory.");
/* build list of rectangle corners ordered
in a circular way around the rectangle */
vx[0] = r->x1 - r->dy * r->width / 2.0;
vy[0] = r->y1 + r->dx * r->width / 2.0;
vx[1] = r->x2 - r->dy * r->width / 2.0;
vy[1] = r->y2 + r->dx * r->width / 2.0;
vx[2] = r->x2 + r->dy * r->width / 2.0;
vy[2] = r->y2 - r->dx * r->width / 2.0;
vx[3] = r->x1 + r->dy * r->width / 2.0;
vy[3] = r->y1 - r->dx * r->width / 2.0;
/* compute rotation of index of corners needed so that the first
point has the smaller x.
if one side is vertical, thus two corners have the same smaller x
value, the one with the largest y value is selected as the first.
*/
if( r->x1 < r->x2 && r->y1 <= r->y2 ) offset = 0;
else if( r->x1 >= r->x2 && r->y1 < r->y2 ) offset = 1;
else if( r->x1 > r->x2 && r->y1 >= r->y2 ) offset = 2;
else offset = 3;
/* apply rotation of index. */
for(n=0; n<4; n++)
{
i->vx[n] = vx[(offset+n)%4];
i->vy[n] = vy[(offset+n)%4];
}
/* Set a initial condition.
The values are set to values that will cause 'ri_inc' (that will
be called immediately) to initialize correctly the first 'column'
and compute the limits 'ys' and 'ye'.
'y' is set to the integer value of vy[0], the starting corner.
'ys' and 'ye' are set to very small values, so 'ri_inc' will
notice that it needs to start a new 'column'.
The smaller integer coordinate inside of the rectangle is
'ceil(vx[0])'. The current 'x' value is set to that value minus
one, so 'ri_inc' (that will increase x by one) will advance to
the first 'column'.
*/
i->x = (int) ceil(i->vx[0]) - 1;
i->y = (int) ceil(i->vy[0]);
i->ys = i->ye = -DBL_MAX;
/* advance to the first pixel */
ri_inc(i);
return i;
}
/*----------------------------------------------------------------------------*/
/** Compute a rectangle's NFA value.
*/
static double rect_nfa(struct rect * rec, image_double angles, double logNT)
{
rect_iter * i;
int pts = 0;
int alg = 0;
/* check parameters */
if( rec == NULL ) error("rect_nfa: invalid rectangle.");
if( angles == NULL ) error("rect_nfa: invalid 'angles'.");
/* compute the total number of pixels and of aligned points in 'rec' */
for(i=ri_ini(rec); !ri_end(i); ri_inc(i)) /* rectangle iterator */
if( i->x >= 0 && i->y >= 0 &&
i->x < (int) angles->xsize && i->y < (int) angles->ysize )
{
++pts; /* total number of pixels counter */
if( isaligned(i->x, i->y, angles, rec->theta, rec->prec) )
++alg; /* aligned points counter */
}
ri_del(i); /* delete iterator */
return nfa(pts,alg,rec->p,logNT); /* compute NFA value */
}
/*----------------------------------------------------------------------------*/
/*---------------------------------- Regions ---------------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** Compute region's angle as the principal inertia axis of the region.
The following is the region inertia matrix A:
@f[
A = \left(\begin{array}{cc}
Ixx & Ixy \\
Ixy & Iyy \\
\end{array}\right)
@f]
where
Ixx = sum_i G(i).(y_i - cx)^2
Iyy = sum_i G(i).(x_i - cy)^2
Ixy = - sum_i G(i).(x_i - cx).(y_i - cy)
and
- G(i) is the gradient norm at pixel i, used as pixel's weight.
- x_i and y_i are the coordinates of pixel i.
- cx and cy are the coordinates of the center of th region.
lambda1 and lambda2 are the eigenvalues of matrix A,
with lambda1 >= lambda2. They are found by solving the
characteristic polynomial:
det( lambda I - A) = 0
that gives:
lambda1 = ( Ixx + Iyy + sqrt( (Ixx-Iyy)^2 + 4.0*Ixy*Ixy) ) / 2
lambda2 = ( Ixx + Iyy - sqrt( (Ixx-Iyy)^2 + 4.0*Ixy*Ixy) ) / 2
To get the line segment direction we want to get the angle the
eigenvector assotiated to the smaller eigenvalue. We have to solve
a,b in:
a.Ixx + b.Ixy = a.lambda2
a.Ixy + b.Iyy = b.lambda2
We want the angle theta = atan(b/a). It can be computed with
any of the two equations:
theta = atan( (lambda2-Ixx) / Ixy )
or
theta = atan( Ixy / (lambda2-Iyy) )
When |Ixx| > |Iyy| we use the first, otherwise the second (just to
get better numeric precision).
*/
static double get_theta( struct point * reg, int reg_size, double x, double y,
image_double modgrad, double reg_angle, double prec )
{
double lambda,theta,weight;
double Ixx = 0.0;
double Iyy = 0.0;
double Ixy = 0.0;
int i;
/* check parameters */
if( reg == NULL ) error("get_theta: invalid region.");
if( reg_size <= 1 ) error("get_theta: region size <= 1.");
if( modgrad == NULL || modgrad->data == NULL )
error("get_theta: invalid 'modgrad'.");
if( prec < 0.0 ) error("get_theta: 'prec' must be positive.");
/* compute inertia matrix */
for(i=0; i<reg_size; i++)
{
weight = modgrad->data[ reg[i].x + reg[i].y * modgrad->xsize ];
Ixx += ( (double) reg[i].y - y ) * ( (double) reg[i].y - y ) * weight;
Iyy += ( (double) reg[i].x - x ) * ( (double) reg[i].x - x ) * weight;
Ixy -= ( (double) reg[i].x - x ) * ( (double) reg[i].y - y ) * weight;
}
if( double_equal(Ixx,0.0) && double_equal(Iyy,0.0) && double_equal(Ixy,0.0) )
error("get_theta: null inertia matrix.");
/* compute smallest eigenvalue */
lambda = 0.5 * ( Ixx + Iyy - sqrt( (Ixx-Iyy)*(Ixx-Iyy) + 4.0*Ixy*Ixy ) );
/* compute angle */
theta = fabs(Ixx)>fabs(Iyy) ? atan2(lambda-Ixx,Ixy) : atan2(Ixy,lambda-Iyy);
/* The previous procedure don't cares about orientation,
so it could be wrong by 180 degrees. Here is corrected if necessary. */
if( angle_diff(theta,reg_angle) > prec ) theta += M_PI;
return theta;
}
/*----------------------------------------------------------------------------*/
/** Computes a rectangle that covers a region of points.
*/
static void region2rect( struct point * reg, int reg_size,
image_double modgrad, double reg_angle,
double prec, double p, struct rect * rec )
{
double x,y,dx,dy,l,w,theta,weight,sum,l_min,l_max,w_min,w_max;
int i;
/* check parameters */
if( reg == NULL ) error("region2rect: invalid region.");
if( reg_size <= 1 ) error("region2rect: region size <= 1.");
if( modgrad == NULL || modgrad->data == NULL )
error("region2rect: invalid image 'modgrad'.");
if( rec == NULL ) error("region2rect: invalid 'rec'.");
/* center of the region:
It is computed as the weighted sum of the coordinates
of all the pixels in the region. The norm of the gradient
is used as the weight of a pixel. The sum is as follows:
cx = \sum_i G(i).x_i
cy = \sum_i G(i).y_i
where G(i) is the norm of the gradient of pixel i
and x_i,y_i are its coordinates.
*/
x = y = sum = 0.0;
for(i=0; i<reg_size; i++)
{
weight = modgrad->data[ reg[i].x + reg[i].y * modgrad->xsize ];
x += (double) reg[i].x * weight;
y += (double) reg[i].y * weight;
sum += weight;
}
if( sum <= 0.0 ) error("region2rect: weights sum equal to zero.");
x /= sum;
y /= sum;
/* theta */
theta = get_theta(reg,reg_size,x,y,modgrad,reg_angle,prec);
/* length and width:
'l' and 'w' are computed as the distance from the center of the
region to pixel i, projected along the rectangle axis (dx,dy) and
to the orthogonal axis (-dy,dx), respectively.
The length of the rectangle goes from l_min to l_max, where l_min
and l_max are the minimum and maximum values of l in the region.
Analogously, the width is selected from w_min to w_max, where
w_min and w_max are the minimum and maximum of w for the pixels
in the region.
*/
dx = cos(theta);
dy = sin(theta);
l_min = l_max = w_min = w_max = 0.0;
for(i=0; i<reg_size; i++)
{
l = ( (double) reg[i].x - x) * dx + ( (double) reg[i].y - y) * dy;
w = -( (double) reg[i].x - x) * dy + ( (double) reg[i].y - y) * dx;
if( l > l_max ) l_max = l;
if( l < l_min ) l_min = l;
if( w > w_max ) w_max = w;
if( w < w_min ) w_min = w;
}
/* store values */
rec->x1 = x + l_min * dx;
rec->y1 = y + l_min * dy;
rec->x2 = x + l_max * dx;
rec->y2 = y + l_max * dy;
rec->width = w_max - w_min;
rec->x = x;
rec->y = y;
rec->theta = theta;
rec->dx = dx;
rec->dy = dy;
rec->prec = prec;
rec->p = p;
/* we impose a minimal width of one pixel
A sharp horizontal or vertical step would produce a perfectly
horizontal or vertical region. The width computed would be
zero. But that corresponds to a one pixels width transition in
the image.
*/
if( rec->width < 1.0 ) rec->width = 1.0;
}
/*----------------------------------------------------------------------------*/
/** Build a region of pixels that share the same angle, up to a
tolerance 'prec', starting at point (x,y).
*/
static void region_grow( int x, int y, image_double angles, struct point * reg,
int * reg_size, double * reg_angle, image_char used,
double prec )
{
double sumdx,sumdy;
int xx,yy,i;
/* check parameters */
if( x < 0 || y < 0 || x >= (int) angles->xsize || y >= (int) angles->ysize )
error("region_grow: (x,y) out of the image.");
if( angles == NULL || angles->data == NULL )
error("region_grow: invalid image 'angles'.");
if( reg == NULL ) error("region_grow: invalid 'reg'.");
if( reg_size == NULL ) error("region_grow: invalid pointer 'reg_size'.");
if( reg_angle == NULL ) error("region_grow: invalid pointer 'reg_angle'.");
if( used == NULL || used->data == NULL )
error("region_grow: invalid image 'used'.");
/* first point of the region */
*reg_size = 1;
reg[0].x = x;
reg[0].y = y;
*reg_angle = angles->data[x+y*angles->xsize]; /* region's angle */
sumdx = cos(*reg_angle);
sumdy = sin(*reg_angle);
used->data[x+y*used->xsize] = USED;
/* try neighbors as new region points */
for(i=0; i<*reg_size; i++)
for(xx=reg[i].x-1; xx<=reg[i].x+1; xx++)
for(yy=reg[i].y-1; yy<=reg[i].y+1; yy++)
if( xx>=0 && yy>=0 && xx<(int)used->xsize && yy<(int)used->ysize &&
used->data[xx+yy*used->xsize] != USED &&
isaligned(xx,yy,angles,*reg_angle,prec) )
{
/* add point */
used->data[xx+yy*used->xsize] = USED;
reg[*reg_size].x = xx;
reg[*reg_size].y = yy;
++(*reg_size);
/* update region's angle */
sumdx += cos( angles->data[xx+yy*angles->xsize] );
sumdy += sin( angles->data[xx+yy*angles->xsize] );
*reg_angle = atan2(sumdy,sumdx);
}
}
/*----------------------------------------------------------------------------*/
/** Try some rectangles variations to improve NFA value. Only if the
rectangle is not meaningful (i.e., log_nfa <= eps).
*/
static double rect_improve( struct rect * rec, image_double angles,
double logNT, double eps )
{
struct rect r;
double log_nfa,log_nfa_new;
double delta = 0.5;
double delta_2 = delta / 2.0;
int n;
log_nfa = rect_nfa(rec,angles,logNT);
if( log_nfa > eps ) return log_nfa;
/* try finer precisions */
rect_copy(rec,&r);
for(n=0; n<5; n++)
{
r.p /= 2.0;
r.prec = r.p * M_PI;
log_nfa_new = rect_nfa(&r,angles,logNT);
if( log_nfa_new > log_nfa )
{
log_nfa = log_nfa_new;
rect_copy(&r,rec);
}
}
if( log_nfa > eps ) return log_nfa;
/* try to reduce width */
rect_copy(rec,&r);
for(n=0; n<5; n++)
{
if( (r.width - delta) >= 0.5 )
{
r.width -= delta;
log_nfa_new = rect_nfa(&r,angles,logNT);
if( log_nfa_new > log_nfa )
{
rect_copy(&r,rec);
log_nfa = log_nfa_new;
}
}
}
if( log_nfa > eps ) return log_nfa;
/* try to reduce one side of the rectangle */
rect_copy(rec,&r);
for(n=0; n<5; n++)
{
if( (r.width - delta) >= 0.5 )
{
r.x1 += -r.dy * delta_2;
r.y1 += r.dx * delta_2;
r.x2 += -r.dy * delta_2;
r.y2 += r.dx * delta_2;
r.width -= delta;
log_nfa_new = rect_nfa(&r,angles,logNT);
if( log_nfa_new > log_nfa )
{
rect_copy(&r,rec);
log_nfa = log_nfa_new;
}
}
}
if( log_nfa > eps ) return log_nfa;
/* try to reduce the other side of the rectangle */
rect_copy(rec,&r);
for(n=0; n<5; n++)
{
if( (r.width - delta) >= 0.5 )
{
r.x1 -= -r.dy * delta_2;
r.y1 -= r.dx * delta_2;
r.x2 -= -r.dy * delta_2;
r.y2 -= r.dx * delta_2;
r.width -= delta;
log_nfa_new = rect_nfa(&r,angles,logNT);
if( log_nfa_new > log_nfa )
{
rect_copy(&r,rec);
log_nfa = log_nfa_new;
}
}
}
if( log_nfa > eps ) return log_nfa;
/* try even finer precisions */
rect_copy(rec,&r);
for(n=0; n<5; n++)
{
r.p /= 2.0;
r.prec = r.p * M_PI;
log_nfa_new = rect_nfa(&r,angles,logNT);
if( log_nfa_new > log_nfa )
{
log_nfa = log_nfa_new;
rect_copy(&r,rec);
}
}
return log_nfa;
}
/*----------------------------------------------------------------------------*/
/** Reduce the region size, by elimination the points far from the
starting point, until that leads to rectangle with the right
density of region points or to discard the region if too small.
*/
static int reduce_region_radius( struct point * reg, int * reg_size,
image_double modgrad, double reg_angle,
double prec, double p, struct rect * rec,
image_char used, image_double angles,
double density_th )
{
double density,rad1,rad2,rad,xc,yc;
int i;
/* check parameters */
if( reg == NULL ) error("reduce_region_radius: invalid pointer 'reg'.");
if( reg_size == NULL )
error("reduce_region_radius: invalid pointer 'reg_size'.");
if( prec < 0.0 ) error("reduce_region_radius: 'prec' must be positive.");
if( rec == NULL ) error("reduce_region_radius: invalid pointer 'rec'.");
if( used == NULL || used->data == NULL )
error("reduce_region_radius: invalid image 'used'.");
if( angles == NULL || angles->data == NULL )
error("reduce_region_radius: invalid image 'angles'.");
/* compute region points density */
density = (double) *reg_size /
( dist(rec->x1,rec->y1,rec->x2,rec->y2) * rec->width );
/* if the density criterion is satisfied there is nothing to do */
if( density >= density_th ) return TRUE;
/* compute region's radius */
xc = (double) reg[0].x;
yc = (double) reg[0].y;
rad1 = dist( xc, yc, rec->x1, rec->y1 );
rad2 = dist( xc, yc, rec->x2, rec->y2 );
rad = rad1 > rad2 ? rad1 : rad2;
/* while the density criterion is not satisfied, remove farther pixels */
while( density < density_th )
{
rad *= 0.75; /* reduce region's radius to 75% of its value */
/* remove points from the region and update 'used' map */
for(i=0; i<*reg_size; i++)
if( dist( xc, yc, (double) reg[i].x, (double) reg[i].y ) > rad )
{
/* point not kept, mark it as NOTUSED */
used->data[ reg[i].x + reg[i].y * used->xsize ] = NOTUSED;
/* remove point from the region */
reg[i].x = reg[*reg_size-1].x; /* if i==*reg_size-1 copy itself */
reg[i].y = reg[*reg_size-1].y;
--(*reg_size);
--i; /* to avoid skipping one point */
}
/* reject if the region is too small.
2 is the minimal region size for 'region2rect' to work. */
if( *reg_size < 2 ) return FALSE;
/* re-compute rectangle */
region2rect(reg,*reg_size,modgrad,reg_angle,prec,p,rec);
/* re-compute region points density */
density = (double) *reg_size /
( dist(rec->x1,rec->y1,rec->x2,rec->y2) * rec->width );
}
/* if this point is reached, the density criterion is satisfied */
return TRUE;
}
/*----------------------------------------------------------------------------*/
/** Refine a rectangle.
For that, an estimation of the angle tolerance is performed by the
standard deviation of the angle at points near the region's
starting point. Then, a new region is grown starting from the same
point, but using the estimated angle tolerance. If this fails to
produce a rectangle with the right density of region points,
'reduce_region_radius' is called to try to satisfy this condition.
*/
static int refine( struct point * reg, int * reg_size, image_double modgrad,
double reg_angle, double prec, double p, struct rect * rec,
image_char used, image_double angles, double density_th )
{
double angle,ang_d,mean_angle,tau,density,xc,yc,ang_c,sum,s_sum;
int i,n;
/* check parameters */
if( reg == NULL ) error("refine: invalid pointer 'reg'.");
if( reg_size == NULL ) error("refine: invalid pointer 'reg_size'.");
if( prec < 0.0 ) error("refine: 'prec' must be positive.");
if( rec == NULL ) error("refine: invalid pointer 'rec'.");
if( used == NULL || used->data == NULL )
error("refine: invalid image 'used'.");
if( angles == NULL || angles->data == NULL )
error("refine: invalid image 'angles'.");
/* compute region points density */
density = (double) *reg_size /
( dist(rec->x1,rec->y1,rec->x2,rec->y2) * rec->width );
/* if the density criterion is satisfied there is nothing to do */
if( density >= density_th ) return TRUE;
/*------ First try: reduce angle tolerance ------*/
/* compute the new mean angle and tolerance */
xc = (double) reg[0].x;
yc = (double) reg[0].y;
ang_c = angles->data[ reg[0].x + reg[0].y * angles->xsize ];
sum = s_sum = 0.0;
n = 0;
for(i=0; i<*reg_size; i++)
{
used->data[ reg[i].x + reg[i].y * used->xsize ] = NOTUSED;
if( dist( xc, yc, (double) reg[i].x, (double) reg[i].y ) < rec->width )
{
angle = angles->data[ reg[i].x + reg[i].y * angles->xsize ];
ang_d = angle_diff_signed(angle,ang_c);
sum += ang_d;
s_sum += ang_d * ang_d;
++n;
}
}
mean_angle = sum / (double) n;
tau = 2.0 * sqrt( (s_sum - 2.0 * mean_angle * sum) / (double) n
+ mean_angle*mean_angle ); /* 2 * standard deviation */
/* find a new region from the same starting point and new angle tolerance */
region_grow(reg[0].x,reg[0].y,angles,reg,reg_size,®_angle,used,tau);
/* if the region is too small, reject */
if( *reg_size < 2 ) return FALSE;
/* re-compute rectangle */
region2rect(reg,*reg_size,modgrad,reg_angle,prec,p,rec);
/* re-compute region points density */
density = (double) *reg_size /
( dist(rec->x1,rec->y1,rec->x2,rec->y2) * rec->width );
/*------ Second try: reduce region radius ------*/
if( density < density_th )
return reduce_region_radius( reg, reg_size, modgrad, reg_angle, prec, p,
rec, used, angles, density_th );
/* if this point is reached, the density criterion is satisfied */
return TRUE;
}
/*----------------------------------------------------------------------------*/
/*-------------------------- Line Segment Detector ---------------------------*/
/*----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------*/
/** LSD full interface.
*/
ntuple_list LineSegmentDetection( image_double image, double scale,
double sigma_scale, double quant,
double ang_th, double eps, double density_th,
int n_bins, double max_grad,
image_int * region )
{
ntuple_list out = new_ntuple_list(5);
image_double scaled_image,angles,modgrad;
image_char used;
struct coorlist * list_p;
void * mem_p;
struct rect rec;
struct point * reg;
int reg_size,min_reg_size,i;
unsigned int xsize,ysize;
double rho,reg_angle,prec,p,log_nfa,logNT;
int ls_count = 0; /* line segments are numbered 1,2,3,... */
/* check parameters */
if( image==NULL || image->data==NULL || image->xsize==0 || image->ysize==0 )
error("invalid image input.");
if( scale <= 0.0 ) error("'scale' value must be positive.");
if( sigma_scale <= 0.0 ) error("'sigma_scale' value must be positive.");
if( quant < 0.0 ) error("'quant' value must be positive.");
if( ang_th <= 0.0 || ang_th >= 180.0 )
error("'ang_th' value must be in the range (0,180).");
if( density_th < 0.0 || density_th > 1.0 )
error("'density_th' value must be in the range [0,1].");
if( n_bins <= 0 ) error("'n_bins' value must be positive.");
if( max_grad <= 0.0 ) error("'max_grad' value must be positive.");
/* angle tolerance */
prec = M_PI * ang_th / 180.0;
p = ang_th / 180.0;
rho = quant / sin(prec); /* gradient magnitude threshold */
/* scale image (if necessary) and compute angle at each pixel */
if( scale != 1.0 )
{
scaled_image = gaussian_sampler( image, scale, sigma_scale );
angles = ll_angle( scaled_image, rho, &list_p, &mem_p,
&modgrad, (unsigned int) n_bins, max_grad );
free_image_double(scaled_image);
}
else
angles = ll_angle( image, rho, &list_p, &mem_p, &modgrad,
(unsigned int) n_bins, max_grad );
xsize = angles->xsize;
ysize = angles->ysize;
logNT = 5.0 * ( log10( (double) xsize ) + log10( (double) ysize ) ) / 2.0;
min_reg_size = (int) (-logNT/log10(p)); /* minimal number of points in region
that can give a meaningful event */
/* initialize some structures */
if( region != NULL ) /* image to output pixel region number, if asked */
*region = new_image_int_ini(angles->xsize,angles->ysize,0);
used = new_image_char_ini(xsize,ysize,NOTUSED);
reg = (struct point *) calloc( (size_t) (xsize*ysize), sizeof(struct point) );
if( reg == NULL ) error("not enough memory!");
/* search for line segments */
for(; list_p != NULL; list_p = list_p->next )
if( used->data[ list_p->x + list_p->y * used->xsize ] == NOTUSED &&
angles->data[ list_p->x + list_p->y * angles->xsize ] != NOTDEF )
/* there is no risk of double comparison problems here
because we are only interested in the exact NOTDEF value */
{
/* find the region of connected point and ~equal angle */
region_grow( list_p->x, list_p->y, angles, reg, ®_size,
®_angle, used, prec );
/* reject small regions */
if( reg_size < min_reg_size ) continue;
/* construct rectangular approximation for the region */
region2rect(reg,reg_size,modgrad,reg_angle,prec,p,&rec);
/* Check if the rectangle exceeds the minimal density of
region points. If not, try to improve the region.
The rectangle will be rejected if the final one does
not fulfill the minimal density condition.
This is an addition to the original LSD algorithm published in
"LSD: A Fast Line Segment Detector with a False Detection Control"
by R. Grompone von Gioi, J. Jakubowicz, J.M. Morel, and G. Randall.
The original algorithm is obtained with density_th = 0.0.
*/
if( !refine( reg, ®_size, modgrad, reg_angle,
prec, p, &rec, used, angles, density_th ) ) continue;
/* compute NFA value */
log_nfa = rect_improve(&rec,angles,logNT,eps);
if( log_nfa <= eps ) continue;
/* A New Line Segment was found! */
++ls_count; /* increase line segment counter */
/*
The gradient was computed with a 2x2 mask, its value corresponds to
points with an offset of (0.5,0.5), that should be added to output.
The coordinates origin is at the center of pixel (0,0).
*/
rec.x1 += 0.5; rec.y1 += 0.5;
rec.x2 += 0.5; rec.y2 += 0.5;
/* scale the result values if a subsampling was performed */
if( scale != 1.0 )
{
rec.x1 /= scale; rec.y1 /= scale;
rec.x2 /= scale; rec.y2 /= scale;
rec.width /= scale;
}
/* add line segment found to output */
add_5tuple(out, rec.x1, rec.y1, rec.x2, rec.y2, rec.width);
/* add region number to 'region' image if needed */
if( region != NULL )
for(i=0; i<reg_size; i++)
(*region)->data[reg[i].x+reg[i].y*(*region)->xsize] = ls_count;
}
/* free memory */
free_image_double(angles);
free_image_double(modgrad);
free_image_char(used);
free( (void *) reg );
free( (void *) mem_p );
return out;
}
/*----------------------------------------------------------------------------*/
/** LSD Simple Interface with Scale.
*/
ntuple_list lsd_scale(image_double image, double scale)
{
/* LSD parameters */
double sigma_scale = 0.6; /* Sigma for Gaussian filter is computed as
sigma = sigma_scale/scale. */
double quant = 2.0; /* Bound to the quantization error on the
gradient norm. */
double ang_th = 22.5; /* Gradient angle tolerance in degrees. */
double eps = 0.0; /* Detection threshold, -log10(NFA). */
double density_th = 0.7; /* Minimal density of region points in rectangle. */
int n_bins = 1024; /* Number of bins in pseudo-ordering of gradient
modulus. */
double max_grad = 255.0; /* Gradient modulus in the highest bin. The
default value corresponds to the highest
gradient modulus on images with gray
levels in [0,255]. */
return LineSegmentDetection( image, scale, sigma_scale, quant, ang_th, eps,
density_th, n_bins, max_grad, NULL );
}
/*----------------------------------------------------------------------------*/
/** LSD Simple Interface.
*/
ntuple_list lsd(image_double image)
{
/* LSD parameters */
double scale = 0.8; /* Scale the image by Gaussian filter to 'scale'. */
return lsd_scale(image,scale);
}
/*----------------------------------------------------------------------------*/
| 34.797122 | 80 | 0.52991 | [
"vector"
] |
329651b4c9c1df7323d03a2b0e536a976b44cecf | 1,169 | h | C | net/third_party/http2/platform/api/http2_reconstruct_object.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | net/third_party/http2/platform/api/http2_reconstruct_object.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | net/third_party/http2/platform/api/http2_reconstruct_object.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_THIRD_PARTY_HTTP2_PLATFORM_API_HTTP2_RECONSTRUCT_OBJECT_H_
#define NET_THIRD_PARTY_HTTP2_PLATFORM_API_HTTP2_RECONSTRUCT_OBJECT_H_
#include <utility>
#include "net/third_party/http2/platform/impl/http2_reconstruct_object_impl.h"
namespace http2 {
namespace test {
class RandomBase;
// Reconstruct an object so that it is initialized as when it was first
// constructed. Runs the destructor to handle objects that might own resources,
// and runs the constructor with the provided arguments, if any.
template <class T, class... Args>
void Http2ReconstructObject(T* ptr, RandomBase* rng, Args&&... args) {
Http2ReconstructObjectImpl(ptr, rng, std::forward<Args>(args)...);
}
// This version applies default-initialization to the object.
template <class T>
void Http2DefaultReconstructObject(T* ptr, RandomBase* rng) {
Http2DefaultReconstructObjectImpl(ptr, rng);
}
} // namespace test
} // namespace http2
#endif // NET_THIRD_PARTY_HTTP2_PLATFORM_API_HTTP2_RECONSTRUCT_OBJECT_H_
| 33.4 | 79 | 0.79213 | [
"object"
] |
32975ce1451cb0a810292af4a8def1a79187357a | 10,833 | c | C | implementations/c/lib/key_agreement/xx/xx_responder.c | hollyfeld/ockam | 10a618b60b5b913821bfa8df3ad9693a70913ace | [
"Apache-2.0"
] | null | null | null | implementations/c/lib/key_agreement/xx/xx_responder.c | hollyfeld/ockam | 10a618b60b5b913821bfa8df3ad9693a70913ace | [
"Apache-2.0"
] | null | null | null | implementations/c/lib/key_agreement/xx/xx_responder.c | hollyfeld/ockam | 10a618b60b5b913821bfa8df3ad9693a70913ace | [
"Apache-2.0"
] | null | null | null | #include <string.h>
#include "ockam/error.h"
#include "key_agreement/key_impl.h"
#include "ockam/key_agreement.h"
#include "ockam/syslog.h"
#include "ockam/transport.h"
#include "ockam/vault.h"
#include "ockam/codec.h"
#include "xx_local.h"
#include <stdio.h>
extern ockam_memory_t* gp_ockam_key_memory;
ockam_error_t ockam_key_establish_responder_xx(void* p_context)
{
ockam_error_t error = OCKAM_ERROR_NONE;
ockam_error_t return_error = OCKAM_ERROR_NONE;
uint8_t message[MAX_XX_TRANSMIT_SIZE];
size_t message_length = 0;
key_establishment_xx xx;
ockam_xx_key_t* p_xx_key = (ockam_xx_key_t*) p_context;
ockam_memory_set(gp_ockam_key_memory, &xx, 0, sizeof(xx));
xx.vault = p_xx_key->p_vault;
/* Initialize handshake struct and generate initial static & ephemeral keys */
error = key_agreement_prologue_xx(&xx);
if (error) goto exit;
/* Msg 1 receive */
error = ockam_read(p_xx_key->p_reader, message, sizeof(message), &message_length);
if (error) goto exit;
/* Msg 1 process */
error = xx_responder_m1_process(&xx, message, message_length);
if (error) goto exit;
/* Msg 2 make */
error = xx_responder_m2_make(&xx, message, sizeof(message), &message_length);
if (error) goto exit;
/* Msg 2 send */
error = ockam_write(p_xx_key->p_writer, message, message_length);
if (error) goto exit;
/* Msg 3 receive */
error = ockam_read(p_xx_key->p_reader, message, sizeof(message), &message_length);
if (error) goto exit;
/* Msg 3 process */
error = xx_responder_m3_process(&xx, message, message_length);
if (error) goto exit;
/* Epilogue */
error = xx_responder_epilogue(&xx, p_xx_key);
if (error) goto exit;
exit:
if (error) log_error(error, __func__);
error = ockam_vault_secret_destroy(xx.vault, &xx.s_secret);
if (error) {
log_error(error, __func__);
return_error = error;
}
error = ockam_vault_secret_destroy(xx.vault, &xx.e_secret);
if (error) {
log_error(error, __func__);
return_error = error;
}
error = ockam_vault_secret_destroy(xx.vault, &xx.k_secret);
if (error) {
log_error(error, __func__);
return_error = error;
}
error = ockam_vault_secret_destroy(xx.vault, &xx.ck_secret);
if (error) {
log_error(error, __func__);
return_error = error;
}
return return_error;
}
/*
********************************************************************************************************
* LOCAL FUNCTIONS *
********************************************************************************************************
*/
ockam_error_t xx_responder_m1_process(key_establishment_xx* p_h, uint8_t* p_m1, size_t m1_size)
{
ockam_error_t error = TRANSPORT_ERROR_NONE;
uint16_t offset = 0;
uint8_t key[KEY_SIZE];
uint32_t key_bytes;
// Read 32 bytes from the incoming message buffer
// parse it as a public key, set it to re
// h = SHA256(h || re)
ockam_memory_copy(gp_ockam_key_memory, p_h->re, p_m1, KEY_SIZE);
offset += KEY_SIZE;
mix_hash(p_h, p_h->re, KEY_SIZE);
// h = SHA256( h || payload )
mix_hash(p_h, NULL, 0);
if (offset != m1_size) {
error = KEYAGREEMENT_ERROR_FAIL;
log_error(error, "handshake failed in responder_m1_process (size mismatch)");
}
exit:
return error;
}
ockam_error_t xx_responder_m2_make(key_establishment_xx* xx, uint8_t* p_msg, size_t msg_size, size_t* p_bytesWritten)
{
ockam_error_t error = TRANSPORT_ERROR_NONE;
uint8_t cipher_and_tag[MAX_XX_TRANSMIT_SIZE];
size_t cipher_and_tag_length = 0;
uint16_t offset = 0;
uint8_t vector[VECTOR_SIZE];
// 1. h = SHA256(h || e.PublicKey),
// Write e.PublicKey to outgoing message
// buffer, BigEndian
mix_hash(xx, xx->e, KEY_SIZE);
ockam_memory_copy(gp_ockam_key_memory, p_msg, xx->e, sizeof(xx->e));
offset += sizeof(xx->e);
// 2. ck, k = HKDF(ck, DH(e, re), 2)
// n = 0
error = hkdf_dh(xx, &xx->ck_secret, &xx->e_secret, xx->re, sizeof(xx->re), &xx->ck_secret, &xx->k_secret);
if (error) goto exit;
error = ockam_vault_secret_type_set(
xx->vault, &xx->k_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY); //!!Todo: remove these from everywhere
if (error) goto exit;
error = ockam_vault_secret_type_set(
xx->vault, &xx->ck_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY); //!!only do this before using for cryptography
if (error) goto exit;
xx->nonce = 0;
// 3. c = ENCRYPT(k, n++, h, s.PublicKey)
// h = SHA256(h || c),
// Write c to outgoing message buffer
ockam_memory_set(gp_ockam_key_memory, cipher_and_tag, 0, sizeof(cipher_and_tag));
make_vector(xx->nonce, vector);
error = ockam_vault_aead_aes_gcm_encrypt(xx->vault,
&xx->k_secret,
xx->nonce,
xx->h,
SHA256_SIZE,
xx->s,
KEY_SIZE,
cipher_and_tag,
KEY_SIZE + TAG_SIZE,
&cipher_and_tag_length);
if (error) goto exit;
xx->nonce += 1;
mix_hash(xx, cipher_and_tag, cipher_and_tag_length);
// Copy cypher text into send buffer
ockam_memory_copy(gp_ockam_key_memory, p_msg + offset, cipher_and_tag, cipher_and_tag_length);
offset += cipher_and_tag_length;
// 4. ck, k = HKDF(ck, DH(s, re), 2)
// n = 0
error = hkdf_dh(xx, &xx->ck_secret, &xx->s_secret, xx->re, sizeof(xx->re), &xx->ck_secret, &xx->k_secret);
if (error) goto exit;
error = ockam_vault_secret_type_set(xx->vault, &xx->k_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY);
if (error) goto exit;
error = ockam_vault_secret_type_set(xx->vault, &xx->ck_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY);
if (error) goto exit;
xx->nonce = 0;
// 5. c = ENCRYPT(k, n++, h, payload)
// h = SHA256(h || c),
// payload is empty
ockam_memory_set(gp_ockam_key_memory, cipher_and_tag, 0, sizeof(cipher_and_tag));
make_vector(xx->nonce, vector);
error = ockam_vault_aead_aes_gcm_encrypt(xx->vault,
&xx->k_secret,
xx->nonce,
xx->h,
sizeof(xx->h),
NULL,
0,
cipher_and_tag,
sizeof(cipher_and_tag),
&cipher_and_tag_length);
if (error) goto exit;
xx->nonce += 1;
ockam_memory_copy(gp_ockam_key_memory, p_msg + offset, cipher_and_tag, cipher_and_tag_length);
offset += cipher_and_tag_length;
mix_hash(xx, cipher_and_tag, cipher_and_tag_length);
// Done
*p_bytesWritten = offset;
exit:
if (error) log_error(error, __func__);
return error;
}
ockam_error_t xx_responder_m3_process(key_establishment_xx* xx, uint8_t* p_m3, size_t m3_size)
{
ockam_error_t error = TRANSPORT_ERROR_NONE;
uint8_t clear_text[MAX_XX_TRANSMIT_SIZE];
size_t clear_text_length = 0;
uint8_t tag[TAG_SIZE];
uint32_t offset = 0;
// 1. Read 48 bytes the incoming message buffer as c
// p = DECRYPT(k, n++, h, c)
// h = SHA256(h || c),
// parse p as a public key,
// set it to rs
ockam_memory_set(gp_ockam_key_memory, tag, 0, sizeof(tag));
ockam_memory_copy(gp_ockam_key_memory, tag, p_m3 + offset + KEY_SIZE, TAG_SIZE);
error = ockam_vault_aead_aes_gcm_decrypt(xx->vault,
&xx->k_secret,
xx->nonce,
xx->h,
sizeof(xx->h),
p_m3,
KEY_SIZE + TAG_SIZE,
clear_text,
sizeof(clear_text),
&clear_text_length);
if (error) goto exit;
ockam_memory_copy(gp_ockam_key_memory, xx->rs, clear_text, KEY_SIZE);
mix_hash(xx, p_m3 + offset, KEY_SIZE + TAG_SIZE);
offset += KEY_SIZE + TAG_SIZE;
// 2. ck, k = HKDF(ck, DH(e, rs), 2)
// n = 0
error = hkdf_dh(xx, &xx->ck_secret, &xx->e_secret, xx->rs, sizeof(xx->rs), &xx->ck_secret, &xx->k_secret);
if (error) goto exit;
error = ockam_vault_secret_type_set(xx->vault, &xx->k_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY);
if (error) goto exit;
error = ockam_vault_secret_type_set(xx->vault, &xx->ck_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY);
if (error) goto exit;
xx->nonce = 0;
// 3. Read remaining bytes of incoming message buffer as c
// p = DECRYPT(k, n++, h, c)
// h = SHA256(h || c),
// parse p as a payload,
// payload should be empty
ockam_memory_set(gp_ockam_key_memory, clear_text, 0, sizeof(clear_text));
error = ockam_vault_aead_aes_gcm_decrypt(xx->vault,
&xx->k_secret,
xx->nonce,
xx->h,
sizeof(xx->h),
p_m3 + offset,
TAG_SIZE,
clear_text,
sizeof(clear_text),
&clear_text_length);
if (error) goto exit;
xx->nonce += 1;
mix_hash(xx, p_m3 + offset, clear_text_length);
exit:
if (error) log_error(error, __func__);
return error;
}
ockam_error_t xx_responder_epilogue(key_establishment_xx* xx, ockam_xx_key_t* p_key)
{
ockam_error_t error = TRANSPORT_ERROR_NONE;
ockam_vault_secret_t secrets[2];
ockam_memory_set(gp_ockam_key_memory, secrets, 0, sizeof(secrets));
error = ockam_vault_hkdf_sha256(xx->vault, &xx->ck_secret, NULL, 2, &secrets[0]);
if (error) goto exit;
ockam_memory_copy(gp_ockam_key_memory, &p_key->encrypt_secret, &secrets[0], sizeof(secrets[0]));
ockam_memory_copy(gp_ockam_key_memory, &p_key->decrypt_secret, &secrets[1], sizeof(secrets[1]));
error = ockam_vault_secret_type_set(xx->vault, &p_key->encrypt_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY);
if (error) goto exit;
error = ockam_vault_secret_type_set(xx->vault, &p_key->decrypt_secret, OCKAM_VAULT_SECRET_TYPE_AES256_KEY);
if (error) goto exit;
p_key->encrypt_nonce = 0;
p_key->decrypt_nonce = 0;
exit:
if (error) log_error(error, __func__);
return error;
}
| 35.752475 | 117 | 0.586818 | [
"vector"
] |
d0cb4ff4ec5e38bd6c3b69d966cd4e6de67324c9 | 28,445 | h | C | aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/Origin.h | neil-b/aws-sdk-cpp | 1602b75abbca880b770c12788f6d2bac0c87176a | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/Origin.h | neil-b/aws-sdk-cpp | 1602b75abbca880b770c12788f6d2bac0c87176a | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-cloudfront/include/aws/cloudfront/model/Origin.h | neil-b/aws-sdk-cpp | 1602b75abbca880b770c12788f6d2bac0c87176a | [
"Apache-2.0"
] | 1 | 2020-11-04T03:18:11.000Z | 2020-11-04T03:18:11.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/cloudfront/CloudFront_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cloudfront/model/CustomHeaders.h>
#include <aws/cloudfront/model/S3OriginConfig.h>
#include <aws/cloudfront/model/CustomOriginConfig.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudFront
{
namespace Model
{
/**
* <p>An origin.</p> <p>An origin is the location where content is stored, and from
* which CloudFront gets content to serve to viewers. To specify an origin:</p>
* <ul> <li> <p>Use the <code>S3OriginConfig</code> type to specify an Amazon S3
* bucket that is <i> <b>not</b> </i> configured with static website hosting.</p>
* </li> <li> <p>Use the <code>CustomOriginConfig</code> type to specify various
* other kinds of content containers or HTTP servers, including:</p> <ul> <li>
* <p>An Amazon S3 bucket that is configured with static website hosting</p> </li>
* <li> <p>An Elastic Load Balancing load balancer</p> </li> <li> <p>An AWS
* Elemental MediaPackage origin</p> </li> <li> <p>An AWS Elemental MediaStore
* container</p> </li> <li> <p>Any other HTTP server, running on an Amazon EC2
* instance or any other kind of host</p> </li> </ul> </li> </ul> <p>For the
* current maximum number of origins that you can specify per distribution, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html#limits-web-distributions">General
* Quotas on Web Distributions</a> in the <i>Amazon CloudFront Developer Guide</i>
* (quotas were formerly referred to as limits).</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/Origin">AWS
* API Reference</a></p>
*/
class AWS_CLOUDFRONT_API Origin
{
public:
Origin();
Origin(const Aws::Utils::Xml::XmlNode& xmlNode);
Origin& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline const Aws::String& GetId() const{ return m_id; }
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline bool IdHasBeenSet() const { return m_idHasBeenSet; }
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; }
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); }
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); }
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline Origin& WithId(const Aws::String& value) { SetId(value); return *this;}
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline Origin& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}
/**
* <p>A unique identifier for the origin. This value must be unique within the
* distribution.</p> <p>Use this value to specify the <code>TargetOriginId</code>
* in a <code>CacheBehavior</code> or <code>DefaultCacheBehavior</code>.</p>
*/
inline Origin& WithId(const char* value) { SetId(value); return *this;}
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline const Aws::String& GetDomainName() const{ return m_domainName; }
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline bool DomainNameHasBeenSet() const { return m_domainNameHasBeenSet; }
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = std::move(value); }
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithDomainName(Aws::String&& value) { SetDomainName(std::move(value)); return *this;}
/**
* <p>The domain name for the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName">Origin
* Domain Name</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithDomainName(const char* value) { SetDomainName(value); return *this;}
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline const Aws::String& GetOriginPath() const{ return m_originPath; }
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline bool OriginPathHasBeenSet() const { return m_originPathHasBeenSet; }
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetOriginPath(const Aws::String& value) { m_originPathHasBeenSet = true; m_originPath = value; }
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetOriginPath(Aws::String&& value) { m_originPathHasBeenSet = true; m_originPath = std::move(value); }
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetOriginPath(const char* value) { m_originPathHasBeenSet = true; m_originPath.assign(value); }
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithOriginPath(const Aws::String& value) { SetOriginPath(value); return *this;}
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithOriginPath(Aws::String&& value) { SetOriginPath(std::move(value)); return *this;}
/**
* <p>An optional path that CloudFront appends to the origin domain name when
* CloudFront requests content from the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath">Origin
* Path</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithOriginPath(const char* value) { SetOriginPath(value); return *this;}
/**
* <p>A list of HTTP header names and values that CloudFront adds to requests it
* sends to the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html">Adding
* Custom Headers to Origin Requests</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p>
*/
inline const CustomHeaders& GetCustomHeaders() const{ return m_customHeaders; }
/**
* <p>A list of HTTP header names and values that CloudFront adds to requests it
* sends to the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html">Adding
* Custom Headers to Origin Requests</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p>
*/
inline bool CustomHeadersHasBeenSet() const { return m_customHeadersHasBeenSet; }
/**
* <p>A list of HTTP header names and values that CloudFront adds to requests it
* sends to the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html">Adding
* Custom Headers to Origin Requests</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p>
*/
inline void SetCustomHeaders(const CustomHeaders& value) { m_customHeadersHasBeenSet = true; m_customHeaders = value; }
/**
* <p>A list of HTTP header names and values that CloudFront adds to requests it
* sends to the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html">Adding
* Custom Headers to Origin Requests</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p>
*/
inline void SetCustomHeaders(CustomHeaders&& value) { m_customHeadersHasBeenSet = true; m_customHeaders = std::move(value); }
/**
* <p>A list of HTTP header names and values that CloudFront adds to requests it
* sends to the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html">Adding
* Custom Headers to Origin Requests</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p>
*/
inline Origin& WithCustomHeaders(const CustomHeaders& value) { SetCustomHeaders(value); return *this;}
/**
* <p>A list of HTTP header names and values that CloudFront adds to requests it
* sends to the origin.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html">Adding
* Custom Headers to Origin Requests</a> in the <i>Amazon CloudFront Developer
* Guide</i>.</p>
*/
inline Origin& WithCustomHeaders(CustomHeaders&& value) { SetCustomHeaders(std::move(value)); return *this;}
/**
* <p>Use this type to specify an origin that is an Amazon S3 bucket that is <i>
* <b>not</b> </i> configured with static website hosting. To specify any other
* type of origin, including an Amazon S3 bucket that is configured with static
* website hosting, use the <code>CustomOriginConfig</code> type instead.</p>
*/
inline const S3OriginConfig& GetS3OriginConfig() const{ return m_s3OriginConfig; }
/**
* <p>Use this type to specify an origin that is an Amazon S3 bucket that is <i>
* <b>not</b> </i> configured with static website hosting. To specify any other
* type of origin, including an Amazon S3 bucket that is configured with static
* website hosting, use the <code>CustomOriginConfig</code> type instead.</p>
*/
inline bool S3OriginConfigHasBeenSet() const { return m_s3OriginConfigHasBeenSet; }
/**
* <p>Use this type to specify an origin that is an Amazon S3 bucket that is <i>
* <b>not</b> </i> configured with static website hosting. To specify any other
* type of origin, including an Amazon S3 bucket that is configured with static
* website hosting, use the <code>CustomOriginConfig</code> type instead.</p>
*/
inline void SetS3OriginConfig(const S3OriginConfig& value) { m_s3OriginConfigHasBeenSet = true; m_s3OriginConfig = value; }
/**
* <p>Use this type to specify an origin that is an Amazon S3 bucket that is <i>
* <b>not</b> </i> configured with static website hosting. To specify any other
* type of origin, including an Amazon S3 bucket that is configured with static
* website hosting, use the <code>CustomOriginConfig</code> type instead.</p>
*/
inline void SetS3OriginConfig(S3OriginConfig&& value) { m_s3OriginConfigHasBeenSet = true; m_s3OriginConfig = std::move(value); }
/**
* <p>Use this type to specify an origin that is an Amazon S3 bucket that is <i>
* <b>not</b> </i> configured with static website hosting. To specify any other
* type of origin, including an Amazon S3 bucket that is configured with static
* website hosting, use the <code>CustomOriginConfig</code> type instead.</p>
*/
inline Origin& WithS3OriginConfig(const S3OriginConfig& value) { SetS3OriginConfig(value); return *this;}
/**
* <p>Use this type to specify an origin that is an Amazon S3 bucket that is <i>
* <b>not</b> </i> configured with static website hosting. To specify any other
* type of origin, including an Amazon S3 bucket that is configured with static
* website hosting, use the <code>CustomOriginConfig</code> type instead.</p>
*/
inline Origin& WithS3OriginConfig(S3OriginConfig&& value) { SetS3OriginConfig(std::move(value)); return *this;}
/**
* <p>Use this type to specify an origin that is a content container or HTTP
* server, including an Amazon S3 bucket that is configured with static website
* hosting. To specify an Amazon S3 bucket that is <i> <b>not</b> </i> configured
* with static website hosting, use the <code>S3OriginConfig</code> type
* instead.</p>
*/
inline const CustomOriginConfig& GetCustomOriginConfig() const{ return m_customOriginConfig; }
/**
* <p>Use this type to specify an origin that is a content container or HTTP
* server, including an Amazon S3 bucket that is configured with static website
* hosting. To specify an Amazon S3 bucket that is <i> <b>not</b> </i> configured
* with static website hosting, use the <code>S3OriginConfig</code> type
* instead.</p>
*/
inline bool CustomOriginConfigHasBeenSet() const { return m_customOriginConfigHasBeenSet; }
/**
* <p>Use this type to specify an origin that is a content container or HTTP
* server, including an Amazon S3 bucket that is configured with static website
* hosting. To specify an Amazon S3 bucket that is <i> <b>not</b> </i> configured
* with static website hosting, use the <code>S3OriginConfig</code> type
* instead.</p>
*/
inline void SetCustomOriginConfig(const CustomOriginConfig& value) { m_customOriginConfigHasBeenSet = true; m_customOriginConfig = value; }
/**
* <p>Use this type to specify an origin that is a content container or HTTP
* server, including an Amazon S3 bucket that is configured with static website
* hosting. To specify an Amazon S3 bucket that is <i> <b>not</b> </i> configured
* with static website hosting, use the <code>S3OriginConfig</code> type
* instead.</p>
*/
inline void SetCustomOriginConfig(CustomOriginConfig&& value) { m_customOriginConfigHasBeenSet = true; m_customOriginConfig = std::move(value); }
/**
* <p>Use this type to specify an origin that is a content container or HTTP
* server, including an Amazon S3 bucket that is configured with static website
* hosting. To specify an Amazon S3 bucket that is <i> <b>not</b> </i> configured
* with static website hosting, use the <code>S3OriginConfig</code> type
* instead.</p>
*/
inline Origin& WithCustomOriginConfig(const CustomOriginConfig& value) { SetCustomOriginConfig(value); return *this;}
/**
* <p>Use this type to specify an origin that is a content container or HTTP
* server, including an Amazon S3 bucket that is configured with static website
* hosting. To specify an Amazon S3 bucket that is <i> <b>not</b> </i> configured
* with static website hosting, use the <code>S3OriginConfig</code> type
* instead.</p>
*/
inline Origin& WithCustomOriginConfig(CustomOriginConfig&& value) { SetCustomOriginConfig(std::move(value)); return *this;}
/**
* <p>The number of times that CloudFront attempts to connect to the origin. The
* minimum number is 1, the maximum is 3, and the default (if you don’t specify
* otherwise) is 3.</p> <p>For a custom origin (including an Amazon S3 bucket
* that’s configured with static website hosting), this value also specifies the
* number of times that CloudFront attempts to get a response from the origin, in
* the case of an <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginResponseTimeout">Origin
* Response Timeout</a>.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts">Origin
* Connection Attempts</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline int GetConnectionAttempts() const{ return m_connectionAttempts; }
/**
* <p>The number of times that CloudFront attempts to connect to the origin. The
* minimum number is 1, the maximum is 3, and the default (if you don’t specify
* otherwise) is 3.</p> <p>For a custom origin (including an Amazon S3 bucket
* that’s configured with static website hosting), this value also specifies the
* number of times that CloudFront attempts to get a response from the origin, in
* the case of an <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginResponseTimeout">Origin
* Response Timeout</a>.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts">Origin
* Connection Attempts</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline bool ConnectionAttemptsHasBeenSet() const { return m_connectionAttemptsHasBeenSet; }
/**
* <p>The number of times that CloudFront attempts to connect to the origin. The
* minimum number is 1, the maximum is 3, and the default (if you don’t specify
* otherwise) is 3.</p> <p>For a custom origin (including an Amazon S3 bucket
* that’s configured with static website hosting), this value also specifies the
* number of times that CloudFront attempts to get a response from the origin, in
* the case of an <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginResponseTimeout">Origin
* Response Timeout</a>.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts">Origin
* Connection Attempts</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetConnectionAttempts(int value) { m_connectionAttemptsHasBeenSet = true; m_connectionAttempts = value; }
/**
* <p>The number of times that CloudFront attempts to connect to the origin. The
* minimum number is 1, the maximum is 3, and the default (if you don’t specify
* otherwise) is 3.</p> <p>For a custom origin (including an Amazon S3 bucket
* that’s configured with static website hosting), this value also specifies the
* number of times that CloudFront attempts to get a response from the origin, in
* the case of an <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginResponseTimeout">Origin
* Response Timeout</a>.</p> <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts">Origin
* Connection Attempts</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithConnectionAttempts(int value) { SetConnectionAttempts(value); return *this;}
/**
* <p>The number of seconds that CloudFront waits when trying to establish a
* connection to the origin. The minimum timeout is 1 second, the maximum is 10
* seconds, and the default (if you don’t specify otherwise) is 10 seconds.</p>
* <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout">Origin
* Connection Timeout</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline int GetConnectionTimeout() const{ return m_connectionTimeout; }
/**
* <p>The number of seconds that CloudFront waits when trying to establish a
* connection to the origin. The minimum timeout is 1 second, the maximum is 10
* seconds, and the default (if you don’t specify otherwise) is 10 seconds.</p>
* <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout">Origin
* Connection Timeout</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline bool ConnectionTimeoutHasBeenSet() const { return m_connectionTimeoutHasBeenSet; }
/**
* <p>The number of seconds that CloudFront waits when trying to establish a
* connection to the origin. The minimum timeout is 1 second, the maximum is 10
* seconds, and the default (if you don’t specify otherwise) is 10 seconds.</p>
* <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout">Origin
* Connection Timeout</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline void SetConnectionTimeout(int value) { m_connectionTimeoutHasBeenSet = true; m_connectionTimeout = value; }
/**
* <p>The number of seconds that CloudFront waits when trying to establish a
* connection to the origin. The minimum timeout is 1 second, the maximum is 10
* seconds, and the default (if you don’t specify otherwise) is 10 seconds.</p>
* <p>For more information, see <a
* href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout">Origin
* Connection Timeout</a> in the <i>Amazon CloudFront Developer Guide</i>.</p>
*/
inline Origin& WithConnectionTimeout(int value) { SetConnectionTimeout(value); return *this;}
private:
Aws::String m_id;
bool m_idHasBeenSet;
Aws::String m_domainName;
bool m_domainNameHasBeenSet;
Aws::String m_originPath;
bool m_originPathHasBeenSet;
CustomHeaders m_customHeaders;
bool m_customHeadersHasBeenSet;
S3OriginConfig m_s3OriginConfig;
bool m_s3OriginConfigHasBeenSet;
CustomOriginConfig m_customOriginConfig;
bool m_customOriginConfigHasBeenSet;
int m_connectionAttempts;
bool m_connectionAttemptsHasBeenSet;
int m_connectionTimeout;
bool m_connectionTimeoutHasBeenSet;
};
} // namespace Model
} // namespace CloudFront
} // namespace Aws
| 54.492337 | 164 | 0.706381 | [
"model"
] |
d0d2963f02e915fd295623d3dedeeef42170b375 | 45,947 | h | C | src/settings_data.h | hramrach/dunst | 722d15f53436db81bfd42aff4d20ded2e9b25542 | [
"BSD-3-Clause"
] | null | null | null | src/settings_data.h | hramrach/dunst | 722d15f53436db81bfd42aff4d20ded2e9b25542 | [
"BSD-3-Clause"
] | null | null | null | src/settings_data.h | hramrach/dunst | 722d15f53436db81bfd42aff4d20ded2e9b25542 | [
"BSD-3-Clause"
] | null | null | null | /* copyright 2013 Sascha Kruse and contributors (see LICENSE for licensing information) */
#ifndef DUNST_SETTING_DATA_H
#define DUNST_SETTING_DATA_H
#include <stddef.h>
#include "option_parser.h"
#include "rules.h"
struct string_to_enum_def {
const char* string;
const int enum_value;
};
struct setting {
/**
* A string with the setting key as found in the config file.
*/
char *name;
/**
* A string with the ini section where the variable is allowed. This
* section should be part of the special_sections array.
*
* Example:
* .section = "global",
*/
char *section;
/**
* A string with a short description of the config variable. This is
* currently not used, but it may be used to generate help messages.
*/
char *description;
// IDEA: Add long description to generate man page from this. This could
// also be useful for an extended help text.
/**
* Enum of the setting type. Every setting type is parsed differently in
* option_parser.c.
*/
enum setting_type type;
/**
* A string with the default value of the setting. This should be the
* same as what it would be in the config file, as this is parsed by the
* same parser.
* default_value is unused when the setting is only a rule (value == NULL).
*
* Example:
* .default_value = "10s", // 10 seconds of time
*/
char *default_value;
/**
* (nullable)
* A pointer to the corresponding setting in the setting struct. Make
* sure to always take the address, even if it's already a pointer in the
* settings struct.
* If value is NULL, the setting is interpreted as a rule.
*
* Example:
* .value = &settings.font,
*/
void *value;
/**
* (nullable)
* Function pointer for the parser - to be used in case of enums or other
* special settings. If the parse requires extra data, it should be given
* with parser_data. This allows for one generic parser for, for example,
* enums, instead of a parser for every enum.
*
* @param data The required data for parsing the value. See parser_data.
* @param cfg_value The string representing the value of the config
* variable
* @param ret A pointer to the return value. This casted by the parser to
* the right type.
*/
int (*parser)(const void* data, const char *cfg_value, void* ret);
/**
* (nullable)
* A pointer to the data required for the parser to parse this setting.
*/
const void* parser_data; // This is passed to the parser function
/**
* The offset of this setting in the rule struct, if it exists. Zero is
* being interpreted as if no rule exists for this setting.
*
* Example:
* .rule_offset = offsetof(struct rule, *member*);
*/
size_t rule_offset;
};
static const struct rule empty_rule = {
.name = "empty",
.appname = NULL,
.summary = NULL,
.body = NULL,
.icon = NULL,
.category = NULL,
.msg_urgency = URG_NONE,
.timeout = -1,
.urgency = URG_NONE,
.markup = MARKUP_NULL,
.history_ignore = -1,
.match_transient = -1,
.set_transient = -1,
.skip_display = -1,
.new_icon = NULL,
.fg = NULL,
.bg = NULL,
.format = NULL,
.script = NULL,
};
#ifndef ZWLR_LAYER_SHELL_V1_LAYER_ENUM
#define ZWLR_LAYER_SHELL_V1_LAYER_ENUM
// Needed for compiling without wayland dependency
const enum zwlr_layer_shell_v1_layer {
ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND = 0,
ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM = 1,
ZWLR_LAYER_SHELL_V1_LAYER_TOP = 2,
ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY = 3,
};
#endif /* ZWLR_LAYER_SHELL_V1_LAYER_ENUM */
enum list_type {
INVALID_LIST = 0,
MOUSE_LIST = 1,
};
#define ENUM_END {NULL, 0}
static const struct string_to_enum_def verbosity_enum_data[] = {
{"critical", G_LOG_LEVEL_CRITICAL },
{"crit", G_LOG_LEVEL_CRITICAL },
{"warning", G_LOG_LEVEL_WARNING },
{"warn", G_LOG_LEVEL_WARNING },
{"message", G_LOG_LEVEL_MESSAGE },
{"mesg", G_LOG_LEVEL_MESSAGE },
{"info", G_LOG_LEVEL_INFO },
{"debug", G_LOG_LEVEL_DEBUG },
{"deb", G_LOG_LEVEL_DEBUG },
ENUM_END,
};
static const struct string_to_enum_def boolean_enum_data[] = {
{"True", true },
{"true", true },
{"On", true },
{"on", true },
{"Yes", true },
{"yes", true },
{"1", true },
{"False", false },
{"false", false },
{"Off", false },
{"off", false },
{"No", false },
{"no", false },
{"0", false },
{"n", false },
{"y", false },
{"N", false },
{"Y", true },
ENUM_END,
};
static const struct string_to_enum_def horizontal_alignment_enum_data[] = {
{"left", ALIGN_LEFT },
{"center", ALIGN_CENTER },
{"right", ALIGN_RIGHT },
ENUM_END,
};
static const struct string_to_enum_def ellipsize_enum_data[] = {
{"start", ELLIPSE_START },
{"middle", ELLIPSE_MIDDLE },
{"end", ELLIPSE_END },
ENUM_END,
};
static struct string_to_enum_def follow_mode_enum_data[] = {
{"mouse", FOLLOW_MOUSE },
{"keyboard", FOLLOW_KEYBOARD },
{"none", FOLLOW_NONE },
ENUM_END,
};
static const struct string_to_enum_def fullscreen_enum_data[] = {
{"show", FS_SHOW },
{"delay", FS_DELAY },
{"pushback", FS_PUSHBACK },
ENUM_END,
};
static const struct string_to_enum_def icon_position_enum_data[] = {
{"left", ICON_LEFT },
{"right", ICON_RIGHT },
{"off", ICON_OFF },
ENUM_END,
};
static const struct string_to_enum_def vertical_alignment_enum_data[] = {
{"top", VERTICAL_TOP },
{"center", VERTICAL_CENTER },
{"bottom", VERTICAL_BOTTOM },
ENUM_END,
};
static const struct string_to_enum_def markup_mode_enum_data[] = {
{"strip", MARKUP_STRIP },
{"no", MARKUP_NO },
{"full", MARKUP_FULL },
{"yes", MARKUP_FULL },
ENUM_END,
};
static const struct string_to_enum_def mouse_action_enum_data[] = {
{"none", MOUSE_NONE },
{"do_action", MOUSE_DO_ACTION },
{"close_current", MOUSE_CLOSE_CURRENT },
{"close_all", MOUSE_CLOSE_ALL },
ENUM_END,
};
static const struct string_to_enum_def sep_color_enum_data[] = {
{"auto", SEP_AUTO },
{"foreground", SEP_FOREGROUND },
{"frame", SEP_FRAME },
ENUM_END,
};
static const struct string_to_enum_def urgency_enum_data[] = {
{"low", URG_LOW },
{"normal", URG_NORM },
{"critical", URG_CRIT },
ENUM_END,
};
static const struct string_to_enum_def layer_enum_data[] = {
{"bottom", ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM },
{"top", ZWLR_LAYER_SHELL_V1_LAYER_TOP },
{"overlay", ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY },
ENUM_END,
};
static const struct setting allowed_settings[] = {
// match rules below
{
.name = "appname",
.section = "*",
.description = "The name of the application as reported by the client. Be aware that the name can often differ depending on the locale used.",
.type = TYPE_STRING,
.default_value = "*", // default_value is not used for rules
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, appname),
},
{
.name = "body",
.section = "*",
.description = "The body of the notification",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, body),
},
{
.name = "category",
.section = "*",
.description = "The category of the notification as defined by the notification spec. See https://developer.gnome.org/notification-spec/#categories",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, category),
},
{
.name = "desktop_entry",
.section = "*",
.description = "GLib based applications export their desktop-entry name. In comparison to the appname, the desktop-entry won't get localized.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, desktop_entry),
},
{
.name = "icon",
.section = "*",
.description = "The icon of the notification in the form of a file path. Can be empty if no icon is available or a raw icon is used instead.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, icon),
},
{
.name = "match_transient",
.section = "*",
.description = "Match if the notification has been declared as transient by the client or by some other rule.",
.type = TYPE_CUSTOM,
.default_value = "*",
.value = NULL,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
.rule_offset = offsetof(struct rule, match_transient),
},
{
.name = "msg_urgency",
.section = "*",
.description = "Matches the urgency of the notification as set by the client or by some other rule.",
.type = TYPE_CUSTOM,
.default_value = "*",
.value = NULL,
.parser = string_parse_enum,
.parser_data = urgency_enum_data,
.rule_offset = offsetof(struct rule, msg_urgency),
},
{
.name = "stack_tag",
.section = "*",
.description = "Matches the stack tag of the notification as set by the client or by some other rule.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, stack_tag),
},
{
.name = "summary",
.section = "*",
.description = "summary text of the notification",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, summary),
},
// modifying rules below
{
.name = "script",
.section = "*",
.description = "script",
.type = TYPE_PATH,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, script),
},
{
.name = "background",
.section = "*",
.description = "The background color of the notification.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, bg),
},
{
.name = "foreground",
.section = "*",
.description = "The foreground color of the notification.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, fg),
},
{
.name = "highlight",
.section = "*",
.description = "The highlight color of the notification.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, highlight),
},
{
.name = "format",
.section = "global",
.description = "The format template for the notifications",
.type = TYPE_STRING,
.default_value = "<b>%s</b>\n%b",
.value = &settings.format,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, format),
},
{
.name = "fullscreen",
.section = "*",
.description = "This attribute specifies how notifications are handled if a fullscreen window is focused. One of show, delay, or pushback.",
.type = TYPE_CUSTOM,
.default_value = "show",
.value = NULL,
.parser = string_parse_enum,
.parser_data = fullscreen_enum_data,
.rule_offset = offsetof(struct rule, fullscreen),
},
{
.name = "new_icon",
.section = "*",
.description = "Updates the icon of the notification, it should be a path to a valid image.",
.type = TYPE_PATH,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, new_icon),
},
{
.name = "set_stack_tag",
.section = "*",
.description = "Sets the stack tag for the notification, notifications with the same (non-empty) stack tag will replace each-other so only the newest one is visible.",
.type = TYPE_STRING,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, stack_tag),
},
{
.name = "set_transient",
.section = "*",
.description = "Sets whether the notification is considered transient. Transient notifications will bypass the idle_threshold setting.",
.type = TYPE_CUSTOM,
.default_value = "*",
.value = NULL,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
.rule_offset = offsetof(struct rule, set_transient),
},
{
.name = "timeout",
.section = "*",
.description = "Don't timeout notifications if user is longer idle than threshold",
.type = TYPE_TIME,
.default_value = "*",
.value = NULL,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, timeout),
},
{
.name = "urgency",
.section = "*",
.description = "This sets the notification urgency.",
.type = TYPE_CUSTOM,
.default_value = "*",
.value = NULL,
.parser = string_parse_enum,
.parser_data = urgency_enum_data,
.rule_offset = offsetof(struct rule, urgency),
},
{
.name = "skip_display",
.section = "*",
.description = "Setting this to true will prevent the notification from being displayed initially but will be saved in history for later viewing.",
.type = TYPE_CUSTOM,
.default_value = "*",
.value = NULL,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
.rule_offset = offsetof(struct rule, skip_display),
},
{
.name = "frame",
.section = "*",
.description = "Setting this to true will prevent the notification from being displayed initially but will be saved in history for later viewing.",
.type = TYPE_CUSTOM,
.default_value = "*",
.value = NULL,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
.rule_offset = offsetof(struct rule, skip_display),
},
{
.name = "frame_color",
.section = "*",
.description = "Color of the frame around the window",
.type = TYPE_STRING,
.default_value = "#888888",
.value = &settings.frame_color,
.parser = NULL,
.parser_data = NULL,
.rule_offset = offsetof(struct rule, fc),
},
// other settings below
{
.name = "per_monitor_dpi",
.section = "experimental",
.description = "Use a different DPI per monitor",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.per_monitor_dpi,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "force_xinerama",
.section = "global",
.description = "Force the use of the Xinerama extension",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.force_xinerama,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "force_xwayland",
.section = "global",
.description = "Force the use of the xwayland output",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.force_xwayland,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "font",
.section = "global",
.description = "The font dunst should use.",
.type = TYPE_STRING,
.default_value = "Monospace 8",
.value = &settings.font,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "sort",
.section = "global",
.description = "Sort notifications by urgency and date?",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.sort,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "indicate_hidden",
.section = "global",
.description = "Show how many notifications are hidden",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.indicate_hidden,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "word_wrap",
.section = "global",
.description = "Truncating long lines or do word wrap",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.word_wrap,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "ignore_dbusclose",
.section = "global",
.description = "Ignore dbus CloseNotification events",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.ignore_dbusclose,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "ignore_newline",
.section = "global",
.description = "Ignore newline characters in notifications",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.ignore_newline,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "idle_threshold",
.section = "global",
.description = "Don't timeout notifications if user is longer idle than threshold",
.type = TYPE_TIME,
.default_value = "0",
.value = &settings.idle_threshold,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "monitor",
.section = "global",
.description = "On which monitor should the notifications be displayed",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.monitor,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "title",
.section = "global",
.description = "Define the title of windows spawned by dunst.",
.type = TYPE_STRING,
.default_value = "Dunst",
.value = &settings.title,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "class",
.section = "global",
.description = "Define the class of windows spawned by dunst.",
.type = TYPE_STRING,
.default_value = "Dunst",
.value = &settings.class,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "shrink",
.section = "global",
.description = "Shrink window if it's smaller than the width",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.shrink,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "line_height",
.section = "global",
.description = "Add spacing between lines of text",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.line_height,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "notification_height",
.section = "global",
.description = "Define height of the window",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.notification_height,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "show_age_threshold",
.section = "global",
.description = "When should the age of the notification be displayed?",
.type = TYPE_TIME,
.default_value = "60",
.value = &settings.show_age_threshold,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "hide_duplicate_count",
.section = "global",
.description = "Hide the count of stacked notifications with the same content",
.type = TYPE_CUSTOM,
.default_value = "false",
.value = &settings.hide_duplicate_count,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "sticky_history",
.section = "global",
.description = "Don't timeout notifications popped up from history",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.sticky_history,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "history_length",
.section = "global",
.description = "Max amount of notifications kept in history",
.type = TYPE_INT,
.default_value = "20",
.value = &settings.history_length,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "show_indicators",
.section = "global",
.description = "Show indicators for actions \"(A)\" and URLs \"(U)\"",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.show_indicators,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "separator_height",
.section = "global",
.description = "height of the separator line",
.type = TYPE_INT,
.default_value = "2",
.value = &settings.separator_height,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "padding",
.section = "global",
.description = "Padding between text and separator",
.type = TYPE_INT,
.default_value = "8",
.value = &settings.padding,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "horizontal_padding",
.section = "global",
.description = "horizontal padding",
.type = TYPE_INT,
.default_value = "8",
.value = &settings.h_padding,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "text_icon_padding",
.section = "global",
.description = "Padding between text and icon",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.text_icon_padding,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "transparency",
.section = "global",
.description = "Transparency. Range 0-100",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.transparency,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "corner_radius",
.section = "global",
.description = "Window corner radius",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.corner_radius,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "progress_bar_height",
.section = "global",
.description = "Height of the progress bar",
.type = TYPE_INT,
.default_value = "10",
.value = &settings.progress_bar_height,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "progress_bar_min_width",
.section = "global",
.description = "Minimum width of the progress bar",
.type = TYPE_INT,
.default_value = "150",
.value = &settings.progress_bar_min_width,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "progress_bar_max_width",
.section = "global",
.description = "Maximum width of the progress bar",
.type = TYPE_INT,
.default_value = "300",
.value = &settings.progress_bar_max_width,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "progress_bar_frame_width",
.section = "global",
.description = "Frame width of the progress bar",
.type = TYPE_INT,
.default_value = "1",
.value = &settings.progress_bar_frame_width,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "progress_bar",
.section = "global",
.description = "Show the progress bar",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.progress_bar,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "stack_duplicates",
.section = "global",
.description = "Stack together notifications with the same content",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.stack_duplicates,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
{
.name = "dmenu",
.section = "global",
.description = "path to dmenu",
.type = TYPE_PATH,
.default_value = "/usr/bin/dmenu -p dunst",
.value = &settings.dmenu,
.parser = NULL,
.parser_data = &settings.dmenu_cmd,
},
{
.name = "browser",
.section = "global",
.description = "path to browser",
.type = TYPE_PATH,
.default_value = "/usr/bin/xdg-open",
.value = &settings.browser,
.parser = NULL,
.parser_data = &settings.browser_cmd,
},
{
.name = "min_icon_size",
.section = "global",
.description = "Scale smaller icons up to this size, set to 0 to disable. If max_icon_size also specified, that has the final say.",
.type = TYPE_INT,
.default_value = "0",
.value = &settings.min_icon_size,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "max_icon_size",
.section = "global",
.description = "Scale larger icons down to this size, set to 0 to disable",
.type = TYPE_INT,
.default_value = "32",
.value = &settings.max_icon_size,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "always_run_script",
.section = "global",
.description = "Always run rule-defined scripts, even if the notification is suppressed with format = \"\".",
.type = TYPE_CUSTOM,
.default_value = "true",
.value = &settings.always_run_script,
.parser = string_parse_bool,
.parser_data = boolean_enum_data,
},
// manual extractions below
{
.name = "markup",
.section = "global",
.description = "Specify how markup should be handled",
.type = TYPE_CUSTOM,
.default_value = "full",
.value = &settings.markup,
.parser = string_parse_enum,
.parser_data = markup_mode_enum_data,
},
{
.name = "ellipsize",
.section = "global",
.description = "Ellipsize truncated lines on the start/middle/end",
.type = TYPE_CUSTOM,
.default_value = "middle",
.value = &settings.ellipsize,
.parser = string_parse_enum,
.parser_data = ellipsize_enum_data,
},
{
.name = "follow",
.section = "global",
.description = "Follow mouse, keyboard or none?",
.type = TYPE_CUSTOM,
.default_value = "mouse",
.value = &settings.f_mode,
.parser = string_parse_enum,
.parser_data = follow_mode_enum_data,
},
{
.name = "geometry",
.section = "global",
.description = "Geometry for the window",
.type = TYPE_GEOMETRY,
.default_value = "300x5-30+20",
.value = &settings.geometry,
.parser = NULL, // TODO replace this setting with some other format and get rid of x11 compile time dependency
.parser_data = NULL,
},
{
.name = "scale",
.section = "global",
.description = "Scale factor, set to 0 to auto-detect, X11 only",
.type = TYPE_DOUBLE,
.default_value = "0",
.value = &settings.scale,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "alignment",
.section = "global",
.description = "Text alignment left/center/right",
.type = TYPE_CUSTOM,
.default_value = "left",
.value = &settings.align,
.parser = string_parse_enum,
.parser_data = horizontal_alignment_enum_data,
},
{
.name = "separator_color",
.section = "global",
.description = "Color of the separator line (or 'auto')",
.type = TYPE_CUSTOM,
.default_value = "frame",
.value = &settings.sep_color,
.parser = string_parse_sepcolor,
.parser_data = sep_color_enum_data,
},
{
.name = "icon_position",
.section = "global",
.description = "Align icons left/right/off",
.type = TYPE_CUSTOM,
.default_value = "left",
.value = &settings.icon_position,
.parser = string_parse_enum,
.parser_data = icon_position_enum_data,
},
{
.name = "vertical_alignment",
.section = "global",
.description = "Align icon and text top/center/bottom",
.type = TYPE_CUSTOM,
.default_value = "center",
.value = &settings.vertical_alignment,
.parser = string_parse_enum,
.parser_data = vertical_alignment_enum_data,
},
{
.name = "layer",
.section = "global",
.description = "Select the layer where notifications should be placed",
.type = TYPE_CUSTOM,
.default_value = "overlay",
.value = &settings.layer,
.parser = string_parse_enum,
.parser_data = layer_enum_data,
},
{
.name = "mouse_left_click",
.section = "global",
.description = "Action of left click event",
.type = TYPE_LIST,
.default_value = "close_current",
.value = &settings.mouse_left_click,
.parser = NULL,
.parser_data = GINT_TO_POINTER(MOUSE_LIST),
},
{
.name = "mouse_middle_click",
.section = "global",
.description = "Action of middle click event",
.type = TYPE_LIST,
.default_value = "do_action, close_current",
.value = &settings.mouse_middle_click,
.parser = NULL,
.parser_data = GINT_TO_POINTER(MOUSE_LIST),
},
{
.name = "mouse_right_click",
.section = "global",
.description = "Action of right click event",
.type = TYPE_LIST,
.default_value = "close_all",
.value = &settings.mouse_right_click,
.parser = NULL,
.parser_data = GINT_TO_POINTER(MOUSE_LIST),
},
{
.name = "icon_path",
.section = "global",
.description = "paths to default icons",
.type = TYPE_STRING,
.default_value = "/usr/share/icons/gnome/16x16/status/:/usr/share/icons/gnome/16x16/devices/",
.value = &settings.icon_path,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "frame_width",
.section = "global",
.description = "Width of frame around the window",
.type = TYPE_INT,
.default_value = "3",
.value = &settings.frame_width,
.parser = NULL,
.parser_data = NULL,
},
// These are only used for setting defaults, since there is a rule
// above doing the same.
// TODO it's probably better to create an array with default rules.
{
.name = "background",
.section = "urgency_low",
.description = "Background color for notifications with low urgency",
.type = TYPE_STRING,
.default_value = "#222222",
.value = &settings.colors_low.bg,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "foreground",
.section = "urgency_low",
.description = "Foreground color for notifications with low urgency",
.type = TYPE_STRING,
.default_value = "#888888",
.value = &settings.colors_low.fg,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "highlight",
.section = "urgency_low",
.description = "Highlight color for notifications with low urgency",
.type = TYPE_STRING,
.default_value = "#7f7fff",
.value = &settings.colors_low.highlight,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "frame_color",
.section = "urgency_low",
.description = "Frame color for notifications with low urgency",
.type = TYPE_STRING,
.default_value = "#888888",
.value = &settings.colors_low.frame,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "timeout",
.section = "urgency_low",
.description = "Timeout for notifications with low urgency",
.type = TYPE_TIME,
.default_value = "10", // in seconds
.value = &settings.timeouts[URG_LOW],
.parser = NULL,
.parser_data = NULL,
},
{
.name = "icon",
.section = "urgency_low",
.description = "Icon for notifications with low urgency",
.type = TYPE_STRING,
.default_value = "dialog-information",
.value = &settings.icons[URG_LOW],
.parser = NULL,
.parser_data = NULL,
},
{
.name = "background",
.section = "urgency_normal",
.description = "Background color for notifications with normal urgency",
.type = TYPE_STRING,
.default_value = "#285577",
.value = &settings.colors_norm.bg,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "foreground",
.section = "urgency_normal",
.description = "Foreground color for notifications with normal urgency",
.type = TYPE_STRING,
.default_value = "#ffffff",
.value = &settings.colors_norm.fg,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "highlight",
.section = "urgency_normal",
.description = "Highlight color for notifications with normal urgency",
.type = TYPE_STRING,
.default_value = "#1745d1",
.value = &settings.colors_norm.highlight,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "frame_color",
.section = "urgency_normal",
.description = "Frame color for notifications with normal urgency",
.type = TYPE_STRING,
.default_value = "#888888",
.value = &settings.colors_norm.frame,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "timeout",
.section = "urgency_normal",
.description = "Timeout for notifications with normal urgency",
.type = TYPE_TIME,
.default_value = "10",
.value = &settings.timeouts[URG_NORM],
.parser = NULL,
.parser_data = NULL,
},
{
.name = "icon",
.section = "urgency_normal",
.description = "Icon for notifications with normal urgency",
.type = TYPE_STRING,
.default_value = "dialog-information",
.value = &settings.icons[URG_NORM],
.parser = NULL,
.parser_data = NULL,
},
{
.name = "background",
.section = "urgency_critical",
.description = "Background color for notifications with critical urgency",
.type = TYPE_STRING,
.default_value = "#ffffff",
.value = &settings.colors_crit.bg,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "foreground",
.section = "urgency_critical",
.description = "Foreground color for notifications with ciritical urgency",
.type = TYPE_STRING,
.default_value = "#ffffff",
.value = &settings.colors_crit.fg,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "highlight",
.section = "urgency_critical",
.description = "Highlight color for notifications with ciritical urgency",
.type = TYPE_STRING,
.default_value = "#ff6666",
.value = &settings.colors_crit.highlight,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "frame_color",
.section = "urgency_critical",
.description = "Frame color for notifications with critical urgency",
.type = TYPE_STRING,
.default_value = "#ff0000",
.value = &settings.colors_crit.frame,
.parser = NULL,
.parser_data = NULL,
},
{
.name = "timeout",
.section = "urgency_critical",
.description = "Timeout for notifications with critical urgency",
.type = TYPE_TIME,
.default_value = "0",
.value = &settings.timeouts[URG_CRIT],
.parser = NULL,
.parser_data = NULL,
},
{
.name = "icon",
.section = "urgency_critical",
.description = "Icon for notifications with critical urgency",
.type = TYPE_STRING,
.default_value = "dialog-warning",
.value = &settings.icons[URG_CRIT],
.parser = NULL,
.parser_data = NULL,
},
};
#endif
/* vim: set ft=c tabstop=8 shiftwidth=8 expandtab textwidth=0: */
| 37.324939 | 183 | 0.46978 | [
"geometry"
] |
d0d83a39f91c3d58cdd7792619011d97dee71917 | 6,018 | h | C | 3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Utils/vgMeshRenderer.h | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | null | null | null | 3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Utils/vgMeshRenderer.h | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | null | null | null | 3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Utils/vgMeshRenderer.h | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | null | null | null | /*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef _VITELOTTE_VG_MESH_RENDERER_
#define _VITELOTTE_VG_MESH_RENDERER_
#include <Eigen/Dense>
#include <Eigen/StdVector>
#include "../../common/gl_utils/shader.h"
#include "../../common/gl_utils/color.h"
#include "../Core/femUtils.h"
#include "vgMeshRendererShaders.hpp"
namespace Vitelotte {
using PatateCommon::ColorSpace;
/**
* \brief The VGMeshRendererResources encapsulate resources required by
* VGMeshRenderer for sharing.
*/
class VGMeshRendererResources {
public:
struct SolidUniforms
{
GLint viewMatrixLoc;
GLint normalMatrixLoc;
GLint nodesLoc;
GLint baseNodeIndexLoc;
GLint singularTrianglesLoc;
GLfloat smoothnessLoc;
GLint enableShadingLoc;
GLint meshColorSpaceLoc;
GLint screenColorSpaceLoc;
};
struct WireframeUniforms
{
GLint viewMatrixLoc;
GLint viewportSizeLoc;
GLfloat smoothnessLoc;
GLint lineWidthLoc;
GLint wireframeColorLoc;
};
enum
{
VG_MESH_POSITION_ATTR_LOC,
VG_MESH_NORMAL_ATTR_LOC
};
public:
inline VGMeshRendererResources();
inline ~VGMeshRendererResources();
inline bool initialize();
inline void releaseGLResources();
// private
inline PatateCommon::Shader& solidLinearShader() { return m_solidLinearShader; }
inline PatateCommon::Shader& solidQuadraticShader() { return m_solidQuadraticShader; }
inline PatateCommon::Shader& wireframeShader() { return m_wireframeShader; }
inline const SolidUniforms& solidLinearUniforms() const { return m_solidLinearUniforms; }
inline const SolidUniforms& solidQuadraticUniforms() const { return m_solidQuadraticUniforms; }
inline const WireframeUniforms& wireframeUniforms() const { return m_wireframeUniforms; }
protected:
inline bool initSolidShader(PatateCommon::Shader& shader, SolidUniforms& unif,
const char *fragCode);
inline bool initWireframeShader();
protected:
bool m_initialized;
PatateCommon::Shader m_solidLinearShader;
PatateCommon::Shader m_solidQuadraticShader;
PatateCommon::Shader m_wireframeShader;
SolidUniforms m_solidLinearUniforms;
SolidUniforms m_solidQuadraticUniforms;
WireframeUniforms m_wireframeUniforms;
};
template < typename Vector >
struct DefaultPosProj {
inline Eigen::Vector4f operator()(const Vector& position) const;
};
template < typename Value >
struct DefaultValueProj {
inline Eigen::Vector4f operator()(const Value& value) const;
};
/**
* \brief An OpenGL 3 renderer to display VGMesh objects.
*/
template < class _Mesh,
typename _PosProj = DefaultPosProj <typename _Mesh::Vector>,
typename _ValueProj = DefaultValueProj<typename _Mesh::Value> >
class VGMeshRenderer
{
public:
typedef _Mesh Mesh;
typedef _PosProj PosProj;
typedef _ValueProj ValueProj;
typedef typename Mesh::Node Node;
typedef typename Mesh::Vector Vector;
typedef typename Mesh::Value Value;
typedef typename Mesh::Vertex Vertex;
typedef typename Mesh::Face Face;
typedef VGMeshRendererResources Resources;
typedef Eigen::Vector3f Vector3;
typedef Eigen::Vector4f Vector4;
enum
{
NORMAL_TRIANGLES = 0x01,
SINGULAR_TRIANGLES = 0x02,
ALL_TRIANGLES = NORMAL_TRIANGLES | SINGULAR_TRIANGLES
};
enum
{
NODES_TEXTURE_UNIT
};
public:
VGMeshRenderer(Resources* resources = 0,
const PosProj& posProj = PosProj(),
const ValueProj& valueProj = ValueProj());
~VGMeshRenderer();
const PosProj& positionProjection() const;
PosProj& positionProjection();
const ValueProj& valueProjection() const;
ValueProj& valueProjection();
ColorSpace screenColorSpace() const;
void setScreenColorSpace(ColorSpace cs) const;
void setResources(Resources* resources);
void releaseGLResources();
void updateBuffers(const Mesh& mesh);
void drawGeometry(unsigned geomFlags);
void render(const Eigen::Matrix4f& viewMatrix, float smoothness = 8);
void renderWireframe(const Eigen::Matrix4f& viewMatrix,
const Eigen::Vector2f& viewportSize, float lineWidth = 1,
const Eigen::Vector4f& color = Eigen::Vector4f(0, 0, 0, 1),
float smoothness = 8);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
typedef std::vector<unsigned> IndicesVector;
typedef std::vector<Vector4, Eigen::aligned_allocator<Vector4> > Vector4Vector;
struct GlVertex {
Vector4 position;
Vector3 normal;
};
typedef std::vector<GlVertex, Eigen::aligned_allocator<GlVertex> > VertexVector;
protected:
Vector4 position(const Mesh& mesh, Vertex vx) const;
Vector4 color(const Mesh& mesh, Node node) const;
void initResources();
template < typename Vec >
void createAndUploadBuffer(GLuint& glId, GLenum type,
const Vec& data,
GLenum usage = GL_DYNAMIC_DRAW);
private:
bool m_useVao;
bool m_convertSrgbToLinear;
bool m_ownResources;
PosProj m_positionProjection;
ValueProj m_valueProjection;
Vector4 m_invalidNodeColor;
ColorSpace m_meshColorSpace;
ColorSpace m_screenColorSpace;
Resources* m_resources;
GLuint m_verticesBuffer;
GLuint m_indicesBuffer;
GLuint m_nodesBuffer;
GLuint m_nodesTexture;
GLuint m_vao;
VertexVector m_vertices;
IndicesVector m_indices;
Vector4Vector m_nodes;
bool m_quadratic;
bool m_3d;
unsigned m_nTriangles;
unsigned m_nSingulars;
};
}
#include "vgMeshRenderer.hpp"
#endif
| 26.511013 | 103 | 0.68777 | [
"mesh",
"render",
"vector"
] |
d0d9cb3f4edeb8b25f91f5f65e559506c3295ed2 | 22,085 | c | C | c_src/numerl.c | tanguyl/numerl | c0ca907ef54b05eb2e466a1de971361f10965086 | [
"Apache-2.0"
] | 23 | 2021-12-18T02:51:31.000Z | 2022-01-20T04:16:14.000Z | c_src/numerl.c | tanguyl/numerl | c0ca907ef54b05eb2e466a1de971361f10965086 | [
"Apache-2.0"
] | 7 | 2022-01-09T15:55:06.000Z | 2022-02-14T12:26:23.000Z | c_src/numerl.c | tanguyl/numerl | c0ca907ef54b05eb2e466a1de971361f10965086 | [
"Apache-2.0"
] | 4 | 2022-01-08T19:51:31.000Z | 2022-01-20T04:29:43.000Z | #include <erl_nif.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cblas.h>
/*
--------------------------------------------------------------------|
------------------------------ |
| LAPACKE | |
------------------------------ |
--------------------------------------------------------------------|
*/
void dgetrf_(int* M, int *N, double* A, int* lda, int* IPIV, int* INFO);
void dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO);
/*
--------------------------------------------------------------------|
------------------------------ |
| INIT FC | |
------------------------------ |
--------------------------------------------------------------------|
*/
ERL_NIF_TERM atom_nok;
ERL_NIF_TERM atom_true;
ERL_NIF_TERM atom_false;
ERL_NIF_TERM atom_matrix;
ErlNifResourceType *MULT_YIELDING_ARG = NULL;
int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info){
atom_nok = enif_make_atom(env, "nok\0");
atom_true = enif_make_atom(env, "true\0");
atom_false = enif_make_atom(env, "false\0");
atom_matrix = enif_make_atom(env, "matrix\0");
return 0;
}
int upgrade(ErlNifEnv* caller_env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info){
return 0;
}
//Gives easier access to an ErlangBinary containing a matrix.
typedef struct{
int n_rows;
int n_cols;
//Content of the matrix, in row major format.
double* content;
//Erlang binary containing the matrix.
ErlNifBinary bin;
} Matrix;
//Access asked coordinates of matrix
double* matrix_at(int col, int row, Matrix m){
return &m.content[row*m.n_cols + col];
}
//Allocates memory space of for matrix of dimensions n_rows, n_cols.
//The matrix_content can be modified, until a call to array_to_erl.
//Matrix content is stored in row major format.
Matrix matrix_alloc(int n_rows, int n_cols){
ErlNifBinary bin;
enif_alloc_binary(sizeof(double)*n_rows*n_cols, &bin);
Matrix matrix;
matrix.n_cols = n_cols;
matrix.n_rows = n_rows;
matrix.bin = bin;
matrix.content = (double*) bin.data;
return matrix;
}
//Creates a duplicate of a matrix.
//This duplicate can be modified until uploaded.
Matrix matrix_dup(Matrix m){
Matrix d = matrix_alloc(m.n_rows, m.n_cols);
memcpy(d.content, m.content, d.bin.size);
return d;
}
//Free an allocated matrix that was not sent back to Erlang.
void matrix_free(Matrix m){
enif_release_binary(&m.bin);
}
//Constructs a matrix erlang term.
//No modifications can be made afterwards to the matrix.
ERL_NIF_TERM matrix_to_erl(ErlNifEnv* env, Matrix m){
ERL_NIF_TERM term = enif_make_binary(env, &m.bin);
return enif_make_tuple4(env, atom_matrix, enif_make_int(env,m.n_rows), enif_make_int(env,m.n_cols), term);
}
int enif_is_matrix(ErlNifEnv* env, ERL_NIF_TERM term){
int arity;
const ERL_NIF_TERM* content;
if(!enif_is_tuple(env, term))
return 0;
enif_get_tuple(env, term, &arity, &content);
if(arity != 4)
return 0;
if(content[0] != atom_matrix
|| !enif_is_number(env, content[1])
|| !enif_is_number(env, content[2])
|| !enif_is_binary(env, content[3]))
return 0;
return 1;
}
//Reads an erlang term as a matrix.
//As such, no modifications can be made to the red matrix.
//Returns true if it was possible to read a matrix, false otherwise
int enif_get_matrix(ErlNifEnv* env, ERL_NIF_TERM term, Matrix *dest){
int arity;
const ERL_NIF_TERM* content;
if(!enif_is_tuple(env, term))
return 0;
enif_get_tuple(env, term, &arity, &content);
if(arity != 4)
return 0;
if(content[0] != atom_matrix
|| !enif_get_int(env, content[1], &dest->n_rows)
|| !enif_get_int(env, content[2], &dest->n_cols)
|| !enif_inspect_binary(env, content[3], &dest->bin))
{
return 0;
}
dest->content = (double*) (dest->bin.data);
return 1;
}
//Used to translate at once a number of ERL_NIF_TERM.
//Data types are inferred via content of format string:
// n: number (int or double) translated to double.
// m: matrix
// i: int
int enif_get(ErlNifEnv* env, const ERL_NIF_TERM* erl_terms, const char* format, ...){
va_list valist;
va_start(valist, format);
int valid = 1;
while(valid && *format != '\0'){
switch(*format++){
case 'n':
//Read a number as a double.
;
double *d = va_arg(valist, double*);
int i;
if(!enif_get_double(env, *erl_terms, d))
if(enif_get_int(env, *erl_terms, &i))
*d = (double) i;
else valid = 0;
break;
case 'm':
//Reads a matrix.
valid = enif_get_matrix(env, *erl_terms, va_arg(valist, Matrix*));
break;
case 'i':
//Reads an int.
valid = enif_get_int(env, *erl_terms, va_arg(valist, int*));
break;
default:
//Unknown type... give an error.
valid = 0;
break;
}
erl_terms ++;
}
va_end(valist);
return valid;
}
//----------------------------------------------------------------------------------------------------|
// ------------------------------------------ |
// | NIFS | |
// ------------------------------------------ |
//----------------------------------------------------------------------------------------------------|
//@arg 0: List of Lists of numbers.
//@return: Matrix of dimension
ERL_NIF_TERM nif_matrix(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
unsigned n_rows, line_length, dest = 0, n_cols = -1;
ERL_NIF_TERM list = argv[0], row, elem;
Matrix m;
//Reading incoming matrix.
if(!enif_get_list_length(env, list, &n_rows) && n_rows > 0)
return enif_make_badarg(env);
for(int i = 0; enif_get_list_cell(env, list, &row, &list); i++){
if(!enif_get_list_length(env, row, &line_length))
return enif_make_badarg(env);
if(n_cols == -1){
//Allocate binary, make matrix accessor.
n_cols = line_length;
m = matrix_alloc(n_rows,n_cols);
}
if(n_cols != line_length)
return enif_make_badarg(env);
for(int j = 0; enif_get_list_cell(env, row, &elem, &row); j++){
if(!enif_get_double(env, elem, &m.content[dest])){
int i;
if(enif_get_int(env, elem, &i)){
m.content[dest] = (double) i;
}
else{
return enif_make_badarg(env);
}
}
dest++;
}
}
return matrix_to_erl(env, m);
}
#define PRECISION 10
//Used for debug purpose.
void debug_write(char info[]){
FILE* fp = fopen("debug.txt", "a");
fprintf(fp, info);
fprintf(fp, "\n");
fclose(fp);
}
void debug_write_matrix(Matrix m){
char *content = enif_alloc(sizeof(char)*((2*m.n_cols-1)*m.n_rows*PRECISION + m.n_rows*2 + 3));
content[0] = '[';
content[1] = '\0';
char converted[PRECISION];
for(int i=0; i<m.n_rows; i++){
strcat(content, "[");
for(int j = 0; j<m.n_cols; j++){
snprintf(converted, PRECISION-1, "%.5lf", m.content[i*m.n_cols+j]);
strcat(content, converted);
if(j != m.n_cols-1)
strcat(content, " ");
}
strcat(content, "]");
}
strcat(content, "]");
debug_write(content);
enif_free(content);
}
//@arg 0: matrix.
//@arg 1: int, coord m: row
//@arg 2: int, coord n: col
//@return: double, at cord Matrix(m,n).
ERL_NIF_TERM nif_get(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){
int m,n;
Matrix matrix;
if(!enif_get(env, argv, "iim", &m, &n, &matrix))
return enif_make_badarg(env);
m--, n--;
if(m < 0 || m >= matrix.n_rows || n < 0 || n >= matrix.n_cols)
return enif_make_badarg(env);
int index = m*matrix.n_cols+n;
return enif_make_double(env, matrix.content[index]);
}
ERL_NIF_TERM nif_at(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){
int n;
Matrix matrix;
if(!enif_get(env, argv, "mi", &matrix, &n))
return enif_make_badarg(env);
n--;
if( n < 0 || n >= matrix.n_cols * matrix.n_rows)
return enif_make_badarg(env);
return enif_make_double(env, matrix.content[n]);
}
//Matrix to flattened list of ints
ERL_NIF_TERM nif_mtfli(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){
Matrix M;
if(!enif_get(env, argv, "m", &M)){
return enif_make_badarg(env);
}
int n_elems = M.n_cols * M.n_rows;
ERL_NIF_TERM *arr = enif_alloc(sizeof(ERL_NIF_TERM)*n_elems);
for(int i = 0; i<n_elems; i++){
arr[i] = enif_make_int(env, (int)M.content[i]);
}
ERL_NIF_TERM result = enif_make_list_from_array(env, arr, n_elems);
enif_free(arr);
return result;
}
//Matrix to flattened list of ints
ERL_NIF_TERM nif_mtfl(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){
Matrix M;
if(!enif_get(env, argv, "m", &M)){
return enif_make_badarg(env);
}
int n_elems = M.n_cols * M.n_rows;
ERL_NIF_TERM *arr = enif_alloc(sizeof(ERL_NIF_TERM)*n_elems);
for(int i = 0; i<n_elems; i++){
arr[i] = enif_make_double(env, M.content[i]);
}
ERL_NIF_TERM result = enif_make_list_from_array(env, arr, n_elems);
enif_free(arr);
return result;
}
//Equal all doubles
//Compares whether all doubles are approximately the same.
int equal_ad(double* a, double* b, int size){
for(int i = 0; i<size; i++){
if(fabs(a[i] - b[i])> 1e-6)
return 0;
}
return 1;
}
//@arg 0: Array.
//@arg 1: Array.
//@return: true if arrays share content, false if they have different content || size..
ERL_NIF_TERM nif_equals(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a,b;
if(!enif_get(env, argv, "mm", &a, &b))
return atom_false;
//Compare number of columns and rows
if((a.n_cols != b.n_cols || a.n_rows != b.n_rows))
return atom_false;
//Compare content of arrays
if(!equal_ad(a.content, b.content, a.n_cols*a.n_rows))
return atom_false;
return atom_true;
}
//@arg 0: int.
//@arg 1: Array.
//@return: returns an array, containing requested row.
ERL_NIF_TERM nif_row(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){
int row_req;
Matrix matrix;
if(!enif_get(env, argv, "im", &row_req, &matrix))
return enif_make_badarg(env);
row_req--;
if(row_req<0 || row_req >= matrix.n_rows)
return enif_make_badarg(env);
Matrix row = matrix_alloc(1, matrix.n_cols);
memcpy(row.content, matrix.content + (row_req * matrix.n_cols), matrix.n_cols*sizeof(double));
return matrix_to_erl(env, row);
}
//@arg 0: int.
//@arg 1: Array.
//@return: returns an array, containing requested col.
ERL_NIF_TERM nif_col(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){
int col_req;
Matrix matrix;
if(!enif_get(env, argv, "im", &col_req, &matrix))
return enif_make_badarg(env);
col_req--;
if(col_req<0 || col_req >= matrix.n_cols)
return enif_make_badarg(env);
Matrix col = matrix_alloc(matrix.n_rows, 1);
for(int i = 0; i < matrix.n_rows; i++){
col.content[i] = matrix.content[i * matrix.n_rows + col_req];
}
return matrix_to_erl(env, col);
}
//@arg 0: int.
//@arg 1: int.
//@return: empty Matrix of requested dimension..
ERL_NIF_TERM nif_zeros(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
int m,n;
if(!enif_get(env, argv, "ii", &m, &n))
return enif_make_badarg(env);
Matrix a = matrix_alloc(m,n);
memset(a.content, 0, sizeof(double)*m*n);
return matrix_to_erl(env, a);
}
//@arg 0: int.
//@arg 1: int.
//@return: empty matrix of dimension [arg 0, arg 1]..
ERL_NIF_TERM nif_eye(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
int m;
if(!enif_get_int(env, argv[0], &m))
return enif_make_badarg(env);
if(m <= 0)
return enif_make_badarg(env);
Matrix a = matrix_alloc(m,m);
memset(a.content, 0, sizeof(double)*m*m);
for(int i = 0; i<m; i++){
a.content[i*m+i] = 1.0;
}
return matrix_to_erl(env, a);
}
//Either element-wise multiplication, or multiplication of a matrix by a number.
ERL_NIF_TERM nif_mult(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a,b;
double c;
if(enif_get(env, argv, "mn", &a, &c)){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i<a.n_cols*a.n_rows; i++){
d.content[i] = a.content[i] * c;
}
return matrix_to_erl(env, d);
}
else
if(enif_get(env, argv, "mm", &a, &b)
&& a.n_rows*a.n_cols == b.n_rows*b.n_cols){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i < a.n_rows*a.n_cols; i++){
d.content[i] = a.content[i] * b.content[i];
}
return matrix_to_erl(env, d);
}
return enif_make_badarg(env);
}
//Either element-wise addition, or addition of a matrix by a number.
ERL_NIF_TERM nif_add(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a,b;
double c;
if(enif_get(env, argv, "mn", &a, &c)){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i<a.n_cols*a.n_rows; i++){
d.content[i] = a.content[i] + c;
}
return matrix_to_erl(env, d);
}
else
if(enif_get(env, argv, "mm", &a, &b)
&& a.n_rows*a.n_cols == b.n_rows*b.n_cols){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i < a.n_rows*a.n_cols; i++){
d.content[i] = a.content[i] + b.content[i];
}
return matrix_to_erl(env, d);
}
return enif_make_badarg(env);
}
//Either element-wise subtraction, or subtraction of a matrix by a number.
ERL_NIF_TERM nif_sub(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a,b;
double c;
if(enif_get(env, argv, "mn", &a, &c)){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i<a.n_cols*a.n_rows; i++){
d.content[i] = a.content[i] - c;
}
return matrix_to_erl(env, d);
}
else
if(enif_get(env, argv, "mm", &a, &b)
&& a.n_rows*a.n_cols == b.n_rows*b.n_cols){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i < a.n_rows*a.n_cols; i++){
d.content[i] = a.content[i] - b.content[i];
}
return matrix_to_erl(env, d);
}
return enif_make_badarg(env);
}
//Either element-wise division, or division of a matrix by a number.
ERL_NIF_TERM nif_divide(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a,b;
double c;
if(enif_get(env, argv, "mn", &a, &c)){
if(c!=0.0){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i<a.n_cols*a.n_rows; i++){
d.content[i] = a.content[i] / c;
}
return matrix_to_erl(env, d);
}
}
else if(enif_get(env, argv, "mm", &a, &b)
&& a.n_rows*a.n_cols == b.n_rows*b.n_cols){
Matrix d = matrix_alloc(a.n_rows, a.n_cols);
for(int i = 0; i < a.n_rows*a.n_cols; i++){
if(b.content[i] == 0.0){
return enif_make_badarg(env);
}
else{
d.content[i] = a.content[i] / b.content[i];
}
}
return matrix_to_erl(env, d);
}
return enif_make_badarg(env);
}
//Transpose of a matrix.
Matrix tr(Matrix a){
Matrix result = matrix_alloc(a.n_cols ,a.n_rows);
for(int j = 0; j < a.n_rows; j++){
for(int i = 0; i < a.n_cols; i++){
result.content[i*result.n_cols+j] = a.content[j*a.n_cols+i];
}
}
return result;
}
ERL_NIF_TERM nif_transpose(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a;
if(!enif_get_matrix(env, argv[0], &a))
return enif_make_badarg(env);
return matrix_to_erl(env, tr(a));
}
//arg0: Matrix.
ERL_NIF_TERM nif_inv(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix a;
if(!enif_get_matrix(env, argv[0], &a))
return enif_make_badarg(env);
Matrix inv = matrix_dup(a);
int N = a.n_rows;
int *IPIV = enif_alloc(sizeof(int)*N);
int LWORK = N*N;
double* WORK = enif_alloc(sizeof(int)*N*N);
int INFO1, INFO2;
dgetrf_(&N,&N,inv.content,&N,IPIV,&INFO1);
dgetri_(&N,inv.content,&N,IPIV,WORK,&LWORK,&INFO2);
enif_free(IPIV);
enif_free(WORK);
ERL_NIF_TERM result;
if(INFO1 > 0 || INFO2 > 0){
result = enif_raise_exception(env, enif_make_atom(env, "nif_inv: could not invert singular matrix."));
matrix_free(inv);
}
else if(INFO1 < 0 || INFO2 < 0){
result = enif_raise_exception(env, enif_make_atom(env, "nif_inv: LAPACK error."));
matrix_free(inv);
}
else result = matrix_to_erl(env, inv);
return result;
}
//----------------------------------------------------------------------------------------------------|
// ------------------------------------------ |
// | CBLAS | |
// ------------------------------------------ |
//----------------------------------------------------------------------------------------------------|
//Some CBLAS wrappers.
//Calculates the norm of input vector/matrix, aka the square root of the sum of its composants.
ERL_NIF_TERM nif_dnrm2(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix x;
if(!enif_get(env, argv, "m", &x)){
return enif_make_badarg(env);
}
double result = cblas_dnrm2(x.n_cols*x.n_rows, x.content, 1);
return enif_make_double(env, result);
}
//Performs blas_ddot
//Input: two vectors / matrices
ERL_NIF_TERM nif_ddot(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix x,y;
if(!enif_get(env, argv, "mm", &x, &y)){
return enif_make_badarg(env);
}
int n = fmin(x.n_rows*x.n_cols, y.n_rows*y.n_cols);
if(n <= 0){
return enif_make_badarg(env);
}
double result = cblas_ddot(n, x.content, 1, y.content, 1);
return enif_make_double(env, result);
}
//Performs blas_daxpy
//Input: a number, vectors X and Y
//Output: a vector of same dimension then Y, containing alpha X + Y
//------------------------------------------------------------------------
ERL_NIF_TERM nif_daxpy(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix x,y;
int n;
double alpha;
if(!enif_get(env, argv, "inmm", &n, &alpha, &x, &y)){
return enif_make_badarg(env);
}
if(fmin(x.n_rows, x.n_cols) * fmin(y.n_rows, y.n_cols) != 1){
//We are not using vectors...
return enif_make_badarg(env);
}
Matrix ny = matrix_dup(y);
cblas_daxpy(n, alpha, x.content, 1, ny.content, 1);
return matrix_to_erl(env, ny);
}
// Arguments: alpha, A, x, beta, y
// Performs alpha*A*x + beta*y.
// alpha, beta are numbers
// A, x, y are matrices (x and y being vectors)
// x and y are expected to have a length of A.n_cols
ERL_NIF_TERM nif_dgemv(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix A,x,y;
double alpha, beta;
if(!enif_get(env, argv, "nmmnm", &alpha, &A, &x, &beta, &y)){
enif_make_badarg(env);
}
//Check dimensions compatibility
int vec_length = fmin(fmax(x.n_cols, x.n_rows), fmax(y.n_cols, y.n_rows));
if(vec_length < A.n_cols || fmin(x.n_cols, x.n_rows) != 1 || fmin(y.n_cols, y.n_rows) != 1){
enif_make_badarg(env);
}
Matrix ny = matrix_dup(y);
cblas_dgemv(CblasRowMajor, CblasNoTrans, A.n_rows, A.n_cols, alpha, A.content, A.n_rows, x.content, 1, beta, ny.content, 1);
return matrix_to_erl(env, ny);
}
//Arguments: double alpha, matrix A, matrix B, double beta, matrix C
ERL_NIF_TERM nif_dgemm(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){
Matrix A, B;
double alpha = 1.0;
double beta = 0.0;
if(!enif_get(env, argv, "mm", &A, &B)
|| A.n_cols != B.n_rows){
return enif_make_badarg(env);
}
Matrix C = matrix_alloc(A.n_rows, B.n_cols);
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
A.n_rows, B.n_cols, A.n_cols,
alpha, A.content, A.n_cols, B.content, B.n_rows,
1.0, C.content, C.n_cols);
return matrix_to_erl(env, C);
}
ErlNifFunc nif_funcs[] = {
{"matrix", 1, nif_matrix},
{"get", 3, nif_get},
{"at", 2, nif_at},
{"mtfli", 1, nif_mtfli},
{"mtfl", 1, nif_mtfl},
{"equals", 2, nif_equals},
{"row", 2, nif_row},
{"col", 2, nif_col},
{"zeros", 2, nif_zeros},
{"eye", 1, nif_eye},
{"mult", 2, nif_mult},
{"add", 2, nif_add},
{"sub", 2, nif_sub},
{"divide", 2, nif_divide},
{"transpose", 1, nif_transpose},
{"inv", 1, nif_inv},
//--- BLAS----------
{"nrm2", 1, nif_dnrm2},
{"vec_dot", 2, nif_ddot},
{"dot", 2, nif_dgemm}
};
ERL_NIF_INIT(numerl, nif_funcs, load, NULL, upgrade, NULL) | 28.386889 | 129 | 0.547476 | [
"vector"
] |
d0ebb205b6f4fadec1eb9877a8d1f5a8a501866d | 174,443 | c | C | code/plugins/Display/android/orxDisplay.c | corollari/orx | 209df0c782cdda4678ad5857c14fd7c063106d30 | [
"Zlib"
] | 1 | 2019-11-03T14:54:03.000Z | 2019-11-03T14:54:03.000Z | code/plugins/Display/android/orxDisplay.c | corollari/orx | 209df0c782cdda4678ad5857c14fd7c063106d30 | [
"Zlib"
] | null | null | null | code/plugins/Display/android/orxDisplay.c | corollari/orx | 209df0c782cdda4678ad5857c14fd7c063106d30 | [
"Zlib"
] | null | null | null | /* Orx - Portable Game Engine
*
* Copyright (c) 2008-2019 Orx-Project
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
/**
* @file orxDisplay.c
* @date 13/01/2011
* @author simons.philippe@gmail.com
*
* Android display plugin implementation
*
* @todo
*/
#include "orxPluginAPI.h"
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include "main/orxAndroid.h"
#include <sys/endian.h>
#include "webp/decode.h"
#define STBI_NO_STDIO
#define STB_IMAGE_IMPLEMENTATION
#define STBI_NO_PSD
#define STBI_NO_GIF
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_PNM
#define STBI_MALLOC(sz) orxMemory_Allocate((orxU32)sz, orxMEMORY_TYPE_VIDEO)
#define STBI_REALLOC(p, newsz) orxMemory_Reallocate(p, newsz)
#define STBI_FREE(p) orxMemory_Free(p)
#include "stb_image.h"
#undef STBI_FREE
#undef STBI_REALLOC
#undef STBI_MALLOC
#undef STBI_NO_PNM
#undef STBI_NO_PIC
#undef STBI_NO_HDR
#undef STBI_NO_GIF
#undef STBI_NO_PSD
#undef STB_IMAGE_IMPLEMENTATION
#undef STBI_NO_STDIO
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STBIW_MALLOC(sz) orxMemory_Allocate(sz, orxMEMORY_TYPE_VIDEO)
#define STBIW_REALLOC(p, newsz) orxMemory_Reallocate(p, newsz)
#define STBIW_FREE(p) orxMemory_Free(p)
#define STBIW_MEMMOVE(a, b, sz) orxMemory_Move(a, b, sz)
#include "stb_image_write.h"
#undef STBIW_MEMMOVE
#undef STBIW_FREE
#undef STBIW_REALLOC
#undef STBIW_MALLOC
#undef STB_IMAGE_WRITE_IMPLEMENTATION
/** Module flags
*/
#define orxDISPLAY_KU32_STATIC_FLAG_NONE 0x00000000 /**< No flags */
#define orxDISPLAY_KU32_STATIC_FLAG_READY 0x00000001 /**< Ready flag */
#define orxDISPLAY_KU32_STATIC_FLAG_SHADER 0x00000002 /**< Shader support flag */
#define orxDISPLAY_KU32_STATIC_FLAG_DEPTHBUFFER 0x00000004 /**< Has depth buffer support flag */
#define orxDISPLAY_KU32_STATIC_FLAG_CUSTOM_IBO 0x00000008 /**< Custom IBO flag */
#define orxDISPLAY_KU32_STATIC_MASK_ALL 0xFFFFFFFF /**< All mask */
#define orxDISPLAY_KU32_BITMAP_FLAG_NONE 0x00000000 /** No flags */
#define orxDISPLAY_KU32_BITMAP_FLAG_LOADING 0x00000001 /**< Loading flag */
#define orxDISPLAY_KU32_BITMAP_FLAG_DELETE 0x00000002 /**< Delete flag */
#define orxDISPLAY_KU32_BITMAP_MASK_ALL 0xFFFFFFFF /**< All mask */
#define orxDISPLAY_KU32_BITMAP_BANK_SIZE 128
#define orxDISPLAY_KU32_SHADER_BANK_SIZE 16
#define orxDISPLAY_KU32_VERTEX_BUFFER_SIZE (4 * 16384) /**< 16384 items batch capacity */
#define orxDISPLAY_KU32_INDEX_BUFFER_SIZE (6 * 16384) /**< 16384 items batch capacity */
#define orxDISPLAY_KU32_SHADER_BUFFER_SIZE 131072
#define orxDISPLAY_KF_BORDER_FIX 0.1f
#define orxDISPLAY_KU32_CIRCLE_LINE_NUMBER 32
#define orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER 32
#define orxDISPLAY_KE_DEFAULT_PRIMITIVE GL_TRIANGLE_STRIP
/** Misc defines
*/
#define glUNIFORM(EXT, LOCATION, ...) do {if((LOCATION) >= 0) {glUniform##EXT(LOCATION, ##__VA_ARGS__); glASSERT();}} while(orxFALSE)
#ifdef __orxDEBUG__
#define glASSERT() \
do \
{ \
GLenum eError = glGetError(); \
orxASSERT(eError == GL_NO_ERROR && "OpenGL error code: 0x%X", eError);\
} while(orxFALSE)
#define eglASSERT() \
do \
{ \
EGLint eError = eglGetError(); \
orxASSERT(eError == EGL_SUCCESS && "EGL error code: 0x%X", eError); \
} while(orxFALSE)
#define glUNIFORM_NO_ASSERT(EXT, LOCATION, ...) do {if((LOCATION) >= 0) {glUniform##EXT(LOCATION, ##__VA_ARGS__); glGetError();}} while(orxFALSE)
#else /* __orxDEBUG__ */
#define glASSERT()
#define eglASSERT()
#define glUNIFORM_NO_ASSERT(EXT, LOCATION, ...) do {if((LOCATION) >= 0) {glUniform##EXT(LOCATION, ##__VA_ARGS__);}} while(orxFALSE)
#endif /* __orxDEBUG__ */
/***************************************************************************
* Structure declaration *
***************************************************************************/
typedef enum __orxDISPLAY_ATTRIBUTE_LOCATION_t
{
orxDISPLAY_ATTRIBUTE_LOCATION_VERTEX = 0,
orxDISPLAY_ATTRIBUTE_LOCATION_TEXCOORD,
orxDISPLAY_ATTRIBUTE_LOCATION_COLOR,
orxDISPLAY_ATTRIBUTE_LOCATION_NUMBER,
orxDISPLAY_ATTRIBUTE_LOCATION_NONE = orxENUM_NONE
} orxDISPLAY_ATTRIBUTE_LOCATION;
/** Internal buffer mode
*/
typedef enum __orxDISPLAY_BUFFER_MODE_t
{
orxDISPLAY_BUFFER_MODE_INDIRECT = 0,
orxDISPLAY_BUFFER_MODE_DIRECT,
orxDISPLAY_BUFFER_MODE_NUMBER,
orxDISPLAY_BUFFER_MODE_NONE = orxENUM_NONE
} orxDISPLAY_BUFFER_MODE;
/** Internal matrix structure
*/
typedef struct __orxDISPLAY_MATRIX_t
{
orxVECTOR vX;
orxVECTOR vY;
} orxDISPLAY_MATRIX;
/** Internal vertex structure
*/
typedef struct __orxDISPLAY_ANDROID_VERTEX_t
{
GLfloat fX, fY;
GLfloat fU, fV;
orxRGBA stRGBA;
} orxDISPLAY_ANDROID_VERTEX;
/** Internal projection matrix structure
*/
typedef struct __orxDISPLAY_PROJ_MATRIX_t
{
orxFLOAT aafValueList[4][4];
} orxDISPLAY_PROJ_MATRIX;
/** Internal bitmap structure
*/
struct __orxBITMAP_t
{
GLuint uiTexture;
orxBOOL bSmoothing;
orxFLOAT fWidth, fHeight;
orxAABOX stClip;
orxU32 u32RealWidth, u32RealHeight, u32Depth;
orxFLOAT fRecRealWidth, fRecRealHeight;
orxU32 u32DataSize;
const orxSTRING zLocation;
orxSTRINGID stFilenameID;
orxU32 u32Flags;
};
/** Internal bitmap save info structure
*/
typedef struct __orxDISPLAY_SAVE_INFO_t
{
orxU8 *pu8ImageData;
orxU32 u32Width;
orxU32 u32Height;
orxSTRINGID stFilenameID;
} orxDISPLAY_SAVE_INFO;
/** Internal bitmap load info structure
*/
typedef struct __orxDISPLAY_LOAD_INFO_t
{
orxU8 *pu8ImageBuffer;
orxU8 *pu8ImageSource;
orxS64 s64Size;
orxBITMAP *pstBitmap;
GLuint uiWidth;
GLuint uiHeight;
GLuint uiRealWidth;
GLuint uiRealHeight;
} orxDISPLAY_LOAD_INFO;
/** Internal texture info structure
*/
typedef struct __orxDISPLAY_TEXTURE_INFO_t
{
GLint iLocation;
const orxBITMAP *pstBitmap;
} orxDISPLAY_TEXTURE_INFO;
/** Internal param info structure
*/
typedef struct __orxDISPLAY_PARAM_INFO_t
{
GLint iLocation, iLocationTop, iLocationLeft, iLocationBottom, iLocationRight;
} orxDISPLAY_PARAM_INFO;
/** Internal shader structure
*/
typedef struct __orxDISPLAY_SHADER_t
{
orxLINKLIST_NODE stNode;
GLuint uiProgram;
GLint iTextureLocation;
GLint iProjectionMatrixLocation;
GLint iTextureCount;
orxS32 s32ParamCount;
orxBOOL bPending;
orxBOOL bUseCustomParam;
orxSTRING zCode;
orxDISPLAY_TEXTURE_INFO *astTextureInfoList;
orxDISPLAY_PARAM_INFO *astParamInfoList;
} orxDISPLAY_SHADER;
/** Static structure
*/
typedef struct __orxDISPLAY_STATIC_t
{
orxBANK *pstBitmapBank;
orxBANK *pstShaderBank;
orxLINKLIST stActiveShaderList;
orxBOOL bDefaultSmoothing;
orxBITMAP *pstScreen;
const orxBITMAP *pstTempBitmap;
orxRGBA stLastColor;
orxU32 u32LastClipX, u32LastClipY, u32LastClipWidth, u32LastClipHeight;
orxDISPLAY_BLEND_MODE eLastBlendMode;
orxDISPLAY_BUFFER_MODE eLastBufferMode;
GLenum ePrimitive;
orxS32 s32PendingShaderCount;
GLint iLastViewportX, iLastViewportY;
GLsizei iLastViewportWidth, iLastViewportHeight;
orxFLOAT fLastOrthoRight, fLastOrthoBottom;
orxDISPLAY_SHADER *pstDefaultShader;
orxDISPLAY_SHADER *pstNoTextureShader;
GLint iTextureUnitNumber;
GLint iDrawBufferNumber;
orxU32 u32DestinationBitmapCount;
GLuint uiFrameBuffer;
GLuint uiLastFrameBuffer;
GLuint uiVertexBuffer;
GLuint uiIndexBuffer;
orxS32 s32BufferIndex;
orxS32 s32ElementNumber;
orxU32 u32Flags;
orxU32 u32Depth;
orxS32 s32ActiveTextureUnit;
stbi_io_callbacks stSTBICallbacks;
GLenum aeDrawBufferList[orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER];
orxBITMAP *apstDestinationBitmapList[orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER];
const orxBITMAP *apstBoundBitmapList[orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER];
orxDOUBLE adMRUBitmapList[orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER];
orxDISPLAY_PROJ_MATRIX mProjectionMatrix;
orxDISPLAY_ANDROID_VERTEX astVertexList[orxDISPLAY_KU32_VERTEX_BUFFER_SIZE];
GLushort au16IndexList[orxDISPLAY_KU32_INDEX_BUFFER_SIZE];
orxCHAR acShaderCodeBuffer[orxDISPLAY_KU32_SHADER_BUFFER_SIZE];
EGLDisplay display;
EGLConfig config;
EGLSurface surface;
EGLContext context;
EGLint format;
} orxDISPLAY_STATIC;
/** KTX header
*/
typedef struct KTX_header_t {
orxU8 identifier[12];
orxU32 endianness;
orxU32 glType;
orxU32 glTypeSize;
orxU32 glFormat;
orxU32 glInternalFormat;
orxU32 glBaseInternalFormat;
orxU32 pixelWidth;
orxU32 pixelHeight;
orxU32 pixelDepth;
orxU32 numberOfArrayElements;
orxU32 numberOfFaces;
orxU32 numberOfMipmapLevels;
orxU32 bytesOfKeyValueData;
} KTX_header;
/* KTX files require an unpack alignment of 4 */
#define KTX_GL_UNPACK_ALIGNMENT 4
static int getKTXInfos(orxHANDLE _hResource, int *x, int *y)
{
KTX_header stHeader;
/* Loads KTX header from file */
if(orxResource_Read(_hResource, sizeof(KTX_header), &stHeader, orxNULL, orxNULL) == sizeof(KTX_header))
{
*x = stHeader.pixelWidth;
*y = stHeader.pixelHeight;
return 1;
}
return 0;
}
/***************************************************************************
* Static variables *
***************************************************************************/
/** Static data
*/
static orxDISPLAY_STATIC sstDisplay;
static const orxSTRING szKTXExtention = ".ktx";
/** Prototypes
*/
orxSTATUS orxFASTCALL orxDisplay_Android_StartShader(orxHANDLE _hShader);
orxSTATUS orxFASTCALL orxDisplay_Android_StopShader(orxHANDLE _hShader);
orxSTATUS orxFASTCALL orxDisplay_Android_SetBlendMode(orxDISPLAY_BLEND_MODE _eBlendMode);
orxSTATUS orxFASTCALL orxDisplay_Android_SetDestinationBitmaps(orxBITMAP **_apstBitmapList, orxU32 _u32Number);
orxSTATUS orxFASTCALL orxDisplay_Android_SetVideoMode(const orxDISPLAY_VIDEO_MODE *_pstVideoMode);
#define GL_MAX_DRAW_BUFFERS 0x8824
void (* glDrawBuffers) (GLsizei n, const GLenum* bufs);
static orxBOOL gl3stubInit()
{
glDrawBuffers = (void (*)(GLsizei, const GLenum*)) eglGetProcAddress("glDrawBuffers");
return glDrawBuffers != orxNULL ? orxTRUE : orxFALSE;
}
static EGLConfig defaultEGLChooser(EGLDisplay disp)
{
EGLint count = 0;
EGLConfig bestConfig = orxNULL;
eglGetConfigs(disp, NULL, 0, &count);
eglASSERT();
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Config count = %d", count);
EGLConfig* configs = new EGLConfig[count];
eglGetConfigs(disp, configs, count, &count);
eglASSERT();
int bestMatch = 1<<30;
int minDepthBits = orxFLAG_TEST(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_DEPTHBUFFER) ? 16 : 0;
int minRedBits = sstDisplay.u32Depth == 16 ? 5 : 8;
int minGreenBits = sstDisplay.u32Depth == 16 ? 6 : 8;
int minBlueBits = sstDisplay.u32Depth == 16 ? 5 : 8;
int i;
for (i = 0; i < count; i++)
{
int match = 0;
EGLint surfaceType = 0;
EGLint blueBits = 0;
EGLint greenBits = 0;
EGLint redBits = 0;
EGLint alphaBits = 0;
EGLint depthBits = 0;
EGLint stencilBits = 0;
EGLint renderableFlags = 0;
eglGetConfigAttrib(disp, configs[i], EGL_SURFACE_TYPE, &surfaceType);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_BLUE_SIZE, &blueBits);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_GREEN_SIZE, &greenBits);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_RED_SIZE, &redBits);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_ALPHA_SIZE, &alphaBits);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_DEPTH_SIZE, &depthBits);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_STENCIL_SIZE, &stencilBits);
eglASSERT();
eglGetConfigAttrib(disp, configs[i], EGL_RENDERABLE_TYPE, &renderableFlags);
eglASSERT();
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Config[%d]: R%dG%dB%dA%d D%dS%d Type=%04x Render=%04x",
i, redBits, greenBits, blueBits, alphaBits, depthBits, stencilBits, surfaceType, renderableFlags);
if ((surfaceType & EGL_WINDOW_BIT) == 0)
continue;
if ((renderableFlags & EGL_OPENGL_ES2_BIT) == 0)
continue;
if (depthBits < minDepthBits)
continue;
if ((redBits < minRedBits) || (greenBits < minGreenBits) || (blueBits < minBlueBits))
continue;
int penalty = depthBits - minDepthBits;
match += penalty * penalty;
penalty = redBits - minRedBits;
match += penalty * penalty;
penalty = greenBits - minGreenBits;
match += penalty * penalty;
penalty = blueBits - minBlueBits;
match += penalty * penalty;
penalty = alphaBits;
match += penalty * penalty;
penalty = stencilBits;
match += penalty * penalty;
if ((match < bestMatch) || (bestConfig == orxNULL))
{
bestMatch = match;
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Config[%d] is the new best config", i);
bestConfig = configs[i];
}
}
delete[] configs;
return bestConfig;
}
/** Render inhibitor
*/
static orxSTATUS orxFASTCALL orxDisplay_Android_RenderInhibitor(const orxEVENT *_pstEvent)
{
/* Done! */
return orxSTATUS_FAILURE;
}
static orxSTATUS orxAndroid_Display_CreateSurface()
{
orxSTATUS eResult = orxSTATUS_FAILURE;
if (sstDisplay.surface == EGL_NO_SURFACE)
{
orxU32 u32Width, u32Height;
int32_t windowWidth, windowHeight;
orxFLOAT fScale;
ANativeWindow *window = orxAndroid_GetNativeWindow();
if(!window)
{
return orxSTATUS_FAILURE;
}
windowWidth = ANativeWindow_getWidth(window);
windowHeight = ANativeWindow_getHeight(window);
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "native windows size: (%dx%d)", windowWidth, windowHeight);
if(windowWidth > 0 && windowHeight > 0)
{
/* default to native window size */
u32Width = windowWidth;
u32Height = windowHeight;
fScale = orxFLOAT_1;
/* Pushes config section */
orxConfig_PushSection(orxDISPLAY_KZ_CONFIG_SECTION);
/* Has ScreenWidth? */
if (orxConfig_HasValue(orxDISPLAY_KZ_CONFIG_WIDTH))
{
orxU32 u32ConfigWidth;
u32ConfigWidth = orxConfig_GetU32(orxDISPLAY_KZ_CONFIG_WIDTH);
if ( windowWidth > u32ConfigWidth )
{
u32Width = u32ConfigWidth;
fScale = orx2F(u32Width) / orx2F(windowWidth);
u32Height = windowHeight * fScale;
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "scaled windows size: (%dx%d)", u32Width, u32Height);
}
if(orxConfig_HasValue(orxDISPLAY_KZ_CONFIG_HEIGHT))
{
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "WARNING, Display.ScreenHeight ignored.");
}
}
else
/* Has ScreenHeight? */
if (orxConfig_HasValue(orxDISPLAY_KZ_CONFIG_HEIGHT))
{
orxU32 u32ConfigHeight;
u32ConfigHeight = orxConfig_GetU32(orxDISPLAY_KZ_CONFIG_HEIGHT);
if ( windowHeight > u32ConfigHeight )
{
u32Height = u32ConfigHeight;
fScale = orx2F(u32Height) / orx2F(windowHeight);
u32Width = windowWidth * fScale;
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "scaled windows size: (%dx%d)", u32Width, u32Height);
}
}
/* Updates ScreenHeight value */
orxConfig_SetU32(orxDISPLAY_KZ_CONFIG_HEIGHT, u32Height);
/* Updates ScreenWidth value */
orxConfig_SetU32(orxDISPLAY_KZ_CONFIG_WIDTH, u32Width);
/* Pops config section */
orxConfig_PopSection();
/* Pushes config section */
orxConfig_PushSection(KZ_CONFIG_ANDROID);
/* Save scaling */
orxConfig_SetFloat(KZ_CONFIG_SURFACE_SCALE, fScale);
/* Pops config section */
orxConfig_PopSection();
/* Set framebuffer size */
ANativeWindow_setBuffersGeometry(window, u32Width, u32Height, sstDisplay.format);
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Creating new EGL Surface");
sstDisplay.surface = eglCreateWindowSurface(sstDisplay.display, sstDisplay.config, window, NULL);
eglASSERT();
eglMakeCurrent(sstDisplay.display, sstDisplay.surface, sstDisplay.surface, sstDisplay.context);
eglASSERT();
/* Removes render inhibitor */
orxEvent_RemoveHandler(orxEVENT_TYPE_RENDER, orxDisplay_Android_RenderInhibitor);
eResult = orxSTATUS_SUCCESS;
}
}
return eResult;
}
static void orxAndroid_Display_DestroySurface()
{
eglMakeCurrent(sstDisplay.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglASSERT();
if( sstDisplay.surface != EGL_NO_SURFACE )
{
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Destroying EGL Surface");
eglDestroySurface(sstDisplay.display, sstDisplay.surface);
eglASSERT();
sstDisplay.surface = EGL_NO_SURFACE;
/* Adds render inhibitor */
orxEvent_AddHandler(orxEVENT_TYPE_RENDER, orxDisplay_Android_RenderInhibitor);
}
}
static void orxAndroid_Display_CreateContext()
{
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Creating new EGL Context");
sstDisplay.display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglASSERT();
orxASSERT(sstDisplay.display != EGL_NO_DISPLAY);
eglInitialize(sstDisplay.display, 0, 0);
eglASSERT();
sstDisplay.config = defaultEGLChooser(sstDisplay.display);
orxASSERT(sstDisplay.config != orxNULL);
eglGetConfigAttrib(sstDisplay.display, sstDisplay.config, EGL_NATIVE_VISUAL_ID, &sstDisplay.format);
eglASSERT();
EGLint contextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
sstDisplay.context = eglCreateContext(sstDisplay.display, sstDisplay.config, EGL_NO_CONTEXT, contextAttrs);
eglASSERT();
orxASSERT(sstDisplay.context != EGL_NO_CONTEXT);
}
static orxDISPLAY_PROJ_MATRIX *orxDisplay_Android_OrthoProjMatrix(orxDISPLAY_PROJ_MATRIX *_pmResult, orxFLOAT _fLeft, orxFLOAT _fRight, orxFLOAT _fBottom, orxFLOAT _fTop, orxFLOAT _fNear, orxFLOAT _fFar)
{
orxFLOAT fDeltaX, fDeltaY, fDeltaZ;
orxDISPLAY_PROJ_MATRIX *pmResult;
/* Checks */
orxASSERT(_pmResult != orxNULL);
/* Gets deltas */
fDeltaX = _fRight - _fLeft;
fDeltaY = _fTop - _fBottom;
fDeltaZ = _fFar - _fNear;
/* Valid? */
if((fDeltaX != orxFLOAT_0) && (fDeltaY != orxFLOAT_0) && (fDeltaZ != orxFLOAT_0))
{
/* Clears matrix */
orxMemory_Zero(_pmResult, sizeof(orxDISPLAY_PROJ_MATRIX));
/* Updates result */
_pmResult->aafValueList[0][0] = orx2F(2.0f) / fDeltaX;
_pmResult->aafValueList[3][0] = -(_fRight + _fLeft) / fDeltaX;
_pmResult->aafValueList[1][1] = orx2F(2.0f) / fDeltaY;
_pmResult->aafValueList[3][1] = -(_fTop + _fBottom) / fDeltaY;
_pmResult->aafValueList[2][2] = orx2F(-2.0f) / fDeltaZ;
_pmResult->aafValueList[3][2] = -(_fNear + _fFar) / fDeltaZ;
_pmResult->aafValueList[3][3] = orxFLOAT_1;
pmResult = _pmResult;
}
else
{
/* Updates result */
pmResult = orxNULL;
}
/* Done! */
return pmResult;
}
static orxINLINE void orxDisplay_Android_BindBitmap(const orxBITMAP *_pstBitmap)
{
orxDOUBLE dBestTime;
orxS32 i, s32BestCandidate;
/* For all texture units */
for(i = 0, s32BestCandidate = -1, dBestTime = orxDOUBLE_MAX; i < (orxS32)sstDisplay.iTextureUnitNumber; i++)
{
/* Found? */
if(sstDisplay.apstBoundBitmapList[i] == _pstBitmap)
{
/* Stops */
break;
}
/* Is first empty? */
else if((dBestTime != orxDOUBLE_0) && (sstDisplay.apstBoundBitmapList[i] == orxNULL))
{
/* Selects it */
s32BestCandidate = i;
dBestTime = orxDOUBLE_0;
}
/* Older candidate? */
else if(sstDisplay.adMRUBitmapList[i] < dBestTime)
{
/* Selects it */
s32BestCandidate = i;
dBestTime = sstDisplay.adMRUBitmapList[i];
}
}
/* Found? */
if(i < (orxS32)sstDisplay.iTextureUnitNumber)
{
/* Selects unit */
glActiveTexture(GL_TEXTURE0 + i);
glASSERT();
/* Updates MRU timestamp */
sstDisplay.adMRUBitmapList[i] = orxSystem_GetSystemTime();
/* Updates active texture unit */
sstDisplay.s32ActiveTextureUnit = i;
}
else
{
/* Selects unit */
glActiveTexture(GL_TEXTURE0 + s32BestCandidate);
glASSERT();
/* Binds texture */
glBindTexture(GL_TEXTURE_2D, _pstBitmap->uiTexture);
glASSERT();
/* Stores texture */
sstDisplay.apstBoundBitmapList[s32BestCandidate] = _pstBitmap;
/* Updates MRU timestamp */
sstDisplay.adMRUBitmapList[s32BestCandidate] = orxSystem_GetSystemTime();
/* Updates active texture unit */
sstDisplay.s32ActiveTextureUnit = s32BestCandidate;
}
/* Done! */
return;
}
static int orxDisplay_Android_ReadSTBICallback(void *_hResource, char *_pBuffer, int _iSize)
{
/* Reads data */
return (int)orxResource_Read((orxHANDLE)_hResource, _iSize, (orxU8 *)_pBuffer, orxNULL, orxNULL);
}
static void orxDisplay_Android_SkipSTBICallback(void *_hResource, int _iOffset)
{
/* Seeks offset */
orxResource_Seek((orxHANDLE)_hResource, _iOffset, orxSEEK_OFFSET_WHENCE_CURRENT);
/* Done! */
return;
}
static int orxDisplay_Android_EOFSTBICallback(void *_hResource)
{
/* End of buffer? */
return (orxResource_Tell((orxHANDLE)_hResource) == orxResource_GetSize(_hResource)) ? 1 : 0;
}
static void orxFASTCALL orxDisplay_Android_ReadKTXResourceCallback(orxHANDLE _hResource, orxS64 _s64Size, void *_pBuffer, void *_pContext)
{
orxDISPLAY_EVENT_PAYLOAD stPayload;
orxBITMAP *pstBitmap;
/* Gets associated bitmap */
pstBitmap = (orxBITMAP *)_pContext;
/* Inits payload */
stPayload.stBitmap.zLocation = pstBitmap->zLocation;
stPayload.stBitmap.stFilenameID = pstBitmap->stFilenameID;
stPayload.stBitmap.u32ID = orxU32_UNDEFINED;
if(_s64Size >= sizeof(KTX_header))
{
KTX_header *stHeader;
orxU8 *pu8ImageData;
orxBOOL bCompressed = orxFALSE;
GLint previousUnpackAlignment;
GLuint uiWidth, uiHeight;
GLenum eInternalFormat;
stHeader = (KTX_header*)_pBuffer;
uiWidth = stHeader->pixelWidth;
uiHeight = stHeader->pixelHeight;
/* Check glType and glFormat */
if(stHeader->glType == 0 || stHeader->glFormat == 0)
{
orxASSERT(stHeader->glType + stHeader->glFormat == 0 && "Can't load KTX texture <%s>: either both or none of glType, glFormat must be zero, aborting.", pstBitmap->zLocation);
bCompressed = orxTRUE;
}
/* KTX files require an unpack alignment of 4 */
glGetIntegerv(GL_UNPACK_ALIGNMENT, &previousUnpackAlignment);
if(previousUnpackAlignment != KTX_GL_UNPACK_ALIGNMENT)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, KTX_GL_UNPACK_ALIGNMENT);
}
if(bCompressed == orxTRUE)
{
eInternalFormat = stHeader->glInternalFormat;
}
else
{
eInternalFormat = stHeader->glBaseInternalFormat;
}
/* Loads image */
pu8ImageData = (orxU8 *)_pBuffer;
if(_s64Size >= sizeof(KTX_header) + stHeader->bytesOfKeyValueData)
{
orxU32 u32DataSize, u32RoundedDataSize;
GLuint uiRealWidth, uiRealHeight;
orxS32 i;
orxU8 *pu8ImageBuffer;
/* Skip header */
pu8ImageData = (orxU8 *)(pu8ImageData + sizeof(KTX_header) + stHeader->bytesOfKeyValueData);
u32DataSize = *((orxU32 *)pu8ImageData);
u32RoundedDataSize = orxALIGN(u32DataSize, 4);
/* Uses image buffer */
pu8ImageBuffer = pu8ImageData + sizeof(u32DataSize);
/* Gets real size */
uiRealWidth = uiWidth;
uiRealHeight = uiHeight;
/* Inits bitmap */
pstBitmap->fWidth = orxU2F(uiWidth);
pstBitmap->fHeight = orxU2F(uiHeight);
pstBitmap->u32RealWidth = (orxU32)uiRealWidth;
pstBitmap->u32RealHeight = (orxU32)uiRealHeight;
pstBitmap->u32Depth = 32;
pstBitmap->fRecRealWidth = orxFLOAT_1 / orxU2F(pstBitmap->u32RealWidth);
pstBitmap->fRecRealHeight = orxFLOAT_1 / orxU2F(pstBitmap->u32RealHeight);
pstBitmap->u32DataSize = u32RoundedDataSize;
orxVector_Copy(&(pstBitmap->stClip.vTL), &orxVECTOR_0);
orxVector_Set(&(pstBitmap->stClip.vBR), pstBitmap->fWidth, pstBitmap->fHeight, orxFLOAT_0);
/* Tracks video memory */
orxMEMORY_TRACK(VIDEO, pstBitmap->u32DataSize, orxTRUE);
/* Creates new texture */
glGenTextures(1, &pstBitmap->uiTexture);
glASSERT();
glBindTexture(GL_TEXTURE_2D, pstBitmap->uiTexture);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
/* Compressed? */
if(bCompressed == orxTRUE)
{
/* Loads compressed data */
glCompressedTexImage2D(GL_TEXTURE_2D, 0, eInternalFormat, (GLsizei)pstBitmap->u32RealWidth, (GLsizei)pstBitmap->u32RealHeight, 0, u32DataSize, pu8ImageBuffer);
}
else
{
/* Loads data */
glTexImage2D(GL_TEXTURE_2D, 0, eInternalFormat, (GLsizei)pstBitmap->u32RealWidth, (GLsizei)pstBitmap->u32RealHeight, 0, stHeader->glFormat, stHeader->glType, pu8ImageBuffer);
}
glASSERT();
/* Restores previous texture */
glBindTexture(GL_TEXTURE_2D, (sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] != orxNULL) ? sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit]->uiTexture : 0);
glASSERT();
/* For all bound bitmaps */
for(i = 0; i < (orxS32)sstDisplay.iTextureUnitNumber; i++)
{
/* Is deleted bitmap? */
if(sstDisplay.apstBoundBitmapList[i] == pstBitmap)
{
/* Resets it */
sstDisplay.apstBoundBitmapList[i] = orxNULL;
sstDisplay.adMRUBitmapList[i] = orxDOUBLE_0;
}
}
/* Updates payload */
stPayload.stBitmap.u32ID = (orxU32)pstBitmap->uiTexture;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_DISPLAY, orxDISPLAY_EVENT_LOAD_BITMAP, pstBitmap, orxNULL, &stPayload);
/* Clears loading flag */
orxFLAG_SET(pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_NONE, orxDISPLAY_KU32_BITMAP_FLAG_LOADING);
orxMEMORY_BARRIER();
}
else
{
/* Clears info */
pstBitmap->fWidth =
pstBitmap->fHeight = orxFLOAT_1;
pstBitmap->u32RealWidth =
pstBitmap->u32RealHeight = 1;
/* Creates new texture */
glGenTextures(1, &pstBitmap->uiTexture);
glASSERT();
glBindTexture(GL_TEXTURE_2D, pstBitmap->uiTexture);
glASSERT();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)pstBitmap->u32RealWidth, (GLsizei)pstBitmap->u32RealHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't process data for bitmap <%s>: temp texture will remain in use.", pstBitmap->zLocation);
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_DISPLAY, orxDISPLAY_EVENT_LOAD_BITMAP, pstBitmap, orxNULL, &stPayload);
/* Clears loading flag */
orxFLAG_SET(pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_NONE, orxDISPLAY_KU32_BITMAP_FLAG_LOADING);
}
if(previousUnpackAlignment != KTX_GL_UNPACK_ALIGNMENT)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, previousUnpackAlignment);
}
}
else
{
/* Clears info */
pstBitmap->fWidth =
pstBitmap->fHeight = orxFLOAT_1;
pstBitmap->u32RealWidth =
pstBitmap->u32RealHeight = 1;
/* Creates new texture */
glGenTextures(1, &pstBitmap->uiTexture);
glASSERT();
glBindTexture(GL_TEXTURE_2D, pstBitmap->uiTexture);
glASSERT();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)pstBitmap->u32RealWidth, (GLsizei)pstBitmap->u32RealHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't process data for bitmap <%s>: temp texture will remain in use.", pstBitmap->zLocation);
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_DISPLAY, orxDISPLAY_EVENT_LOAD_BITMAP, pstBitmap, orxNULL, &stPayload);
/* Clears loading flag */
orxFLAG_SET(pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_NONE, orxDISPLAY_KU32_BITMAP_FLAG_LOADING);
}
/* Asked for deletion? */
if(orxFLAG_TEST(pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_DELETE))
{
/* Deletes it */
orxDisplay_DeleteBitmap(pstBitmap);
}
/* Frees buffer */
orxMemory_Free(_pBuffer);
/* Closes resource */
orxResource_Close(_hResource);
}
static orxSTATUS orxFASTCALL orxDisplay_Android_DecompressBitmapCallback(void *_pContext)
{
orxDISPLAY_LOAD_INFO *pstInfo;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Gets load info */
pstInfo = (orxDISPLAY_LOAD_INFO *)_pContext;
/* Hasn't exited yet? */
if(sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY)
{
orxDISPLAY_EVENT_PAYLOAD stPayload;
orxU32 i;
/* Inits bitmap */
pstInfo->pstBitmap->fWidth = orxU2F(pstInfo->uiWidth);
pstInfo->pstBitmap->fHeight = orxU2F(pstInfo->uiHeight);
pstInfo->pstBitmap->u32RealWidth = (orxU32)pstInfo->uiRealWidth;
pstInfo->pstBitmap->u32RealHeight = (orxU32)pstInfo->uiRealHeight;
pstInfo->pstBitmap->u32Depth = 32;
pstInfo->pstBitmap->fRecRealWidth = orxFLOAT_1 / orxU2F(pstInfo->pstBitmap->u32RealWidth);
pstInfo->pstBitmap->fRecRealHeight = orxFLOAT_1 / orxU2F(pstInfo->pstBitmap->u32RealHeight);
pstInfo->pstBitmap->u32DataSize = pstInfo->pstBitmap->u32RealWidth * pstInfo->pstBitmap->u32RealHeight * 4 * sizeof(orxU8);
orxVector_Copy(&(pstInfo->pstBitmap->stClip.vTL), &orxVECTOR_0);
orxVector_Set(&(pstInfo->pstBitmap->stClip.vBR), pstInfo->pstBitmap->fWidth, pstInfo->pstBitmap->fHeight, orxFLOAT_0);
/* Tracks video memory */
orxMEMORY_TRACK(VIDEO, pstInfo->pstBitmap->u32DataSize, orxTRUE);
/* Creates new texture */
glGenTextures(1, &(pstInfo->pstBitmap->uiTexture));
glASSERT();
glBindTexture(GL_TEXTURE_2D, pstInfo->pstBitmap->uiTexture);
glASSERT();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)pstInfo->pstBitmap->u32RealWidth, (GLsizei)pstInfo->pstBitmap->u32RealHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (pstInfo->pu8ImageBuffer != orxNULL) ? pstInfo->pu8ImageBuffer : NULL);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (pstInfo->pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (pstInfo->pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
/* Restores previous texture */
glBindTexture(GL_TEXTURE_2D, (sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] != orxNULL) ? sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit]->uiTexture : 0);
glASSERT();
/* For all bound bitmaps */
for(i = 0; i < (orxU32)sstDisplay.iTextureUnitNumber; i++)
{
/* Is decompressed bitmap? */
if(sstDisplay.apstBoundBitmapList[i] == pstInfo->pstBitmap)
{
/* Resets it */
sstDisplay.apstBoundBitmapList[i] = orxNULL;
sstDisplay.adMRUBitmapList[i] = orxDOUBLE_0;
}
}
/* Asynchronous call? */
if(orxFLAG_TEST(pstInfo->pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING))
{
/* Failed decompression? */
if(pstInfo->pu8ImageBuffer == orxNULL)
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't process data for bitmap <%s>: an empty texture will be used instead.", pstInfo->pstBitmap->zLocation);
}
}
/* Inits payload */
stPayload.stBitmap.zLocation = pstInfo->pstBitmap->zLocation;
stPayload.stBitmap.stFilenameID = pstInfo->pstBitmap->stFilenameID;
stPayload.stBitmap.u32ID = (pstInfo->pu8ImageBuffer != orxNULL) ? (orxU32)pstInfo->pstBitmap->uiTexture : orxU32_UNDEFINED;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_DISPLAY, orxDISPLAY_EVENT_LOAD_BITMAP, pstInfo->pstBitmap, orxNULL, &stPayload);
/* Frees image buffer */
if(pstInfo->pu8ImageBuffer != pstInfo->pu8ImageSource)
{
orxMemory_Free(pstInfo->pu8ImageBuffer);
}
pstInfo->pu8ImageBuffer = orxNULL;
/* Frees source */
if(pstInfo->pu8ImageSource != orxNULL)
{
stbi_image_free(pstInfo->pu8ImageSource);
pstInfo->pu8ImageSource = orxNULL;
}
/* Clears loading flag */
orxFLAG_SET(pstInfo->pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_NONE, orxDISPLAY_KU32_BITMAP_FLAG_LOADING);
orxMEMORY_BARRIER();
/* Asked for deletion? */
if(orxFLAG_TEST(pstInfo->pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_DELETE))
{
/* Deletes it */
orxDisplay_DeleteBitmap(pstInfo->pstBitmap);
}
}
else
{
/* Frees image buffer */
if(pstInfo->pu8ImageBuffer != pstInfo->pu8ImageSource)
{
orxMemory_Free(pstInfo->pu8ImageBuffer);
}
pstInfo->pu8ImageBuffer = orxNULL;
/* Frees source */
if(pstInfo->pu8ImageSource != orxNULL)
{
stbi_image_free(pstInfo->pu8ImageSource);
pstInfo->pu8ImageSource = orxNULL;
}
}
/* Frees load info */
orxMemory_Free(pstInfo);
/* Done! */
return eResult;
}
static orxSTATUS orxFASTCALL orxDisplay_Android_DecompressBitmap(void *_pContext)
{
orxDISPLAY_LOAD_INFO *pstInfo;
orxSTATUS eResult;
/* Profiles */
orxPROFILER_PUSH_MARKER("orxDisplay_DecompressBitmap");
/* Gets load info */
pstInfo = (orxDISPLAY_LOAD_INFO *)_pContext;
/* Hasn't exited yet? */
if(sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY)
{
orxU8 *pu8ImageData;
GLuint uiBytesPerPixel;
/* Loads image */
pu8ImageData = stbi_load_from_memory((orxU8 *)pstInfo->pu8ImageSource, (int)pstInfo->s64Size, (int *)&(pstInfo->uiWidth), (int *)&(pstInfo->uiHeight), (int *)&uiBytesPerPixel, STBI_rgb_alpha);
/* Valid? */
if(pu8ImageData != NULL)
{
/* Uses image buffer */
pstInfo->pu8ImageBuffer = pu8ImageData;
/* Gets real size */
pstInfo->uiRealWidth = pstInfo->uiWidth;
pstInfo->uiRealHeight = pstInfo->uiHeight;
/* Frees original source from resource */
orxMemory_Free(pstInfo->pu8ImageSource);
/* Stores uncompressed data as new source */
pstInfo->pu8ImageSource = pu8ImageData;
}
else
{
/* Clears info */
pstInfo->uiWidth =
pstInfo->uiHeight =
pstInfo->uiRealWidth =
pstInfo->uiRealHeight = 1;
/* Frees original source from resource */
orxMemory_Free(pstInfo->pu8ImageSource);
pstInfo->pu8ImageSource = orxNULL;
}
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Frees original source from resource */
orxMemory_Free(pstInfo->pu8ImageSource);
pstInfo->pu8ImageSource = orxNULL;
/* Frees load info */
orxMemory_Free(pstInfo);
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
/* Profiles */
orxPROFILER_POP_MARKER();
/* Done! */
return eResult;
}
static void orxFASTCALL orxDisplay_Android_ReadResourceCallback(orxHANDLE _hResource, orxS64 _s64Size, void *_pBuffer, void *_pContext)
{
orxDISPLAY_LOAD_INFO *pstInfo;
/* Allocates load info */
pstInfo = (orxDISPLAY_LOAD_INFO *)orxMemory_Allocate(sizeof(orxDISPLAY_LOAD_INFO), orxMEMORY_TYPE_TEMP);
/* Checks */
orxASSERT(pstInfo != orxNULL);
/* Inits it */
orxMemory_Zero(pstInfo, sizeof(orxDISPLAY_LOAD_INFO));
pstInfo->pu8ImageSource = (orxU8 *)_pBuffer;
pstInfo->s64Size = _s64Size;
pstInfo->pstBitmap = (orxBITMAP *)_pContext;
/* Asynchronous? */
if(orxFLAG_TEST(pstInfo->pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING))
{
/* Runs asynchronous task */
if(orxThread_RunTask(&orxDisplay_Android_DecompressBitmap, orxDisplay_Android_DecompressBitmapCallback, orxNULL, (void *)pstInfo) == orxSTATUS_FAILURE)
{
/* Frees load info */
orxMemory_Free(pstInfo);
}
}
else
{
/* Decompresses bitmap */
if(orxDisplay_Android_DecompressBitmap(pstInfo) != orxSTATUS_FAILURE)
{
/* Upload texture */
orxDisplay_Android_DecompressBitmapCallback(pstInfo);
}
}
/* Closes resource */
orxResource_Close(_hResource);
}
static orxSTATUS orxFASTCALL orxDisplay_Android_LoadKTXBitmapData(orxBITMAP *_pstBitmap)
{
orxHANDLE hResource;
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Opens resource */
hResource = orxResource_Open(_pstBitmap->zLocation, orxFALSE);
/* Success? */
if(hResource != orxHANDLE_UNDEFINED)
{
orxS64 s64Size;
orxU8 *pu8Buffer;
/* Gets its size */
s64Size = orxResource_GetSize(hResource);
/* Checks */
orxASSERT((s64Size > 0) && (s64Size < 0xFFFFFFFF));
/* Allocates buffer */
pu8Buffer = (orxU8 *)orxMemory_Allocate((orxU32)s64Size, orxMEMORY_TYPE_MAIN);
/* Success? */
if(pu8Buffer != orxNULL)
{
/* Asynchronous? */
if(sstDisplay.pstTempBitmap != orxNULL)
{
int iWidth, iHeight;
/* Gets its info */
if(getKTXInfos(hResource, &iWidth, &iHeight) != 0)
{
/* Resets resource cursor */
orxResource_Seek(hResource, 0, orxSEEK_OFFSET_WHENCE_START);
/* Updates asynchronous loading flag */
orxFLAG_SET(_pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING, orxDISPLAY_KU32_BITMAP_FLAG_NONE);
/* Loads data from resource */
s64Size = orxResource_Read(hResource, s64Size, pu8Buffer, orxDisplay_Android_ReadKTXResourceCallback, (void *)_pstBitmap);
/* Successful asynchronous call? */
if(s64Size < 0)
{
/* Inits bitmap info using temp */
_pstBitmap->uiTexture = sstDisplay.pstTempBitmap->uiTexture;
_pstBitmap->fWidth = orxS2F(iWidth);
_pstBitmap->fHeight = orxS2F(iHeight);
_pstBitmap->u32RealWidth = sstDisplay.pstTempBitmap->u32RealWidth;
_pstBitmap->u32RealHeight = sstDisplay.pstTempBitmap->u32RealHeight;
_pstBitmap->u32Depth = sstDisplay.pstTempBitmap->u32Depth;
_pstBitmap->fRecRealWidth = sstDisplay.pstTempBitmap->fRecRealWidth;
_pstBitmap->fRecRealHeight = sstDisplay.pstTempBitmap->fRecRealHeight;
_pstBitmap->u32DataSize = sstDisplay.pstTempBitmap->u32DataSize;
orxVector_Copy(&(_pstBitmap->stClip.vTL), &(sstDisplay.pstTempBitmap->stClip.vTL));
orxVector_Copy(&(_pstBitmap->stClip.vBR), &(sstDisplay.pstTempBitmap->stClip.vBR));
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Frees buffer */
orxMemory_Free(pu8Buffer);
/* Closes resource */
orxResource_Close(hResource);
}
}
else
{
/* Frees buffer */
orxMemory_Free(pu8Buffer);
/* Closes resource */
orxResource_Close(hResource);
}
}
else
{
/* Loads data from resource */
s64Size = orxResource_Read(hResource, s64Size, pu8Buffer, orxNULL, orxNULL);
/* Success? */
if(s64Size != 0)
{
/* Processes data */
orxDisplay_Android_ReadKTXResourceCallback(hResource, s64Size, (void *)pu8Buffer, (void *)_pstBitmap);
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Frees buffer */
orxMemory_Free(pu8Buffer);
/* Closes resource */
orxResource_Close(hResource);
}
}
}
else
{
/* Closes resource */
orxResource_Close(hResource);
}
}
/* Done! */
return eResult;
}
static orxSTATUS orxFASTCALL orxDisplay_Android_LoadBitmapData(orxBITMAP *_pstBitmap)
{
orxHANDLE hResource;
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Opens resource */
hResource = orxResource_Open(_pstBitmap->zLocation, orxFALSE);
/* Success? */
if(hResource != orxHANDLE_UNDEFINED)
{
orxS64 s64Size;
orxU8 *pu8Buffer;
/* Gets its size */
s64Size = orxResource_GetSize(hResource);
/* Checks */
orxASSERT((s64Size > 0) && (s64Size < 0xFFFFFFFF));
/* Allocates buffer */
pu8Buffer = (orxU8 *)orxMemory_Allocate((orxU32)s64Size, orxMEMORY_TYPE_MAIN);
/* Success? */
if(pu8Buffer != orxNULL)
{
/* Asynchronous? */
if(sstDisplay.pstTempBitmap != orxNULL)
{
int iWidth, iHeight, iComp;
/* Gets its info */
if(stbi_info_from_callbacks(&(sstDisplay.stSTBICallbacks), (void *)hResource, &iWidth, &iHeight, &iComp) != 0)
{
/* Resets resource cursor */
orxResource_Seek(hResource, 0, orxSEEK_OFFSET_WHENCE_START);
/* Updates asynchronous loading flag */
orxFLAG_SET(_pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING, orxDISPLAY_KU32_BITMAP_FLAG_NONE);
/* Loads data from resource */
s64Size = orxResource_Read(hResource, s64Size, pu8Buffer, orxDisplay_Android_ReadResourceCallback, (void *)_pstBitmap);
/* Successful asynchronous call? */
if(s64Size < 0)
{
/* Inits bitmap info using temp */
_pstBitmap->uiTexture = sstDisplay.pstTempBitmap->uiTexture;
_pstBitmap->fWidth = orxS2F(iWidth);
_pstBitmap->fHeight = orxS2F(iHeight);
_pstBitmap->u32RealWidth = sstDisplay.pstTempBitmap->u32RealWidth;
_pstBitmap->u32RealHeight = sstDisplay.pstTempBitmap->u32RealHeight;
_pstBitmap->u32Depth = sstDisplay.pstTempBitmap->u32Depth;
_pstBitmap->fRecRealWidth = sstDisplay.pstTempBitmap->fRecRealWidth;
_pstBitmap->fRecRealHeight = sstDisplay.pstTempBitmap->fRecRealHeight;
_pstBitmap->u32DataSize = sstDisplay.pstTempBitmap->u32DataSize;
orxVector_Copy(&(_pstBitmap->stClip.vTL), &(sstDisplay.pstTempBitmap->stClip.vTL));
orxVector_Copy(&(_pstBitmap->stClip.vBR), &(sstDisplay.pstTempBitmap->stClip.vBR));
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Frees buffer */
orxMemory_Free(pu8Buffer);
/* Closes resource */
orxResource_Close(hResource);
}
}
else
{
/* Frees buffer */
orxMemory_Free(pu8Buffer);
/* Closes resource */
orxResource_Close(hResource);
}
}
else
{
/* Loads data from resource */
s64Size = orxResource_Read(hResource, s64Size, pu8Buffer, orxNULL, orxNULL);
/* Success? */
if(s64Size != 0)
{
/* Processes data */
orxDisplay_Android_ReadResourceCallback(hResource, s64Size, (void *)pu8Buffer, (void *)_pstBitmap);
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Frees buffer */
orxMemory_Free(pu8Buffer);
/* Closes resource */
orxResource_Close(hResource);
}
}
}
else
{
/* Closes resource */
orxResource_Close(hResource);
}
}
/* Done! */
return eResult;
}
static void orxFASTCALL orxDisplay_Android_DeleteBitmapData(orxBITMAP *_pstBitmap)
{
orxS32 i;
/* For all bound bitmaps */
for(i = 0; i < (orxS32)sstDisplay.iTextureUnitNumber; i++)
{
/* Is deleted bitmap? */
if(sstDisplay.apstBoundBitmapList[i] == _pstBitmap)
{
/* Resets it */
sstDisplay.apstBoundBitmapList[i] = orxNULL;
sstDisplay.adMRUBitmapList[i] = orxDOUBLE_0;
}
}
/* Tracks video memory */
orxMEMORY_TRACK(VIDEO, _pstBitmap->u32DataSize, orxFALSE);
/* Deletes its texture */
glDeleteTextures(1, &(_pstBitmap->uiTexture));
glASSERT();
/* Done! */
return;
}
static orxSTATUS orxFASTCALL orxDisplay_Android_SaveBitmapData(void *_pContext)
{
orxDISPLAY_SAVE_INFO *pstInfo;
const orxCHAR *zExtension;
const orxSTRING zFilename;
orxU32 u32Length;
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Gets save info */
pstInfo = (orxDISPLAY_SAVE_INFO *)_pContext;
/* Gets filename */
zFilename = orxString_GetFromID(pstInfo->stFilenameID);
/* Gets file name's length */
u32Length = orxString_GetLength(zFilename);
/* Gets extension */
zExtension = (u32Length > 3) ? zFilename + u32Length - 3 : orxSTRING_EMPTY;
/* PNG? */
if(orxString_ICompare(zExtension, "png") == 0)
{
/* Saves image to disk */
eResult = stbi_write_png(zFilename, pstInfo->u32Width, pstInfo->u32Height, 4, pstInfo->pu8ImageData, 0) != 0 ? orxSTATUS_SUCCESS : orxSTATUS_FAILURE;
}
/* BMP? */
else if(orxString_ICompare(zExtension, "bmp") == 0)
{
/* Saves image to disk */
eResult = stbi_write_bmp(zFilename, pstInfo->u32Width, pstInfo->u32Height, 4, pstInfo->pu8ImageData) != 0 ? orxSTATUS_SUCCESS : orxSTATUS_FAILURE;
}
/* TGA */
else
{
/* Saves image to disk */
eResult = stbi_write_tga(zFilename, pstInfo->u32Width, pstInfo->u32Height, 4, pstInfo->pu8ImageData) != 0 ? orxSTATUS_SUCCESS : orxSTATUS_FAILURE;
}
/* Deletes data */
orxMemory_Free(pstInfo->pu8ImageData);
/* Deletes save info */
orxMemory_Free(pstInfo);
/* Done! */
return eResult;
}
static orxINLINE orxDISPLAY_MATRIX *orxDisplay_Android_InitMatrix(orxDISPLAY_MATRIX *_pmMatrix, orxFLOAT _fPosX, orxFLOAT _fPosY, orxFLOAT _fScaleX, orxFLOAT _fScaleY, orxFLOAT _fRotation, orxFLOAT _fPivotX, orxFLOAT _fPivotY)
{
orxFLOAT fCos, fSin, fSCosX, fSCosY, fSSinX, fSSinY, fTX, fTY;
/* Has rotation? */
if(_fRotation != orxFLOAT_0)
{
/* Gets its cos/sin */
fCos = orxMath_Cos(_fRotation);
fSin = orxMath_Sin(_fRotation);
}
else
{
/* Inits cos/sin */
fCos = orxFLOAT_1;
fSin = orxFLOAT_0;
}
/* Computes values */
fSCosX = _fScaleX * fCos;
fSCosY = _fScaleY * fCos;
fSSinX = _fScaleX * fSin;
fSSinY = _fScaleY * fSin;
fTX = _fPosX - (_fPivotX * fSCosX) + (_fPivotY * fSSinY);
fTY = _fPosY - (_fPivotX * fSSinX) - (_fPivotY * fSCosY);
/* Updates matrix */
orxVector_Set(&(_pmMatrix->vX), fSCosX, -fSSinY, fTX);
orxVector_Set(&(_pmMatrix->vY), fSSinX, fSCosY, fTY);
/* Done! */
return _pmMatrix;
}
static orxSTATUS orxFASTCALL orxDisplay_Android_CompileShader(orxDISPLAY_SHADER *_pstShader)
{
static const orxSTRING szVertexShaderSource =
"attribute vec2 _vPosition_;"
"uniform mat4 _mProjection_;"
"attribute mediump vec2 _vTexCoord_;"
"varying mediump vec2 _gl_TexCoord0_;"
"attribute mediump vec4 _vColor_;"
"varying mediump vec4 _Color0_;"
"void main()"
"{"
" mediump float fCoef = 1.0 / 255.0;"
" gl_Position = _mProjection_ * vec4(_vPosition_.xy, 0.0, 1.0);"
" _gl_TexCoord0_ = _vTexCoord_;"
" _Color0_ = fCoef * _vColor_;"
"}";
GLuint uiProgram, uiVertexShader, uiFragmentShader;
GLint iSuccess;
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Creates program */
uiProgram = glCreateProgram();
glASSERT();
/* Creates vertex and fragment shaders */
uiVertexShader = glCreateShader(GL_VERTEX_SHADER);
glASSERT();
uiFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glASSERT();
/* Compiles shader objects */
glShaderSource(uiVertexShader, 1, (const char **)&szVertexShaderSource, NULL);
glASSERT();
glShaderSource(uiFragmentShader, 1, (const char **)&(_pstShader->zCode), NULL);
glASSERT();
glCompileShader(uiVertexShader);
glASSERT();
glCompileShader(uiFragmentShader);
glASSERT();
/* Gets vertex shader compiling status */
glGetShaderiv(uiVertexShader, GL_COMPILE_STATUS, &iSuccess);
glASSERT();
/* Success? */
if(iSuccess != GL_FALSE)
{
/* Gets fragment shader compiling status */
glGetShaderiv(uiFragmentShader, GL_COMPILE_STATUS, &iSuccess);
glASSERT();
/* Success? */
if(iSuccess != GL_FALSE)
{
/* Attaches shader objects to program */
glAttachShader(uiProgram, uiVertexShader);
glASSERT();
glAttachShader(uiProgram, uiFragmentShader);
glASSERT();
/* Deletes shader objects */
glDeleteShader(uiVertexShader);
glASSERT();
glDeleteShader(uiFragmentShader);
glASSERT();
/* Binds attributes */
glBindAttribLocation(uiProgram, orxDISPLAY_ATTRIBUTE_LOCATION_VERTEX, "_vPosition_");
glASSERT();
glBindAttribLocation(uiProgram, orxDISPLAY_ATTRIBUTE_LOCATION_TEXCOORD, "_vTexCoord_");
glASSERT();
glBindAttribLocation(uiProgram, orxDISPLAY_ATTRIBUTE_LOCATION_COLOR, "_vColor_");
glASSERT();
/* Links program */
glLinkProgram(uiProgram);
glASSERT();
/* Gets texture location */
_pstShader->iTextureLocation = glGetUniformLocation(uiProgram, "_Texture_");
glASSERT();
/* Gets projection matrix location */
_pstShader->iProjectionMatrixLocation = glGetUniformLocation(uiProgram, "_mProjection_");
glASSERT();
/* Gets linking status */
glGetProgramiv(uiProgram, GL_LINK_STATUS, &iSuccess);
glASSERT();
/* Success? */
if(iSuccess != GL_FALSE)
{
/* Updates shader */
_pstShader->uiProgram = uiProgram;
_pstShader->iTextureCount = 0;
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
orxCHAR acBuffer[4096];
/* Gets log */
glGetProgramInfoLog(uiProgram, sizeof(acBuffer) - 1, NULL, (char *)acBuffer);
glASSERT();
acBuffer[sizeof(acBuffer) - 1] = orxCHAR_NULL;
/* Outputs log */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't link shader program:\n%s\n", acBuffer);
/* Deletes program */
glDeleteProgram(uiProgram);
glASSERT();
}
}
else
{
orxCHAR acBuffer[4096];
/* Gets log */
glGetShaderInfoLog(uiFragmentShader, sizeof(acBuffer) - 1, NULL, (char *)acBuffer);
glASSERT();
acBuffer[sizeof(acBuffer) - 1] = orxCHAR_NULL;
/* Outputs log */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't compile fragment shader:\n%s\n", acBuffer);
/* Deletes shader objects & program */
glDeleteShader(uiVertexShader);
glASSERT();
glDeleteShader(uiFragmentShader);
glASSERT();
glDeleteProgram(uiProgram);
glASSERT();
}
}
else
{
orxCHAR acBuffer[4096];
/* Gets log */
glGetShaderInfoLog(uiVertexShader, sizeof(acBuffer) - 1, NULL, (char *)acBuffer);
glASSERT();
acBuffer[sizeof(acBuffer) - 1] = orxCHAR_NULL;
/* Outputs log */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Couldn't compile vertex shader:\n%s\n", acBuffer);
/* Deletes shader objects & program */
glDeleteShader(uiVertexShader);
glASSERT();
glDeleteShader(uiFragmentShader);
glASSERT();
glDeleteProgram(uiProgram);
glASSERT();
}
/* Done! */
return eResult;
}
static void orxFASTCALL orxDisplay_Android_InitShader(orxDISPLAY_SHADER *_pstShader)
{
/* Uses shader's program */
glUseProgram(_pstShader->uiProgram);
glASSERT();
/* Has custom textures? */
if(_pstShader->iTextureCount > 0)
{
GLint i;
/* For all defined textures */
for(i = 0; i < _pstShader->iTextureCount; i++)
{
/* Binds bitmap */
orxDisplay_Android_BindBitmap(_pstShader->astTextureInfoList[i].pstBitmap);
/* Updates shader uniform */
glUNIFORM(1i, _pstShader->astTextureInfoList[i].iLocation, sstDisplay.s32ActiveTextureUnit);
}
}
/* Done! */
return;
}
static void orxFASTCALL orxDisplay_Android_DrawArrays()
{
/* Has data? */
if(sstDisplay.s32BufferIndex > 0)
{
/* Profiles */
orxPROFILER_PUSH_MARKER("orxDisplay_DrawArrays");
/* Indirect mode? */
if(sstDisplay.eLastBufferMode == orxDISPLAY_BUFFER_MODE_INDIRECT)
{
/* Sends vertex buffer */
glBufferData(GL_ARRAY_BUFFER, (GLsizei)(sstDisplay.s32BufferIndex * sizeof(orxDISPLAY_ANDROID_VERTEX)), sstDisplay.astVertexList, GL_STREAM_DRAW);
glASSERT();
}
/* Has active shaders? */
if(orxLinkList_GetCount(&(sstDisplay.stActiveShaderList)) > 0)
{
orxDISPLAY_SHADER *pstShader, *pstNextShader;
/* For all active shaders */
for(pstShader = (orxDISPLAY_SHADER *)orxLinkList_GetFirst(&(sstDisplay.stActiveShaderList));
pstShader != orxNULL;
pstShader = pstNextShader)
{
/* Inits shader */
orxDisplay_Android_InitShader(pstShader);
/* Draws elements */
glDrawElements(sstDisplay.ePrimitive, sstDisplay.s32ElementNumber, GL_UNSIGNED_SHORT, 0);
glASSERT();
/* Gets next shader */
pstNextShader = (orxDISPLAY_SHADER *)orxLinkList_GetNext(&(pstShader->stNode));
/* Was pending removal? */
if(pstShader->bPending != orxFALSE)
{
/* Clears its texture count */
pstShader->iTextureCount = 0;
/* Clears its texture info list */
orxMemory_Zero(pstShader->astTextureInfoList, sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_TEXTURE_INFO));
/* Removes its pending status */
pstShader->bPending = orxFALSE;
/* Removes it from active list */
orxLinkList_Remove(&(pstShader->stNode));
/* Updates count */
sstDisplay.s32PendingShaderCount--;
}
}
/* Uses default program */
orxDisplay_Android_StopShader(orxNULL);
}
else
{
/* Draws elements */
glDrawElements(sstDisplay.ePrimitive, sstDisplay.s32ElementNumber, GL_UNSIGNED_SHORT, 0);
glASSERT();
}
/* Clears buffer index & element number */
sstDisplay.s32BufferIndex =
sstDisplay.s32ElementNumber = 0;
/* Profiles */
orxPROFILER_POP_MARKER();
}
/* Done! */
return;
}
static void orxFASTCALL orxDisplay_Android_SetBufferMode(orxDISPLAY_BUFFER_MODE _eBufferMode)
{
/* New blend mode? */
if(_eBufferMode != sstDisplay.eLastBufferMode)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Indirect? */
if(_eBufferMode == orxDISPLAY_BUFFER_MODE_INDIRECT)
{
/* Reverts back to default primitive */
sstDisplay.ePrimitive = orxDISPLAY_KE_DEFAULT_PRIMITIVE;
/* Was using custom IBO? */
if(orxFLAG_TEST(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_CUSTOM_IBO))
{
/* Fills IBO */
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizei)(orxDISPLAY_KU32_INDEX_BUFFER_SIZE * sizeof(GLushort)), sstDisplay.au16IndexList, GL_STATIC_DRAW);
glASSERT();
/* Updates flags */
orxFLAG_SET(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_NONE, orxDISPLAY_KU32_STATIC_FLAG_CUSTOM_IBO);
}
}
/* Stores it */
sstDisplay.eLastBufferMode = _eBufferMode;
}
/* Done! */
return;
}
static void orxFASTCALL orxDisplay_Android_PrepareBitmap(const orxBITMAP *_pstBitmap, orxDISPLAY_SMOOTHING _eSmoothing, orxDISPLAY_BLEND_MODE _eBlendMode, orxDISPLAY_BUFFER_MODE _eBufferMode)
{
orxBOOL bSmoothing;
/* Checks */
orxASSERT((_pstBitmap != orxNULL) && (_pstBitmap != sstDisplay.pstScreen));
/* Has pending shaders? */
if(sstDisplay.s32PendingShaderCount != 0)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Checks */
orxASSERT(sstDisplay.s32PendingShaderCount == 0);
}
/* New bitmap? */
if(_pstBitmap != sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit])
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Binds source bitmap */
orxDisplay_Android_BindBitmap(_pstBitmap);
/* No other shader active? */
if(orxLinkList_GetCount(&(sstDisplay.stActiveShaderList)) == 0)
{
/* Updates shader uniform */
glUNIFORM(1i, sstDisplay.pstDefaultShader->iTextureLocation, sstDisplay.s32ActiveTextureUnit);
}
}
/* Depending on smoothing type */
switch(_eSmoothing)
{
case orxDISPLAY_SMOOTHING_ON:
{
/* Applies smoothing */
bSmoothing = orxTRUE;
break;
}
case orxDISPLAY_SMOOTHING_OFF:
{
/* Applies no smoothing */
bSmoothing = orxFALSE;
break;
}
default:
case orxDISPLAY_SMOOTHING_DEFAULT:
{
/* Applies default smoothing */
bSmoothing = sstDisplay.bDefaultSmoothing;
break;
}
}
/* Should update smoothing? */
if(bSmoothing != _pstBitmap->bSmoothing)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Smoothing? */
if(bSmoothing != orxFALSE)
{
/* Updates texture */
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glASSERT();
/* Updates mode */
((orxBITMAP *)_pstBitmap)->bSmoothing = orxTRUE;
}
else
{
/* Updates texture */
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glASSERT();
/* Updates mode */
((orxBITMAP *)_pstBitmap)->bSmoothing = orxFALSE;
}
}
/* Sets blend mode */
orxDisplay_Android_SetBlendMode(_eBlendMode);
/* Sets buffer mode */
orxDisplay_Android_SetBufferMode(_eBufferMode);
/* Done! */
return;
}
static orxINLINE void orxDisplay_Android_DrawBitmap(const orxBITMAP *_pstBitmap, const orxDISPLAY_MATRIX *_pmTransform, orxRGBA _stColor, orxDISPLAY_SMOOTHING _eSmoothing, orxDISPLAY_BLEND_MODE _eBlendMode)
{
GLfloat fWidth, fHeight;
/* Prepares bitmap for drawing */
orxDisplay_Android_PrepareBitmap(_pstBitmap, _eSmoothing, _eBlendMode, orxDISPLAY_BUFFER_MODE_INDIRECT);
/* Gets bitmap working size */
fWidth = (GLfloat) (_pstBitmap->stClip.vBR.fX - _pstBitmap->stClip.vTL.fX);
fHeight = (GLfloat) (_pstBitmap->stClip.vBR.fY - _pstBitmap->stClip.vTL.fY);
/* End of buffer? */
if(sstDisplay.s32BufferIndex > orxDISPLAY_KU32_VERTEX_BUFFER_SIZE - 5)
{
/* Draws arrays */
orxDisplay_Android_DrawArrays();
}
/* Fills the vertex list */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fX = (_pmTransform->vX.fY * fHeight) + _pmTransform->vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fY = (_pmTransform->vY.fY * fHeight) + _pmTransform->vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fX = _pmTransform->vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fY = _pmTransform->vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fX = (_pmTransform->vX.fX * fWidth) + (_pmTransform->vX.fY * fHeight) + _pmTransform->vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fY = (_pmTransform->vY.fX * fWidth) + (_pmTransform->vY.fY * fHeight) + _pmTransform->vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fX = (_pmTransform->vX.fX * fWidth) + _pmTransform->vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fY = (_pmTransform->vY.fX * fWidth) + _pmTransform->vY.fZ;
/* Fills the texture coord list */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fU =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fU = (GLfloat) (_pstBitmap->fRecRealWidth * (_pstBitmap->stClip.vTL.fX + orxDISPLAY_KF_BORDER_FIX));
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fU =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fU = (GLfloat) (_pstBitmap->fRecRealWidth * (_pstBitmap->stClip.vBR.fX - orxDISPLAY_KF_BORDER_FIX));
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fV =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fV = (GLfloat)(_pstBitmap->fRecRealHeight * (_pstBitmap->stClip.vTL.fY + orxDISPLAY_KF_BORDER_FIX));
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fV =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fV = (GLfloat)(_pstBitmap->fRecRealHeight * (_pstBitmap->stClip.vBR.fY - orxDISPLAY_KF_BORDER_FIX));
/* Fills the color list */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].stRGBA = _stColor;
/* Updates index & element number */
sstDisplay.s32BufferIndex += 4;
sstDisplay.s32ElementNumber += 6;
/* Done! */
return;
}
static void orxFASTCALL orxDisplay_Android_DrawPrimitive(orxU32 _u32VertexNumber, orxRGBA _stColor, orxBOOL _bFill, orxBOOL _bOpen)
{
/* Profiles */
orxPROFILER_PUSH_MARKER("orxDisplay_DrawPrimitive");
/* Starts no texture shader */
orxDisplay_Android_StartShader((orxHANDLE)sstDisplay.pstNoTextureShader);
/* Inits it */
orxDisplay_Android_InitShader(sstDisplay.pstNoTextureShader);
/* Has alpha? */
if(orxRGBA_A(_stColor) != 0xFF)
{
/* Enables alpha blending */
glEnable(GL_BLEND);
glASSERT();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glASSERT();
/* Updates blend mode */
sstDisplay.eLastBlendMode = orxDISPLAY_BLEND_MODE_ALPHA;
}
else
{
/* Disables alpha blending */
glDisable(GL_BLEND);
glASSERT();
/* Updates blend mode */
sstDisplay.eLastBlendMode = orxDISPLAY_BLEND_MODE_NONE;
}
/* Copies vertex buffer */
glBufferData(GL_ARRAY_BUFFER, (GLsizei)(_u32VertexNumber * sizeof(orxDISPLAY_ANDROID_VERTEX)), sstDisplay.astVertexList, GL_STREAM_DRAW);
glASSERT();
/* Only 2 vertices? */
if(_u32VertexNumber == 2)
{
/* Draws it */
glDrawArrays(GL_LINES, 0, 2);
glASSERT();
}
else
{
/* Should fill? */
if(_bFill != orxFALSE)
{
/* Draws it */
glDrawArrays(GL_TRIANGLE_FAN, 0, _u32VertexNumber);
glASSERT();
}
else
{
/* Is open? */
if(_bOpen != orxFALSE)
{
/* Draws it */
glDrawArrays(GL_LINE_STRIP, 0, _u32VertexNumber);
glASSERT();
}
else
{
/* Draws it */
glDrawArrays(GL_LINE_LOOP, 0, _u32VertexNumber);
glASSERT();
}
}
}
/* Bypasses the full screen rendering when stopping shader */
sstDisplay.s32BufferIndex = -1;
/* Stops current shader */
orxDisplay_Android_StopShader((orxHANDLE)sstDisplay.pstNoTextureShader);
/* Resets buffer index */
sstDisplay.s32BufferIndex = 0;
/* Profiles */
orxPROFILER_POP_MARKER();
/* Done! */
return;
}
static orxINLINE GLenum orxDisplay_Android_GetOpenGLPrimitive(orxDISPLAY_PRIMITIVE _ePrimitive)
{
GLenum eResult;
#define orxDISPLAY_PRIMITIVE_CASE(TYPE) case orxDISPLAY_PRIMITIVE_##TYPE: eResult = GL_##TYPE; break
/* Depending on mode */
switch(_ePrimitive)
{
orxDISPLAY_PRIMITIVE_CASE(POINTS);
orxDISPLAY_PRIMITIVE_CASE(LINES);
orxDISPLAY_PRIMITIVE_CASE(LINE_LOOP);
orxDISPLAY_PRIMITIVE_CASE(LINE_STRIP);
orxDISPLAY_PRIMITIVE_CASE(TRIANGLES);
orxDISPLAY_PRIMITIVE_CASE(TRIANGLE_STRIP);
orxDISPLAY_PRIMITIVE_CASE(TRIANGLE_FAN);
default: eResult = orxDISPLAY_KE_DEFAULT_PRIMITIVE; break;
}
/* Done! */
return eResult;
}
orxBITMAP *orxFASTCALL orxDisplay_Android_GetScreenBitmap()
{
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Done! */
return sstDisplay.pstScreen;
}
orxSTATUS orxFASTCALL orxDisplay_Android_TransformText(const orxSTRING _zString, const orxBITMAP *_pstFont, const orxCHARACTER_MAP *_pstMap, const orxDISPLAY_TRANSFORM *_pstTransform, orxRGBA _stColor, orxDISPLAY_SMOOTHING _eSmoothing, orxDISPLAY_BLEND_MODE _eBlendMode)
{
orxDISPLAY_MATRIX mTransform;
const orxCHAR *pc;
orxU32 u32CharacterCodePoint;
GLfloat fX, fY, fHeight;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_zString != orxNULL);
orxASSERT(_pstFont != orxNULL);
orxASSERT(_pstMap != orxNULL);
orxASSERT(_pstTransform != orxNULL);
/* Inits matrix */
orxDisplay_Android_InitMatrix(&mTransform, _pstTransform->fDstX, _pstTransform->fDstY, _pstTransform->fScaleX, _pstTransform->fScaleY, _pstTransform->fRotation, _pstTransform->fSrcX, _pstTransform->fSrcY);
/* Gets character's height */
fHeight = _pstMap->fCharacterHeight;
/* Prepares font for drawing */
orxDisplay_Android_PrepareBitmap(_pstFont, _eSmoothing, _eBlendMode, orxDISPLAY_BUFFER_MODE_INDIRECT);
/* For all characters */
for (u32CharacterCodePoint = orxString_GetFirstCharacterCodePoint(_zString, &pc), fX = 0.0f, fY = 0.0f;
u32CharacterCodePoint != orxCHAR_NULL;
u32CharacterCodePoint = orxString_GetFirstCharacterCodePoint(pc, &pc))
{
/* Depending on character */
switch (u32CharacterCodePoint)
{
case orxCHAR_CR:
{
/* Half EOL? */
if(*pc == orxCHAR_LF)
{
/* Updates pointer */
pc++;
}
/* Fall through */
}
case orxCHAR_LF:
{
/* Updates Y position */
fY += fHeight;
/* Resets X position */
fX = 0.0f;
break;
}
default:
{
const orxCHARACTER_GLYPH *pstGlyph;
/* Gets glyph from table */
pstGlyph = (orxCHARACTER_GLYPH *) orxHashTable_Get(_pstMap->pstCharacterTable, u32CharacterCodePoint);
orxFLOAT fWidth;
/* Valid? */
if(pstGlyph != orxNULL)
{
/* Gets character width */
fWidth = pstGlyph->fWidth;
/* End of buffer? */
if(sstDisplay.s32BufferIndex > orxDISPLAY_KU32_VERTEX_BUFFER_SIZE - 5)
{
/* Draws arrays */
orxDisplay_Android_DrawArrays();
}
/* Outputs vertices and texture coordinates */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fX = (mTransform.vX.fX * fX) + (mTransform.vX.fY * (fY + fHeight)) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fY = (mTransform.vY.fX * fX) + (mTransform.vY.fY * (fY + fHeight)) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fX = (mTransform.vX.fX * fX) + (mTransform.vX.fY * fY) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fY = (mTransform.vY.fX * fX) + (mTransform.vY.fY * fY) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fX = (mTransform.vX.fX * (fX + fWidth)) + (mTransform.vX.fY * (fY + fHeight)) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fY = (mTransform.vY.fX * (fX + fWidth)) + (mTransform.vY.fY * (fY + fHeight)) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fX = (mTransform.vX.fX * (fX + fWidth)) + (mTransform.vX.fY * fY) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fY = (mTransform.vY.fX * (fX + fWidth)) + (mTransform.vY.fY * fY) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fU =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fU = (GLfloat) (_pstFont->fRecRealWidth * (pstGlyph->fX + orxDISPLAY_KF_BORDER_FIX));
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fU =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fU = (GLfloat) (_pstFont->fRecRealWidth * (pstGlyph->fX + fWidth - orxDISPLAY_KF_BORDER_FIX));
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fV =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fV = (GLfloat)(_pstFont->fRecRealHeight * (pstGlyph->fY + orxDISPLAY_KF_BORDER_FIX));
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fV =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fV = (GLfloat)(_pstFont->fRecRealHeight * (pstGlyph->fY + fHeight - orxDISPLAY_KF_BORDER_FIX));
/* Fills the color list */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].stRGBA = _stColor;
/* Updates index & element number */
sstDisplay.s32BufferIndex += 4;
sstDisplay.s32ElementNumber += 6;
}
else
{
/* Gets default width */
fWidth = fHeight;
}
/* Updates X position */
fX += fWidth;
break;
}
}
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_DrawLine(const orxVECTOR *_pvStart, const orxVECTOR *_pvEnd, orxRGBA _stColor)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pvStart != orxNULL);
orxASSERT(_pvEnd != orxNULL);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Copies vertices */
sstDisplay.astVertexList[0].fX = (GLfloat)(_pvStart->fX);
sstDisplay.astVertexList[0].fY = (GLfloat)(_pvStart->fY);
sstDisplay.astVertexList[1].fX = (GLfloat)(_pvEnd->fX);
sstDisplay.astVertexList[1].fY = (GLfloat)(_pvEnd->fY);
/* Copies color */
sstDisplay.astVertexList[0].stRGBA =
sstDisplay.astVertexList[1].stRGBA = _stColor;
/* Draws it */
orxDisplay_Android_DrawPrimitive(2, _stColor, orxFALSE, orxTRUE);
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_DrawPolyline(const orxVECTOR *_avVertexList, orxU32 _u32VertexNumber, orxRGBA _stColor)
{
orxU32 i;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_avVertexList != orxNULL);
orxASSERT(_u32VertexNumber > 0);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* For all vertices */
for(i = 0; i < _u32VertexNumber; i++)
{
/* Copies its coords */
sstDisplay.astVertexList[i].fX = (GLfloat)(_avVertexList[i].fX);
sstDisplay.astVertexList[i].fY = (GLfloat)(_avVertexList[i].fY);
/* Copies color */
sstDisplay.astVertexList[i].stRGBA = _stColor;
}
/* Draws it */
orxDisplay_Android_DrawPrimitive(_u32VertexNumber, _stColor, orxFALSE, orxTRUE);
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_DrawPolygon(const orxVECTOR *_avVertexList, orxU32 _u32VertexNumber, orxRGBA _stColor, orxBOOL _bFill)
{
orxU32 i;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_avVertexList != orxNULL);
orxASSERT(_u32VertexNumber > 0);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* For all vertices */
for(i = 0; i < _u32VertexNumber; i++)
{
/* Copies its coords */
sstDisplay.astVertexList[i].fX = (GLfloat)(_avVertexList[i].fX);
sstDisplay.astVertexList[i].fY = (GLfloat)(_avVertexList[i].fY);
/* Copies color */
sstDisplay.astVertexList[i].stRGBA = _stColor;
}
/* Draws it */
orxDisplay_Android_DrawPrimitive(_u32VertexNumber, _stColor, _bFill, orxFALSE);
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_DrawCircle(const orxVECTOR *_pvCenter, orxFLOAT _fRadius, orxRGBA _stColor, orxBOOL _bFill)
{
orxU32 i;
orxFLOAT fAngle;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pvCenter != orxNULL);
orxASSERT(_fRadius >= orxFLOAT_0);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* For all vertices */
for(i = 0, fAngle = orxFLOAT_0; i < orxDISPLAY_KU32_CIRCLE_LINE_NUMBER; i++, fAngle += orxMATH_KF_2_PI / orxDISPLAY_KU32_CIRCLE_LINE_NUMBER)
{
/* Copies its coords */
sstDisplay.astVertexList[i].fX = (GLfloat)(_fRadius * orxMath_Cos(fAngle) + _pvCenter->fX);
sstDisplay.astVertexList[i].fY = (GLfloat)(_fRadius * orxMath_Sin(fAngle) + _pvCenter->fY);
/* Copies color */
sstDisplay.astVertexList[i].stRGBA = _stColor;
}
/* Draws it */
orxDisplay_Android_DrawPrimitive(orxDISPLAY_KU32_CIRCLE_LINE_NUMBER, _stColor, _bFill, orxFALSE);
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_DrawOBox(const orxOBOX *_pstBox, orxRGBA _stColor, orxBOOL _bFill)
{
orxVECTOR vOrigin;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstBox != orxNULL);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Gets origin */
orxVector_Sub(&vOrigin, &(_pstBox->vPosition), &(_pstBox->vPivot));
/* Sets vertices */
sstDisplay.astVertexList[0].fX = (GLfloat)(vOrigin.fX);
sstDisplay.astVertexList[0].fY = (GLfloat)(vOrigin.fY);
sstDisplay.astVertexList[1].fX = (GLfloat)(vOrigin.fX + _pstBox->vX.fX);
sstDisplay.astVertexList[1].fY = (GLfloat)(vOrigin.fY + _pstBox->vX.fY);
sstDisplay.astVertexList[2].fX = (GLfloat)(vOrigin.fX + _pstBox->vX.fX + _pstBox->vY.fX);
sstDisplay.astVertexList[2].fY = (GLfloat)(vOrigin.fY + _pstBox->vX.fY + _pstBox->vY.fY);
sstDisplay.astVertexList[3].fX = (GLfloat)(vOrigin.fX + _pstBox->vY.fX);
sstDisplay.astVertexList[3].fY = (GLfloat)(vOrigin.fY + _pstBox->vY.fY);
/* Copies color */
sstDisplay.astVertexList[0].stRGBA =
sstDisplay.astVertexList[1].stRGBA =
sstDisplay.astVertexList[2].stRGBA =
sstDisplay.astVertexList[3].stRGBA = _stColor;
/* Draws it */
orxDisplay_Android_DrawPrimitive(4, _stColor, _bFill, orxFALSE);
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_DrawMesh(const orxDISPLAY_MESH *_pstMesh, const orxBITMAP *_pstBitmap, orxDISPLAY_SMOOTHING _eSmoothing, orxDISPLAY_BLEND_MODE _eBlendMode)
{
const orxBITMAP *pstBitmap;
orxU32 u32ElementNumber;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstMesh != orxNULL);
orxASSERT(_pstMesh->u32VertexNumber > 1);
orxASSERT((_pstMesh->au16IndexList == orxNULL) || (_pstMesh->u32IndexNumber > 1));
orxASSERT((_pstMesh->ePrimitive < orxDISPLAY_PRIMITIVE_NUMBER) || ((_pstMesh->ePrimitive == orxDISPLAY_PRIMITIVE_NONE) && (_pstMesh->au16IndexList == orxNULL)));
/* Gets bitmap to use */
pstBitmap = (_pstBitmap != orxNULL) ? _pstBitmap : sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit];
/* Prepares bitmap for drawing */
orxDisplay_Android_PrepareBitmap(pstBitmap, _eSmoothing, _eBlendMode, orxDISPLAY_BUFFER_MODE_DIRECT);
/* Stores primitive */
sstDisplay.ePrimitive = orxDisplay_Android_GetOpenGLPrimitive(_pstMesh->ePrimitive);
/* Gets element number */
u32ElementNumber = ((_pstMesh->u32IndexNumber != 0) && (_pstMesh->au16IndexList != orxNULL)) ? _pstMesh->u32IndexNumber : _pstMesh->u32VertexNumber + (_pstMesh->u32VertexNumber >> 1);
/* Fills VBO */
glBufferData(GL_ARRAY_BUFFER, (GLsizei)(_pstMesh->u32VertexNumber * sizeof(orxDISPLAY_ANDROID_VERTEX)), _pstMesh->astVertexList, GL_STREAM_DRAW);
glASSERT();
/* Has index buffer? */
if((_pstMesh->au16IndexList != orxNULL)
&& (_pstMesh->u32IndexNumber > 1))
{
/* Fills IBO */
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizei)(_pstMesh->u32IndexNumber * sizeof(GLushort)), _pstMesh->au16IndexList, GL_STREAM_DRAW);
glASSERT();
/* Updates flags */
orxFLAG_SET(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_CUSTOM_IBO, orxDISPLAY_KU32_STATIC_FLAG_NONE);
}
/* Updates buffer index */
sstDisplay.s32BufferIndex = _pstMesh->u32VertexNumber;
/* Updates element number */
sstDisplay.s32ElementNumber = u32ElementNumber;
/* Draws mesh */
orxDisplay_Android_DrawArrays();
/* Done! */
return eResult;
}
void orxFASTCALL orxDisplay_Android_DeleteBitmap(orxBITMAP *_pstBitmap)
{
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstBitmap != orxNULL);
/* Not screen? */
if(_pstBitmap != sstDisplay.pstScreen)
{
/* Loading? */
if(orxFLAG_TEST(_pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING))
{
/* Asks for deletion */
orxFLAG_SET(_pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_DELETE, orxDISPLAY_KU32_BITMAP_FLAG_NONE);
}
else
{
/* Deletes its data */
orxDisplay_Android_DeleteBitmapData(_pstBitmap);
/* Is temp bitmap? */
if(_pstBitmap == sstDisplay.pstTempBitmap)
{
/* Clears temp bitmap */
sstDisplay.pstTempBitmap = orxNULL;
}
/* Deletes it */
orxBank_Free(sstDisplay.pstBitmapBank, _pstBitmap);
}
}
/* Done! */
return;
}
orxBITMAP *orxFASTCALL orxDisplay_Android_CreateBitmap(orxU32 _u32Width, orxU32 _u32Height)
{
orxBITMAP *pstBitmap;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Allocates bitmap */
pstBitmap = (orxBITMAP *) orxBank_Allocate(sstDisplay.pstBitmapBank);
/* Valid? */
if(pstBitmap != orxNULL)
{
/* Pushes display section */
orxConfig_PushSection(orxDISPLAY_KZ_CONFIG_SECTION);
/* Inits it */
pstBitmap->bSmoothing = sstDisplay.bDefaultSmoothing;
pstBitmap->fWidth = orxU2F(_u32Width);
pstBitmap->fHeight = orxU2F(_u32Height);
pstBitmap->u32RealWidth = _u32Width;
pstBitmap->u32RealHeight = _u32Height;
pstBitmap->u32Depth = 32;
pstBitmap->fRecRealWidth = orxFLOAT_1 / orxU2F(pstBitmap->u32RealWidth);
pstBitmap->fRecRealHeight = orxFLOAT_1 / orxU2F(pstBitmap->u32RealHeight);
pstBitmap->u32DataSize = pstBitmap->u32RealWidth * pstBitmap->u32RealHeight * 4 * sizeof(orxU8);
pstBitmap->zLocation = orxSTRING_EMPTY;
pstBitmap->stFilenameID = orxSTRINGID_UNDEFINED;
pstBitmap->u32Flags = orxDISPLAY_KU32_BITMAP_FLAG_NONE;
orxVector_Copy(&(pstBitmap->stClip.vTL), &orxVECTOR_0);
orxVector_Set(&(pstBitmap->stClip.vBR), pstBitmap->fWidth, pstBitmap->fHeight, orxFLOAT_0);
/* Tracks video memory */
orxMEMORY_TRACK(VIDEO, pstBitmap->u32DataSize, orxTRUE);
/* Creates new texture */
glGenTextures(1, &pstBitmap->uiTexture);
glASSERT();
glBindTexture(GL_TEXTURE_2D, pstBitmap->uiTexture);
glASSERT();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pstBitmap->u32RealWidth, pstBitmap->u32RealHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (pstBitmap->bSmoothing != orxFALSE) ? GL_LINEAR : GL_NEAREST);
glASSERT();
/* Restores previous texture */
glBindTexture(GL_TEXTURE_2D, (sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] != orxNULL) ? sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit]->uiTexture : 0);
glASSERT();
/* Pops config section */
orxConfig_PopSection();
}
/* Done! */
return pstBitmap;
}
orxSTATUS orxFASTCALL orxDisplay_Android_ClearBitmap(orxBITMAP *_pstBitmap, orxRGBA _stColor)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Clears current destinations? */
if(_pstBitmap == orxNULL)
{
/* Different clear color? */
if(_stColor.u32RGBA != sstDisplay.stLastColor.u32RGBA)
{
/* Updates it */
glClearColor(orxCOLOR_NORMALIZER * orxU2F(orxRGBA_R(_stColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_G(_stColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_B(_stColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_A(_stColor)));
glASSERT();
/* Stores it */
sstDisplay.stLastColor.u32RGBA = _stColor.u32RGBA;
}
/* Clears the color buffer with given color */
glClear(GL_COLOR_BUFFER_BIT);
glASSERT();
}
else
{
orxBITMAP *apstBackupBitmap[orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER];
orxU32 u32BackupBitmapCount;
/* Backups current destinations */
orxMemory_Copy(apstBackupBitmap, sstDisplay.apstDestinationBitmapList, sstDisplay.u32DestinationBitmapCount * sizeof(orxBITMAP *));
u32BackupBitmapCount = sstDisplay.u32DestinationBitmapCount;
/* Sets new destination bitmap */
if(orxDisplay_Android_SetDestinationBitmaps(&_pstBitmap, 1) != orxSTATUS_FAILURE)
{
/* Different clear color? */
if(_stColor.u32RGBA != sstDisplay.stLastColor.u32RGBA)
{
/* Updates it */
glClearColor(orxCOLOR_NORMALIZER * orxU2F(orxRGBA_R(_stColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_G(_stColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_B(_stColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_A(_stColor)));
glASSERT();
/* Stores it */
sstDisplay.stLastColor.u32RGBA = _stColor.u32RGBA;
}
/* Clears the color buffer with given color */
glClear(GL_COLOR_BUFFER_BIT);
glASSERT();
/* Is screen and has depth buffer? */
if((_pstBitmap == sstDisplay.pstScreen) && (orxFLAG_TEST(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_DEPTHBUFFER)))
{
/* Clears depth buffer */
glClear(GL_DEPTH_BUFFER_BIT);
glASSERT();
}
/* Restores previous destinations */
orxDisplay_Android_SetDestinationBitmaps(apstBackupBitmap, u32BackupBitmapCount);
}
/* Not screen? */
else if(_pstBitmap != sstDisplay.pstScreen)
{
orxRGBA *astBuffer, *pstPixel;
/* Allocates buffer */
astBuffer = (orxRGBA *)orxMemory_Allocate(_pstBitmap->u32RealWidth * _pstBitmap->u32RealHeight * sizeof(orxRGBA), orxMEMORY_TYPE_MAIN);
/* Checks */
orxASSERT(astBuffer != orxNULL);
/* For all pixels */
for(pstPixel = astBuffer; pstPixel < astBuffer + (_pstBitmap->u32RealWidth * _pstBitmap->u32RealHeight); pstPixel++)
{
/* Sets its value */
*pstPixel = _stColor;
}
/* Binds texture */
glBindTexture(GL_TEXTURE_2D, _pstBitmap->uiTexture);
glASSERT();
/* Updates texture */
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, (GLsizei)_pstBitmap->u32RealWidth, (GLsizei)_pstBitmap->u32RealHeight, GL_RGBA, GL_UNSIGNED_BYTE, astBuffer);
glASSERT();
/* Restores previous texture */
glBindTexture(GL_TEXTURE_2D, (sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] != orxNULL) ? sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit]->uiTexture : 0);
glASSERT();
/* Frees buffer */
orxMemory_Free(astBuffer);
}
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetBlendMode(orxDISPLAY_BLEND_MODE _eBlendMode)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* New blend mode? */
if(_eBlendMode != sstDisplay.eLastBlendMode)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Stores it */
sstDisplay.eLastBlendMode = _eBlendMode;
/* Depending on blend mode */
switch(_eBlendMode)
{
case orxDISPLAY_BLEND_MODE_ALPHA:
{
glEnable(GL_BLEND);
glASSERT();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glASSERT();
break;
}
case orxDISPLAY_BLEND_MODE_MULTIPLY:
{
glEnable(GL_BLEND);
glASSERT();
glBlendFunc(GL_DST_COLOR, GL_ZERO);
glASSERT();
break;
}
case orxDISPLAY_BLEND_MODE_ADD:
{
glEnable(GL_BLEND);
glASSERT();
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glASSERT();
break;
}
case orxDISPLAY_BLEND_MODE_PREMUL:
{
glEnable(GL_BLEND);
glASSERT();
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glASSERT();
break;
}
default:
{
glDisable(GL_BLEND);
glASSERT();
break;
}
}
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_Swap()
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Swaps buffers */
eglSwapBuffers(sstDisplay.display, sstDisplay.surface);
eglASSERT();
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetBitmapData(orxBITMAP *_pstBitmap, const orxU8 *_au8Data, orxU32 _u32ByteNumber)
{
orxSTATUS eResult;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstBitmap != orxNULL);
orxASSERT(_au8Data != orxNULL);
/* Not loading? */
if(!orxFLAG_TEST(_pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING))
{
orxU32 u32Width, u32Height;
/* Gets bitmap's size */
u32Width = orxF2U(_pstBitmap->fWidth);
u32Height = orxF2U(_pstBitmap->fHeight);
/* Valid? */
if((_pstBitmap != sstDisplay.pstScreen) && (_u32ByteNumber == u32Width * u32Height * sizeof(orxRGBA)))
{
orxU8 *pu8ImageBuffer;
pu8ImageBuffer = (orxU8 *)_au8Data;
/* Binds texture */
glBindTexture(GL_TEXTURE_2D, _pstBitmap->uiTexture);
glASSERT();
/* Updates its content */
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, _pstBitmap->u32RealWidth, _pstBitmap->u32RealHeight, GL_RGBA, GL_UNSIGNED_BYTE, pu8ImageBuffer);
glASSERT();
/* Restores previous texture */
glBindTexture(GL_TEXTURE_2D, (sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] != orxNULL) ? sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit]->uiTexture : 0);
glASSERT();
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Screen? */
if(_pstBitmap == sstDisplay.pstScreen)
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set bitmap data: can't use screen as destination bitmap.");
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set bitmap data for [%s]: format needs to be RGBA.", _pstBitmap->zLocation);
}
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set bitmap data for [%s]: bitmap is not done loading.", _pstBitmap->zLocation);
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_GetBitmapData(const orxBITMAP *_pstBitmap, orxU8 *_au8Data, orxU32 _u32ByteNumber)
{
orxSTATUS eResult;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstBitmap != orxNULL);
orxASSERT(_au8Data != orxNULL);
/* Not loading? */
if(!orxFLAG_TEST(_pstBitmap->u32Flags, orxDISPLAY_KU32_BITMAP_FLAG_LOADING))
{
orxU32 u32BufferSize;
/* Gets buffer size */
u32BufferSize = orxF2U(_pstBitmap->fWidth * _pstBitmap->fHeight) * 4 * sizeof(orxU8);
/* Is size matching? */
if(_u32ByteNumber == u32BufferSize)
{
orxBITMAP *apstBackupBitmap[orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER];
orxU32 u32BackupBitmapCount;
/* Backups current destinations */
orxMemory_Copy(apstBackupBitmap, sstDisplay.apstDestinationBitmapList, sstDisplay.u32DestinationBitmapCount * sizeof(orxBITMAP *));
u32BackupBitmapCount = sstDisplay.u32DestinationBitmapCount;
/* Sets new destination bitmap */
if((eResult = orxDisplay_Android_SetDestinationBitmaps((orxBITMAP **)&_pstBitmap, 1)) != orxSTATUS_FAILURE)
{
orxU8 *pu8ImageBuffer;
/* Allocates buffer */
pu8ImageBuffer = (_pstBitmap != sstDisplay.pstScreen) ? _au8Data : (orxU8 *)orxMemory_Allocate(_pstBitmap->u32RealWidth * _pstBitmap->u32RealHeight * 4 * sizeof(orxU8), orxMEMORY_TYPE_VIDEO);
/* Checks */
orxASSERT(pu8ImageBuffer != orxNULL);
/* Reads OpenGL data */
glReadPixels(0, 0, _pstBitmap->u32RealWidth, _pstBitmap->u32RealHeight, GL_RGBA, GL_UNSIGNED_BYTE, pu8ImageBuffer);
glASSERT();
if(_pstBitmap == sstDisplay.pstScreen)
{
orxRGBA stOpaque;
orxU32 u32LineSize, u32RealLineSize, u32SrcOffset, u32DstOffset, i;
/* Sets opaque pixel */
stOpaque = orx2RGBA(0x00, 0x00, 0x00, 0xFF);
/* Gets line sizes */
u32LineSize = orxF2U(_pstBitmap->fWidth) * 4 * sizeof(orxU8);
u32RealLineSize = _pstBitmap->u32RealWidth * 4 * sizeof(orxU8);
/* For all lines */
for(i = 0, u32SrcOffset = u32RealLineSize * (_pstBitmap->u32RealHeight - orxF2U(_pstBitmap->fHeight)), u32DstOffset = u32LineSize * (orxF2U(_pstBitmap->fHeight) - 1);
i < orxF2U(_pstBitmap->fHeight);
i++, u32SrcOffset += u32RealLineSize, u32DstOffset -= u32LineSize)
{
orxU32 j;
/* For all columns */
for(j = 0; j < orxF2U(_pstBitmap->fWidth); j++)
{
orxRGBA stPixel;
/* Gets opaque pixel */
stPixel.u32RGBA = ((orxRGBA *)(pu8ImageBuffer + u32SrcOffset))[j].u32RGBA | stOpaque.u32RGBA;
/* Stores it */
((orxRGBA *)(_au8Data + u32DstOffset))[j] = stPixel;
}
}
/* Deletes buffer */
orxMemory_Free(pu8ImageBuffer);
}
/* Restores previous destinations */
orxDisplay_Android_SetDestinationBitmaps(apstBackupBitmap, u32BackupBitmapCount);
}
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't get bitmap data for [%s] as the buffer size is %u when it should be %u.", _pstBitmap->zLocation, _u32ByteNumber, u32BufferSize);
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set bitmap data for [%s]: bitmap is not done loading.", _pstBitmap->zLocation);
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetDestinationBitmaps(orxBITMAP **_apstBitmapList, orxU32 _u32Number)
{
orxU32 i, u32Number;
orxBOOL bUseFrameBuffer = orxFALSE;
orxFLOAT fOrthoRight, fOrthoBottom;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_apstBitmapList != orxNULL)
/* Too many destinations? */
if(_u32Number > (orxU32)sstDisplay.iDrawBufferNumber)
{
/* Outputs logs */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can only attach the first <%d> bitmaps as destinations, out of the <%u> requested.", sstDisplay.iDrawBufferNumber, _u32Number);
/* Updates bitmap count */
u32Number = (orxU32)sstDisplay.iDrawBufferNumber;
}
else
{
/* Gets bitmap count */
u32Number = _u32Number;
}
/* Has destinations? */
if(u32Number != 0)
{
orxBOOL bDraw;
/* Updates draw status */
bDraw = ((_apstBitmapList[0] != sstDisplay.apstDestinationBitmapList[0]) || (u32Number != sstDisplay.u32DestinationBitmapCount)) ? orxTRUE : orxFALSE;
/* Not screen? */
if((_apstBitmapList[0] != orxNULL) && (_apstBitmapList[0] != sstDisplay.pstScreen))
{
orxFLOAT fWidth, fHeight;
/* Checks */
orxASSERT(_apstBitmapList[0] != orxNULL);
/* Gets first destination width & height */
fWidth = _apstBitmapList[0]->fWidth;
fHeight = _apstBitmapList[0]->fHeight;
/* For all other destination bitmaps */
for(i = 1; (i < u32Number) && (eResult != orxSTATUS_FAILURE); i++)
{
orxBITMAP *pstBitmap;
/* Gets it */
pstBitmap = _apstBitmapList[i];
/* Checks */
orxASSERT(pstBitmap != orxNULL);
orxASSERT((pstBitmap != sstDisplay.pstScreen) && "Can only use screen as bitmap destination by itself.");
/* Valid? */
if(pstBitmap != orxNULL)
{
/* Same size? */
if((pstBitmap->fWidth == fWidth) && (pstBitmap->fHeight == fHeight))
{
/* Different than previous? */
if(pstBitmap != sstDisplay.apstDestinationBitmapList[i])
{
/* Updates draw status */
bDraw = orxTRUE;
}
}
else
{
/* Logs message */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't set bitmap destinations as they have different dimensions: (%f, %f) != (%f, %f).", pstBitmap->fWidth, pstBitmap->fHeight, fWidth, fHeight);
/* Updates result */
eResult = orxSTATUS_FAILURE;
break;
}
}
}
/* Updates status */
bUseFrameBuffer = orxTRUE;
}
else
{
/* Has destination? */
if(_apstBitmapList[0] != orxNULL)
{
/* Checks */
orxASSERT((_u32Number == 1) && "Can only use screen as bitmap destination by itself.");
/* Multiple destinations? */
if(_u32Number != 1)
{
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
}
else
{
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
}
/* Success? */
if(eResult != orxSTATUS_FAILURE)
{
orxU32 j;
/* Should draw? */
if(bDraw != orxFALSE)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
}
/* Using framebuffer? */
if(bUseFrameBuffer != orxFALSE)
{
/* Different framebuffer? */
if(sstDisplay.uiFrameBuffer != sstDisplay.uiLastFrameBuffer)
{
/* Binds frame buffer */
glBindFramebuffer(GL_FRAMEBUFFER, sstDisplay.uiFrameBuffer);
glASSERT();
/* Updates status */
sstDisplay.uiLastFrameBuffer = sstDisplay.uiFrameBuffer;
}
}
/* For all destination bitmaps */
for(i = 0; i < u32Number; i++)
{
orxBITMAP *pstBitmap;
/* Gets it */
pstBitmap = _apstBitmapList[i];
/* Screen? */
if(pstBitmap == sstDisplay.pstScreen)
{
/* Different destination bitmap? */
if(pstBitmap != sstDisplay.apstDestinationBitmapList[i])
{
/* Different framebuffer? */
if(sstDisplay.uiFrameBuffer != 0)
{
/* Binds default frame buffer */
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glASSERT();
/* Updates status */
sstDisplay.uiLastFrameBuffer = 0;
}
}
}
/* Valid texture? */
else if(pstBitmap != orxNULL)
{
/* Links texture to it */
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, pstBitmap->uiTexture, 0);
glASSERT();
}
else
{
/* Updates result */
eResult = orxSTATUS_FAILURE;
break;
}
/* Stores new destination bitmap */
sstDisplay.apstDestinationBitmapList[i] = pstBitmap;
}
/* Updates count */
sstDisplay.u32DestinationBitmapCount = i;
/* Using framebuffer? */
if(bUseFrameBuffer != orxFALSE)
{
/* For all previous destinations */
for(j = i; j < (orxU32)sstDisplay.iDrawBufferNumber; j++)
{
/* Removes previous bound texture */
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + j, GL_TEXTURE_2D, 0, 0);
glASSERT();
}
/* Supports more than a single draw buffer? */
if((sstDisplay.iDrawBufferNumber > 1) && (i != 0))
{
/* Updates draw buffers */
glDrawBuffers((GLsizei)i, sstDisplay.aeDrawBufferList);
glASSERT();
}
}
/* For all previous destinations */
for(j = i; j < (orxU32)sstDisplay.iDrawBufferNumber; j++)
{
/* Clears it */
sstDisplay.apstDestinationBitmapList[j] = orxNULL;
}
/* Updates result */
eResult = (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) ? orxSTATUS_SUCCESS : orxSTATUS_FAILURE;
glASSERT();
}
}
/* Success? */
if(eResult != orxSTATUS_FAILURE)
{
GLint iX, iY;
GLsizei iWidth, iHeight;
/* Is screen? */
if(sstDisplay.apstDestinationBitmapList[0] == sstDisplay.pstScreen)
{
/* Updates viewport info */
iX = 0;
iY = 0;
iWidth = (GLsizei)orxF2S(sstDisplay.apstDestinationBitmapList[0]->fWidth);
iHeight = (GLsizei)orxF2S(sstDisplay.apstDestinationBitmapList[0]->fHeight);
/* Updates ortho info */
fOrthoRight = sstDisplay.apstDestinationBitmapList[0]->fWidth;
fOrthoBottom = sstDisplay.apstDestinationBitmapList[0]->fHeight;
}
else
{
/* Supports more than a single draw buffer? */
if(sstDisplay.iDrawBufferNumber > 1)
{
/* Updates draw buffers */
glDrawBuffers((GLsizei)sstDisplay.u32DestinationBitmapCount, sstDisplay.aeDrawBufferList);
glASSERT();
}
/* Updates viewport info */
iX = 0;
iY = 0;
iWidth = (GLsizei)orxF2S(sstDisplay.apstDestinationBitmapList[0]->fWidth);
iHeight = (GLsizei)orxF2S(sstDisplay.apstDestinationBitmapList[0]->fHeight);
/* Updates ortho info */
fOrthoRight = sstDisplay.apstDestinationBitmapList[0]->fWidth;
fOrthoBottom = -sstDisplay.apstDestinationBitmapList[0]->fHeight;
}
/* Should update viewport? */
if((iX != sstDisplay.iLastViewportX)
|| (iY != sstDisplay.iLastViewportY)
|| (iWidth != sstDisplay.iLastViewportWidth)
|| (iHeight != sstDisplay.iLastViewportHeight))
{
/* Inits viewport */
glViewport(iX, iY, iWidth, iHeight);
glASSERT();
/* Stores its info */
sstDisplay.iLastViewportX = iX;
sstDisplay.iLastViewportY = iY;
sstDisplay.iLastViewportWidth = iWidth;
sstDisplay.iLastViewportHeight = iHeight;
}
/* Should update the orthogonal projection? */
if((fOrthoRight != sstDisplay.fLastOrthoRight)
|| (fOrthoBottom != sstDisplay.fLastOrthoBottom))
{
/* Stores data */
sstDisplay.fLastOrthoRight = fOrthoRight;
sstDisplay.fLastOrthoBottom = fOrthoBottom;
/* Inits projection matrix */
(fOrthoBottom >= orxFLOAT_0)
? orxDisplay_Android_OrthoProjMatrix(&(sstDisplay.mProjectionMatrix), orxFLOAT_0, fOrthoRight, fOrthoBottom, orxFLOAT_0, -orxFLOAT_1, orxFLOAT_1)
: orxDisplay_Android_OrthoProjMatrix(&(sstDisplay.mProjectionMatrix), orxFLOAT_0, fOrthoRight, orxFLOAT_0, -fOrthoBottom, -orxFLOAT_1, orxFLOAT_1);
/* Passes it to shader */
glUNIFORM(Matrix4fv, sstDisplay.pstDefaultShader->iProjectionMatrixLocation, 1, GL_FALSE, (GLfloat *)&(sstDisplay.mProjectionMatrix.aafValueList[0][0]));
}
}
/* Done! */
return eResult;
}
orxU32 orxFASTCALL orxDisplay_Android_GetBitmapID(const orxBITMAP *_pstBitmap)
{
orxU32 u32Result;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_pstBitmap != orxNULL) && (_pstBitmap != sstDisplay.pstScreen));
/* Updates result */
u32Result = (orxU32)_pstBitmap->uiTexture;
/* Done! */
return u32Result;
}
orxSTATUS orxFASTCALL orxDisplay_Android_TransformBitmap(const orxBITMAP *_pstSrc, const orxDISPLAY_TRANSFORM *_pstTransform, orxRGBA _stColor, orxDISPLAY_SMOOTHING _eSmoothing, orxDISPLAY_BLEND_MODE _eBlendMode)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstSrc != sstDisplay.pstScreen);
orxASSERT((_pstSrc == orxNULL) || (_pstTransform != orxNULL));
/* No bitmap? */
if(_pstSrc == orxNULL)
{
/* Has something to display? */
if(sstDisplay.s32BufferIndex > 0)
{
/* Draws arrays */
orxDisplay_Android_DrawArrays();
}
/* Sets buffer mode */
orxDisplay_Android_SetBufferMode(orxDISPLAY_BUFFER_MODE_INDIRECT);
/* Defines the vertex list */
sstDisplay.astVertexList[0].fX =
sstDisplay.astVertexList[1].fX = sstDisplay.apstDestinationBitmapList[0]->stClip.vTL.fX;
sstDisplay.astVertexList[2].fX =
sstDisplay.astVertexList[3].fX = sstDisplay.apstDestinationBitmapList[0]->stClip.vBR.fX;
sstDisplay.astVertexList[1].fY =
sstDisplay.astVertexList[3].fY = sstDisplay.apstDestinationBitmapList[0]->stClip.vTL.fY;
sstDisplay.astVertexList[0].fY =
sstDisplay.astVertexList[2].fY = sstDisplay.apstDestinationBitmapList[0]->stClip.vBR.fY;
/* Defines the texture coord list */
sstDisplay.astVertexList[0].fU =
sstDisplay.astVertexList[1].fU = 0.0f;
sstDisplay.astVertexList[2].fU =
sstDisplay.astVertexList[3].fU = 1.0f;
sstDisplay.astVertexList[1].fV =
sstDisplay.astVertexList[3].fV = 0.0f;
sstDisplay.astVertexList[0].fV =
sstDisplay.astVertexList[2].fV = 1.0f;
/* Fills the color list */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].stRGBA = sstDisplay.stLastColor;
/* Updates index & element number */
sstDisplay.s32BufferIndex += 4;
sstDisplay.s32ElementNumber += 6;
/* Draws arrays */
orxDisplay_Android_DrawArrays();
}
else
{
orxDISPLAY_MATRIX mTransform;
/* Inits matrix */
orxDisplay_Android_InitMatrix(&mTransform, _pstTransform->fDstX, _pstTransform->fDstY, _pstTransform->fScaleX, _pstTransform->fScaleY, _pstTransform->fRotation, _pstTransform->fSrcX, _pstTransform->fSrcY);
/* No repeat? */
if((_pstTransform->fRepeatX == orxFLOAT_1) && (_pstTransform->fRepeatY == orxFLOAT_1))
{
/* Draws it */
orxDisplay_Android_DrawBitmap(_pstSrc, &mTransform, _stColor, _eSmoothing, _eBlendMode);
}
else
{
orxFLOAT i, j, fRecRepeatX;
GLfloat fX, fY, fWidth, fHeight, fTop, fBottom, fLeft, fRight;
/* Prepares bitmap for drawing */
orxDisplay_Android_PrepareBitmap(_pstSrc, _eSmoothing, _eBlendMode, orxDISPLAY_BUFFER_MODE_INDIRECT);
/* Inits bitmap height */
fHeight = (GLfloat) ((_pstSrc->stClip.vBR.fY - _pstSrc->stClip.vTL.fY) / _pstTransform->fRepeatY);
/* Inits texture coords */
fLeft = _pstSrc->fRecRealWidth * (_pstSrc->stClip.vTL.fX + orxDISPLAY_KF_BORDER_FIX);
fTop = _pstSrc->fRecRealHeight * (_pstSrc->stClip.vTL.fY + orxDISPLAY_KF_BORDER_FIX);
/* For all lines */
for (fY = 0.0f, i = _pstTransform->fRepeatY, fRecRepeatX = orxFLOAT_1 / _pstTransform->fRepeatX; i > orxFLOAT_0; i -= orxFLOAT_1, fY += fHeight)
{
/* Partial line? */
if(i < orxFLOAT_1)
{
/* Updates height */
fHeight *= (GLfloat) i;
/* Resets texture coords */
fRight = (GLfloat)(_pstSrc->fRecRealWidth * (_pstSrc->stClip.vBR.fX - orxDISPLAY_KF_BORDER_FIX));
fBottom = (GLfloat)(_pstSrc->fRecRealHeight * (_pstSrc->stClip.vTL.fY + (i * (_pstSrc->stClip.vBR.fY - _pstSrc->stClip.vTL.fY)) - orxDISPLAY_KF_BORDER_FIX));
}
else
{
/* Resets texture coords */
fRight = (GLfloat)(_pstSrc->fRecRealWidth * (_pstSrc->stClip.vBR.fX - orxDISPLAY_KF_BORDER_FIX));
fBottom = (GLfloat)(_pstSrc->fRecRealHeight * (_pstSrc->stClip.vBR.fY - orxDISPLAY_KF_BORDER_FIX));
}
/* Resets bitmap width */
fWidth = (GLfloat) ((_pstSrc->stClip.vBR.fX - _pstSrc->stClip.vTL.fX) * fRecRepeatX);
/* For all columns */
for (fX = 0.0f, j = _pstTransform->fRepeatX; j > orxFLOAT_0; j -= orxFLOAT_1, fX += fWidth)
{
/* Partial column? */
if(j < orxFLOAT_1)
{
/* Updates width */
fWidth *= (GLfloat) j;
/* Updates texture right coord */
fRight = (GLfloat) (_pstSrc->fRecRealWidth * (_pstSrc->stClip.vTL.fX + (j * (_pstSrc->stClip.vBR.fX - _pstSrc->stClip.vTL.fX))));
}
/* End of buffer? */
if(sstDisplay.s32BufferIndex > orxDISPLAY_KU32_VERTEX_BUFFER_SIZE - 5)
{
/* Draws arrays */
orxDisplay_Android_DrawArrays();
}
/* Outputs vertices and texture coordinates */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fX = (mTransform.vX.fX * fX) + (mTransform.vX.fY * (fY + fHeight)) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fY = (mTransform.vY.fX * fX) + (mTransform.vY.fY * (fY + fHeight)) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fX = (mTransform.vX.fX * fX) + (mTransform.vX.fY * fY) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fY = (mTransform.vY.fX * fX) + (mTransform.vY.fY * fY) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fX = (mTransform.vX.fX * (fX + fWidth)) + (mTransform.vX.fY * (fY + fHeight)) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fY = (mTransform.vY.fX * (fX + fWidth)) + (mTransform.vY.fY * (fY + fHeight)) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fX = (mTransform.vX.fX * (fX + fWidth)) + (mTransform.vX.fY * fY) + mTransform.vX.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fY = (mTransform.vY.fX * (fX + fWidth)) + (mTransform.vY.fY * fY) + mTransform.vY.fZ;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fU =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fU = fLeft;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fU =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fU = fRight;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].fV =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].fV = fTop;
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].fV =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].fV = fBottom;
/* Fills the color list */
sstDisplay.astVertexList[sstDisplay.s32BufferIndex].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 1].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 2].stRGBA =
sstDisplay.astVertexList[sstDisplay.s32BufferIndex + 3].stRGBA = _stColor;
/* Updates index & element number */
sstDisplay.s32BufferIndex += 4;
sstDisplay.s32ElementNumber += 6;
}
}
}
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SaveBitmap(const orxBITMAP *_pstBitmap, const orxSTRING _zFilename)
{
orxU32 u32BufferSize;
orxU8 *pu8ImageData;
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstBitmap != orxNULL);
orxASSERT(_zFilename != orxNULL);
/* Gets buffer size */
u32BufferSize = orxF2U(_pstBitmap->fWidth * _pstBitmap->fHeight) * 4 * sizeof(orxU8);
/* Allocates buffer */
pu8ImageData = (orxU8 *)orxMemory_Allocate(u32BufferSize, orxMEMORY_TYPE_MAIN);
/* Valid? */
if(pu8ImageData != orxNULL)
{
orxDISPLAY_SAVE_INFO *pstInfo = orxNULL;
/* Gets bitmap data */
if(orxDisplay_Android_GetBitmapData(_pstBitmap, pu8ImageData, u32BufferSize) != orxSTATUS_FAILURE)
{
/* Allocates save info */
pstInfo = (orxDISPLAY_SAVE_INFO *)orxMemory_Allocate(sizeof(orxDISPLAY_SAVE_INFO), orxMEMORY_TYPE_TEMP);
/* Valid? */
if(pstInfo != orxNULL)
{
/* Inits it */
pstInfo->pu8ImageData = pu8ImageData;
pstInfo->stFilenameID = orxString_GetID(_zFilename);
pstInfo->u32Width = orxF2U(_pstBitmap->fWidth);
pstInfo->u32Height = orxF2U(_pstBitmap->fHeight);
/* Runs asynchronous task */
eResult = orxThread_RunTask(&orxDisplay_Android_SaveBitmapData, orxNULL, orxNULL, (void *)pstInfo);
}
}
/* Failure? */
if(eResult == orxSTATUS_FAILURE)
{
/* Frees save info */
if(pstInfo != orxNULL)
{
orxMemory_Free(pstInfo);
}
/* Frees buffer */
orxMemory_Free(pu8ImageData);
}
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetTempBitmap(const orxBITMAP *_pstBitmap)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Stores it */
sstDisplay.pstTempBitmap = _pstBitmap;
/* Done! */
return eResult;
}
const orxBITMAP *orxFASTCALL orxDisplay_Android_GetTempBitmap()
{
const orxBITMAP *pstResult;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Updates result */
pstResult = sstDisplay.pstTempBitmap;
/* Done! */
return pstResult;
}
orxBITMAP *orxFASTCALL orxDisplay_Android_LoadBitmap(const orxSTRING _zFilename)
{
const orxSTRING zResourceName;
orxHANDLE hResource;
orxBITMAP *pstResult = orxNULL;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_zFilename != orxNULL);
/* Gets resource name */
zResourceName = orxResource_Locate(orxTEXTURE_KZ_RESOURCE_GROUP, _zFilename);
/* Success? */
if(zResourceName != orxNULL)
{
pstResult = (orxBITMAP *)orxBank_Allocate(sstDisplay.pstBitmapBank);
/* Valid? */
if(pstResult != orxNULL)
{
/* Inits it */
pstResult->bSmoothing = sstDisplay.bDefaultSmoothing;
pstResult->zLocation = zResourceName;
pstResult->stFilenameID = orxString_GetID(_zFilename);
pstResult->u32Flags = orxDISPLAY_KU32_BITMAP_FLAG_NONE;
/* Loads its data */
if(orxString_SearchString(_zFilename, szKTXExtention) != orxNULL)
{
if(orxDisplay_Android_LoadKTXBitmapData(pstResult) == orxSTATUS_FAILURE)
{
/* Deletes it */
orxBank_Free(sstDisplay.pstBitmapBank, pstResult);
/* Updates result */
pstResult = orxNULL;
}
}
else if(orxDisplay_Android_LoadBitmapData(pstResult) == orxSTATUS_FAILURE)
{
/* Deletes it */
orxBank_Free(sstDisplay.pstBitmapBank, pstResult);
/* Updates result */
pstResult = orxNULL;
}
}
}
/* Done! */
return pstResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_GetBitmapSize(const orxBITMAP *_pstBitmap, orxFLOAT *_pfWidth, orxFLOAT *_pfHeight)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pstBitmap != orxNULL);
orxASSERT(_pfWidth != orxNULL);
orxASSERT(_pfHeight != orxNULL);
/* Gets size */
*_pfWidth = _pstBitmap->fWidth;
*_pfHeight = _pstBitmap->fHeight;
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_GetScreenSize(orxFLOAT *_pfWidth, orxFLOAT *_pfHeight)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_pfWidth != orxNULL);
orxASSERT(_pfHeight != orxNULL);
/* Gets size */
*_pfWidth = sstDisplay.pstScreen->fWidth;
*_pfHeight = sstDisplay.pstScreen->fHeight;
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetBitmapClipping(orxBITMAP *_pstBitmap, orxU32 _u32TLX, orxU32 _u32TLY, orxU32 _u32BRX, orxU32 _u32BRY)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* No destination bitmap? */
if(_pstBitmap == orxNULL)
{
/* Defaults to destination */
_pstBitmap = sstDisplay.apstDestinationBitmapList[0];
}
/* Destination bitmap? */
if(_pstBitmap == sstDisplay.apstDestinationBitmapList[0])
{
orxU32 u32ClipX, u32ClipY, u32ClipWidth, u32ClipHeight;
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Gets new clipping values */
u32ClipX = _u32TLX;
u32ClipY = (_pstBitmap == sstDisplay.pstScreen) ? orxF2U(sstDisplay.apstDestinationBitmapList[0]->fHeight) - _u32BRY : _u32TLY;
u32ClipWidth = _u32BRX - _u32TLX;
u32ClipHeight = _u32BRY - _u32TLY;
/* Different clipping? */
if((u32ClipX != sstDisplay.u32LastClipX)
|| (u32ClipY != sstDisplay.u32LastClipY)
|| (u32ClipWidth != sstDisplay.u32LastClipWidth)
|| (u32ClipHeight != sstDisplay.u32LastClipHeight))
{
/* Sets OpenGL clipping */
glScissor((GLint)u32ClipX, (GLint)u32ClipY, (GLsizei)u32ClipWidth, (GLsizei)u32ClipHeight);
glASSERT();
/* Stores clipping values */
sstDisplay.u32LastClipX = u32ClipX;
sstDisplay.u32LastClipY = u32ClipY;
sstDisplay.u32LastClipWidth = u32ClipWidth;
sstDisplay.u32LastClipHeight = u32ClipHeight;
}
}
/* Stores clip coords */
orxVector_Set(&(_pstBitmap->stClip.vTL), orxU2F(_u32TLX), orxU2F(_u32TLY), orxFLOAT_0);
orxVector_Set(&(_pstBitmap->stClip.vBR), orxU2F(_u32BRX), orxU2F(_u32BRY), orxFLOAT_0);
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_EnableVSync(orxBOOL _bEnable)
{
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Not available */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Not available on this platform!");
/* Done! */
return eResult;
}
orxBOOL orxFASTCALL orxDisplay_Android_IsVSyncEnabled()
{
orxBOOL bResult = orxTRUE;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Not available */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Not available on this platform!");
/* Done! */
return bResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetFullScreen(orxBOOL _bFullScreen)
{
orxSTATUS eResult = orxSTATUS_FAILURE;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Not available */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Not available on this platform!");
/* Done! */
return eResult;
}
orxBOOL orxFASTCALL orxDisplay_Android_IsFullScreen()
{
orxBOOL bResult = orxTRUE;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Not available */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Not available on this platform!");
/* Done! */
return bResult;
}
orxU32 orxFASTCALL orxDisplay_Android_GetVideoModeCount()
{
orxU32 u32Result = 1;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Done! */
return u32Result;
}
orxDISPLAY_VIDEO_MODE *orxFASTCALL orxDisplay_Android_GetVideoMode(orxU32 _u32Index, orxDISPLAY_VIDEO_MODE *_pstVideoMode)
{
orxDISPLAY_VIDEO_MODE *pstResult;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Gets default mode */
_pstVideoMode->u32Width = orxF2U(sstDisplay.pstScreen->fWidth);
_pstVideoMode->u32Height = orxF2U(sstDisplay.pstScreen->fHeight);
_pstVideoMode->u32Depth = sstDisplay.u32Depth;
_pstVideoMode->u32RefreshRate = 60;
_pstVideoMode->bFullScreen = orxTRUE;
/* Updates result */
pstResult = _pstVideoMode;
/* Done! */
return pstResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetVideoMode(const orxDISPLAY_VIDEO_MODE *_pstVideoMode)
{
orxS32 i;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Has specified video mode? */
if(_pstVideoMode != orxNULL)
{
int iWidth, iHeight;
/* recreate surface */
orxAndroid_Display_DestroySurface();
eResult = orxAndroid_Display_CreateSurface();
if( eResult == orxSTATUS_SUCCESS )
{
int iDepth, iRefreshRate;
/* Gets its info */
eglQuerySurface(sstDisplay.display, sstDisplay.surface, EGL_WIDTH, &iWidth);
eglASSERT();
eglQuerySurface(sstDisplay.display, sstDisplay.surface, EGL_HEIGHT, &iHeight);
eglASSERT();
iDepth = (int)_pstVideoMode->u32Depth;
iRefreshRate = (int)_pstVideoMode->u32RefreshRate;
orxDISPLAY_EVENT_PAYLOAD stPayload;
/* Inits event payload */
orxMemory_Zero(&stPayload, sizeof(orxDISPLAY_EVENT_PAYLOAD));
stPayload.stVideoMode.u32Width = (orxU32)iWidth;
stPayload.stVideoMode.u32Height = (orxU32)iHeight;
stPayload.stVideoMode.u32Depth = (orxU32)iDepth;
stPayload.stVideoMode.u32RefreshRate = (orxU32)iRefreshRate;
stPayload.stVideoMode.u32PreviousWidth = orxF2U(sstDisplay.pstScreen->fWidth);
stPayload.stVideoMode.u32PreviousHeight = orxF2U(sstDisplay.pstScreen->fHeight);
stPayload.stVideoMode.u32PreviousDepth = sstDisplay.pstScreen->u32Depth;
stPayload.stVideoMode.u32PreviousRefreshRate = 60;
stPayload.stVideoMode.bFullScreen = _pstVideoMode->bFullScreen;
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "surface changed (%ux%u)->(%ux%u)",
stPayload.stVideoMode.u32PreviousWidth,
stPayload.stVideoMode.u32PreviousHeight,
stPayload.stVideoMode.u32Width,
stPayload.stVideoMode.u32Height);
/* Stores screen info */
sstDisplay.pstScreen->fWidth = orxS2F(iWidth);
sstDisplay.pstScreen->fHeight = orxS2F(iHeight);
sstDisplay.pstScreen->u32RealWidth = (orxU32)iWidth;
sstDisplay.pstScreen->u32RealHeight = (orxU32)iHeight;
sstDisplay.pstScreen->u32Depth = (orxU32)iDepth;
sstDisplay.pstScreen->bSmoothing = sstDisplay.bDefaultSmoothing;
sstDisplay.pstScreen->fRecRealWidth = orxFLOAT_1 / orxU2F(sstDisplay.pstScreen->u32RealWidth);
sstDisplay.pstScreen->fRecRealHeight = orxFLOAT_1 / orxU2F(sstDisplay.pstScreen->u32RealHeight);
sstDisplay.pstScreen->u32DataSize = sstDisplay.pstScreen->u32RealWidth * sstDisplay.pstScreen->u32RealHeight * 4 * sizeof(orxU8);
/* Updates bound texture */
sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] = orxNULL;
/* Clears destination bitmap */
sstDisplay.apstDestinationBitmapList[0] = orxNULL;
sstDisplay.u32DestinationBitmapCount = 1;
/* Clears new display surface */
glScissor(0, 0, (GLsizei)sstDisplay.pstScreen->u32RealWidth, (GLsizei)sstDisplay.pstScreen->u32RealHeight);
glASSERT();
glClearColor(orxCOLOR_NORMALIZER * orxU2F(orxRGBA_R(sstDisplay.stLastColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_G(sstDisplay.stLastColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_B(sstDisplay.stLastColor)), orxCOLOR_NORMALIZER * orxU2F(orxRGBA_A(sstDisplay.stLastColor)));
glASSERT();
glClear(GL_COLOR_BUFFER_BIT);
glASSERT();
/* Stores clipping values */
sstDisplay.u32LastClipX = 0;
sstDisplay.u32LastClipY = 0;
sstDisplay.u32LastClipWidth = sstDisplay.pstScreen->u32RealWidth;
sstDisplay.u32LastClipHeight = sstDisplay.pstScreen->u32RealHeight;
/* Stores screen depth & refresh rate */
sstDisplay.u32Depth = (orxU32)iDepth;
/* Sends event */
orxEVENT_SEND(orxEVENT_TYPE_DISPLAY, orxDISPLAY_EVENT_SET_VIDEO_MODE, orxNULL, orxNULL, &stPayload);
}
}
/* Binds buffers */
glBindBuffer(GL_ARRAY_BUFFER, sstDisplay.uiVertexBuffer);
glASSERT();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sstDisplay.uiIndexBuffer);
glASSERT();
/* Enables vextex attribute arrays */
glEnableVertexAttribArray(orxDISPLAY_ATTRIBUTE_LOCATION_VERTEX);
glASSERT();
glEnableVertexAttribArray(orxDISPLAY_ATTRIBUTE_LOCATION_TEXCOORD);
glASSERT();
glEnableVertexAttribArray(orxDISPLAY_ATTRIBUTE_LOCATION_COLOR);
glASSERT();
/* Sets vextex attribute arrays */
glVertexAttribPointer(orxDISPLAY_ATTRIBUTE_LOCATION_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(orxDISPLAY_VERTEX), (GLvoid *)offsetof(orxDISPLAY_ANDROID_VERTEX, fX));
glASSERT();
glVertexAttribPointer(orxDISPLAY_ATTRIBUTE_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(orxDISPLAY_VERTEX), (GLvoid *)offsetof(orxDISPLAY_ANDROID_VERTEX, fU));
glASSERT();
glVertexAttribPointer(orxDISPLAY_ATTRIBUTE_LOCATION_COLOR, 4, GL_UNSIGNED_BYTE, GL_FALSE, sizeof(orxDISPLAY_VERTEX), (GLvoid *)offsetof(orxDISPLAY_ANDROID_VERTEX, stRGBA));
glASSERT();
/* Has depth buffer? */
if(orxFLAG_TEST(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_DEPTHBUFFER))
{
/* Enables depth test */
glEnable(GL_DEPTH_TEST);
glASSERT();
/* Sets depth function */
glDepthFunc(GL_LEQUAL);
glASSERT();
/* Clears depth buffer */
glClearDepthf(1.0f);
glASSERT();
glClear(GL_DEPTH_BUFFER_BIT);
glASSERT();
}
else
{
glDisable(GL_DEPTH_TEST);
glASSERT();
}
/* Common init */
glEnable(GL_SCISSOR_TEST);
glASSERT();
glDisable(GL_CULL_FACE);
glASSERT();
glDisable(GL_STENCIL_TEST);
glASSERT();
/* Updates active texture unit */
sstDisplay.s32ActiveTextureUnit = 0;
/* Selects first texture unit */
glActiveTexture(GL_TEXTURE0);
glASSERT();
/* Uses default shader */
orxDisplay_Android_StopShader(orxNULL);
/* Inits matrices */
sstDisplay.fLastOrthoRight = (sstDisplay.apstDestinationBitmapList[0] != orxNULL) ? sstDisplay.apstDestinationBitmapList[0]->fWidth : sstDisplay.pstScreen->fWidth;
sstDisplay.fLastOrthoBottom = (sstDisplay.apstDestinationBitmapList[0] != orxNULL)
? (sstDisplay.apstDestinationBitmapList[0] == sstDisplay.pstScreen)
? sstDisplay.apstDestinationBitmapList[0]->fHeight
: -sstDisplay.apstDestinationBitmapList[0]->fHeight
: sstDisplay.pstScreen->fHeight;
(sstDisplay.fLastOrthoBottom >= 0.0)
? orxDisplay_Android_OrthoProjMatrix(&(sstDisplay.mProjectionMatrix), orxFLOAT_0, sstDisplay.fLastOrthoRight, sstDisplay.fLastOrthoBottom, orxFLOAT_0, -orxFLOAT_1, orxFLOAT_1)
: orxDisplay_Android_OrthoProjMatrix(&(sstDisplay.mProjectionMatrix), orxFLOAT_0, sstDisplay.fLastOrthoRight, orxFLOAT_0, -sstDisplay.fLastOrthoBottom, -orxFLOAT_1, orxFLOAT_1);
/* Passes it to shader */
glUNIFORM(Matrix4fv, sstDisplay.pstDefaultShader->iProjectionMatrixLocation, 1, GL_FALSE, (GLfloat *)&(sstDisplay.mProjectionMatrix.aafValueList[0][0]));
/* For all texture units */
for(i = 0; i < (orxU32)sstDisplay.iTextureUnitNumber; i++)
{
/* Clears its bound bitmap */
sstDisplay.apstBoundBitmapList[i] = orxNULL;
/* Clears its MRU timestamp */
sstDisplay.adMRUBitmapList[i] = orxDOUBLE_0;
}
/* Clears last modes */
sstDisplay.eLastBlendMode = orxDISPLAY_BLEND_MODE_NUMBER;
sstDisplay.eLastBufferMode= orxDISPLAY_BUFFER_MODE_NUMBER;
/* Resets primitive */
sstDisplay.ePrimitive = orxDISPLAY_KE_DEFAULT_PRIMITIVE;
/* Done! */
return eResult;
}
orxBOOL orxFASTCALL orxDisplay_Android_IsVideoModeAvailable(const orxDISPLAY_VIDEO_MODE *_pstVideoMode)
{
orxBOOL bResult = orxTRUE;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Not available */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Not available on this platform!");
/* Done! */
return bResult;
}
static orxSTATUS orxFASTCALL orxDisplay_Android_EventHandler(const orxEVENT *_pstEvent)
{
/* Render stop? */
if(_pstEvent->eType == orxEVENT_TYPE_RENDER && _pstEvent->eID == orxRENDER_EVENT_STOP)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
}
if(_pstEvent->eType == orxANDROID_EVENT_TYPE_SURFACE && _pstEvent->eID == orxANDROID_EVENT_SURFACE_DESTROYED)
{
orxAndroid_Display_DestroySurface();
}
if(_pstEvent->eType == orxANDROID_EVENT_TYPE_SURFACE && _pstEvent->eID == orxANDROID_EVENT_SURFACE_CREATED)
{
orxAndroid_Display_CreateSurface();
}
if(_pstEvent->eType == orxANDROID_EVENT_TYPE_SURFACE && _pstEvent->eID == orxANDROID_EVENT_SURFACE_CHANGED)
{
orxANDROID_SURFACE_CHANGED_EVENT *pstSurfaceChangedEvent;
/* Gets payload */
pstSurfaceChangedEvent = (orxANDROID_SURFACE_CHANGED_EVENT *)_pstEvent->pstPayload;
/* Valid? */
if((pstSurfaceChangedEvent->u32Width > 0) && (pstSurfaceChangedEvent->u32Height > 0))
{
orxDISPLAY_VIDEO_MODE stVideoMode;
/* Inits video mode */
stVideoMode.u32Width = pstSurfaceChangedEvent->u32Width;
stVideoMode.u32Height = pstSurfaceChangedEvent->u32Height;
stVideoMode.u32Depth = sstDisplay.u32Depth;
stVideoMode.u32RefreshRate = 60;
stVideoMode.bFullScreen = orxTRUE;
/* Applies it */
orxDisplay_Android_SetVideoMode(&stVideoMode);
}
}
/* Done! */
return orxSTATUS_SUCCESS;
}
/*
* init android display
*/
orxSTATUS orxFASTCALL orxDisplay_Android_Init()
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Was not already initialized? */
if(!(sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY))
{
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "orxDisplay_Android_Init()");
/* Cleans static controller */
orxMemory_Zero(&sstDisplay, sizeof(orxDISPLAY_STATIC));
sstDisplay.surface = EGL_NO_SURFACE;
sstDisplay.context = EGL_NO_CONTEXT;
sstDisplay.display = EGL_NO_DISPLAY;
sstDisplay.config = orxNULL;
orxU32 i;
GLushort u16Index;
/* Stores stbi callbacks */
sstDisplay.stSTBICallbacks.read = orxDisplay_Android_ReadSTBICallback;
sstDisplay.stSTBICallbacks.skip = orxDisplay_Android_SkipSTBICallback;
sstDisplay.stSTBICallbacks.eof = orxDisplay_Android_EOFSTBICallback;
/* For all indices */
for (i = 0, u16Index = 0; i < orxDISPLAY_KU32_INDEX_BUFFER_SIZE; i += 6, u16Index += 4)
{
/* Computes them */
sstDisplay.au16IndexList[i] = u16Index;
sstDisplay.au16IndexList[i + 1] = u16Index;
sstDisplay.au16IndexList[i + 2] = u16Index + 1;
sstDisplay.au16IndexList[i + 3] = u16Index + 2;
sstDisplay.au16IndexList[i + 4] = u16Index + 3;
sstDisplay.au16IndexList[i + 5] = u16Index + 3;
}
/* Creates banks */
sstDisplay.pstBitmapBank = orxBank_Create(orxDISPLAY_KU32_BITMAP_BANK_SIZE, sizeof(orxBITMAP), orxBANK_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN);
sstDisplay.pstShaderBank = orxBank_Create(orxDISPLAY_KU32_SHADER_BANK_SIZE, sizeof(orxDISPLAY_SHADER), orxBANK_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN);
/* Valid? */
if(sstDisplay.pstBitmapBank != orxNULL
&& (sstDisplay.pstShaderBank != orxNULL))
{
orxDISPLAY_EVENT_PAYLOAD stPayload;
const orxSTRING zGlRenderer;
const orxSTRING zGlVersion;
int32_t width, height;
/* Pushes display section */
orxConfig_PushSection(orxDISPLAY_KZ_CONFIG_SECTION);
/* Depth buffer? */
if(orxConfig_GetBool(orxDISPLAY_KZ_CONFIG_DEPTHBUFFER) != orxFALSE)
{
/* Updates flags */
sstDisplay.u32Flags = orxDISPLAY_KU32_STATIC_FLAG_DEPTHBUFFER;
}
else
{
sstDisplay.u32Flags = orxDISPLAY_KU32_STATIC_FLAG_NONE;
}
sstDisplay.u32Depth = orxConfig_HasValue(orxDISPLAY_KZ_CONFIG_DEPTH) ? orxConfig_GetU32(orxDISPLAY_KZ_CONFIG_DEPTH) : 24;
// Create OpenGL ES Context
orxAndroid_Display_CreateContext();
// Create OpenGL ES Surface
if(orxAndroid_Display_CreateSurface() == orxSTATUS_FAILURE)
{
orxConfig_PopSection();
return orxSTATUS_FAILURE;
}
eglQuerySurface(sstDisplay.display, sstDisplay.surface, EGL_WIDTH, &width);
eglASSERT();
eglQuerySurface(sstDisplay.display, sstDisplay.surface, EGL_HEIGHT, &height);
eglASSERT();
zGlRenderer = (const orxSTRING) glGetString(GL_RENDERER);
glASSERT();
zGlVersion = (const orxSTRING) glGetString(GL_VERSION);
glASSERT();
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Renderer: %s, Version: %s", zGlRenderer, zGlVersion);
/* Adds event handler */
orxEvent_AddHandler(orxEVENT_TYPE_RENDER, orxDisplay_Android_EventHandler);
orxEvent_AddHandler(orxANDROID_EVENT_TYPE_SURFACE, orxDisplay_Android_EventHandler);
orxEvent_SetHandlerIDFlags(orxDisplay_Android_EventHandler, orxEVENT_TYPE_RENDER, orxNULL, orxEVENT_GET_FLAG(orxRENDER_EVENT_STOP), orxEVENT_KU32_MASK_ID_ALL);
/* Inits default values */
sstDisplay.bDefaultSmoothing = orxConfig_GetBool(orxDISPLAY_KZ_CONFIG_SMOOTH);
sstDisplay.eLastBlendMode = orxDISPLAY_BLEND_MODE_NUMBER;
sstDisplay.eLastBufferMode = orxDISPLAY_BUFFER_MODE_NUMBER;
sstDisplay.ePrimitive = orxDISPLAY_KE_DEFAULT_PRIMITIVE;
/* Allocates screen bitmap */
sstDisplay.pstScreen = (orxBITMAP *) orxBank_Allocate(sstDisplay.pstBitmapBank);
orxMemory_Zero(sstDisplay.pstScreen, sizeof(orxBITMAP));
sstDisplay.pstScreen->fWidth = orxU2F(width);
sstDisplay.pstScreen->fHeight = orxU2F(height);
sstDisplay.pstScreen->u32RealWidth = orxF2U(sstDisplay.pstScreen->fWidth);
sstDisplay.pstScreen->u32RealHeight = orxF2U(sstDisplay.pstScreen->fHeight);
sstDisplay.pstScreen->fRecRealWidth = orxFLOAT_1 / orxU2F(sstDisplay.pstScreen->u32RealWidth);
sstDisplay.pstScreen->fRecRealHeight = orxFLOAT_1 / orxU2F(sstDisplay.pstScreen->u32RealHeight);
sstDisplay.pstScreen->u32DataSize = sstDisplay.pstScreen->u32RealWidth * sstDisplay.pstScreen->u32RealHeight * 4 * sizeof(orxU8);
orxVector_Copy(&(sstDisplay.pstScreen->stClip.vTL), &orxVECTOR_0);
orxVector_Set(&(sstDisplay.pstScreen->stClip.vBR), sstDisplay.pstScreen->fWidth, sstDisplay.pstScreen->fHeight, orxFLOAT_0);
glGenFramebuffers(1, &sstDisplay.uiFrameBuffer);
glASSERT();
/* Updates config info */
orxConfig_SetU32(orxDISPLAY_KZ_CONFIG_DEPTH, sstDisplay.u32Depth);
/* Pops config section */
orxConfig_PopSection();
/* Gets max texture unit number */
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &(sstDisplay.iTextureUnitNumber));
glASSERT();
sstDisplay.iTextureUnitNumber = orxMIN(sstDisplay.iTextureUnitNumber, orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER);
if(orxString_SearchString(zGlVersion, "OpenGL ES 3.") && gl3stubInit())
{
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "OpenGL ES 3 inited!");
glGetIntegerv(GL_MAX_DRAW_BUFFERS, &sstDisplay.iDrawBufferNumber);
glASSERT();
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "GL_MAX_DRAW_BUFFERS = %d", sstDisplay.iDrawBufferNumber);
sstDisplay.iDrawBufferNumber = orxMIN(sstDisplay.iDrawBufferNumber, orxDISPLAY_KU32_MAX_TEXTURE_UNIT_NUMBER);
}
else
{
sstDisplay.iDrawBufferNumber = 1;
}
/* Fills the list of draw buffer symbols */
for(i = 0; i < (orxU32)sstDisplay.iDrawBufferNumber; i++)
{
sstDisplay.aeDrawBufferList[i] = GL_COLOR_ATTACHMENT0 + i;
}
/* hack for old Adreno drivers */
if(orxString_SearchString(zGlRenderer, "Adreno") && orxString_SearchString(zGlVersion, "OpenGL ES 2.0"))
{
orxU32 u32Version;
orxString_ToU32(zGlVersion + orxString_GetLength("OpenGL ES 2.0"), &u32Version, orxNULL);
if(u32Version > 0 && u32Version < 1849878)
{
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Bugged Andreno GPU driver found!, enabling workaround");
sstDisplay.iTextureUnitNumber = 1;
}
}
/* Pushes config section */
orxConfig_PushSection(orxDISPLAY_KZ_CONFIG_SECTION);
/* Stores texture unit and draw buffer numbers */
orxConfig_SetU32("TextureUnitNumber", (orxU32)sstDisplay.iTextureUnitNumber);
orxConfig_SetU32("DrawBufferNumber", (orxU32)sstDisplay.iDrawBufferNumber);
/* Pops config section */
orxConfig_PopSection();
static const orxSTRING szFragmentShaderSource =
"precision mediump float;"
"varying vec2 _gl_TexCoord0_;"
"varying vec4 _Color0_;"
"uniform sampler2D _Texture_;"
"void main()"
"{"
" gl_FragColor = _Color0_.rgba * texture2D(_Texture_, _gl_TexCoord0_).rgba;"
"}";
static const orxSTRING szNoTextureFragmentShaderSource =
"precision mediump float;"
"varying vec2 _gl_TexCoord0_;"
"varying vec4 _Color0_;"
"uniform sampler2D _Texture_;"
"void main()"
"{"
" gl_FragColor = _Color0_;"
"}";
/* Inits flags */
orxFLAG_SET(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_SHADER | orxDISPLAY_KU32_STATIC_FLAG_READY, orxDISPLAY_KU32_STATIC_FLAG_NONE);
/* Clears destination bitmap */
sstDisplay.apstDestinationBitmapList[0] = orxNULL;
sstDisplay.u32DestinationBitmapCount = 1;
/* Updates bound texture */
sstDisplay.apstBoundBitmapList[sstDisplay.s32ActiveTextureUnit] = orxNULL;
/* Creates default shaders */
sstDisplay.pstDefaultShader = (orxDISPLAY_SHADER*) orxDisplay_CreateShader(&szFragmentShaderSource, 1, orxNULL, orxFALSE);
sstDisplay.pstNoTextureShader = (orxDISPLAY_SHADER*) orxDisplay_CreateShader(&szNoTextureFragmentShaderSource, 1, orxNULL, orxTRUE);
/* Generates index buffer object (VBO/IBO) */
glGenBuffers(1, &(sstDisplay.uiVertexBuffer));
glASSERT();
glGenBuffers(1, &(sstDisplay.uiIndexBuffer));
glASSERT();
/* Binds them */
glBindBuffer(GL_ARRAY_BUFFER, sstDisplay.uiVertexBuffer);
glASSERT();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sstDisplay.uiIndexBuffer);
glASSERT();
/* Fills IBO */
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizei)(orxDISPLAY_KU32_INDEX_BUFFER_SIZE * sizeof(GLushort)), sstDisplay.au16IndexList, GL_STATIC_DRAW);
glASSERT();
/* Set up OpenGL state */
orxDisplay_Android_SetVideoMode(orxNULL);
/* Inits event payload */
orxMemory_Zero(&stPayload, sizeof(orxDISPLAY_EVENT_PAYLOAD));
stPayload.stVideoMode.u32Width = orxF2U(sstDisplay.pstScreen->fWidth);
stPayload.stVideoMode.u32Height = orxF2U(sstDisplay.pstScreen->fHeight);
stPayload.stVideoMode.u32Depth = sstDisplay.u32Depth;
stPayload.stVideoMode.bFullScreen = orxTRUE;
/* Sends it */
orxEVENT_SEND(orxEVENT_TYPE_DISPLAY, orxDISPLAY_EVENT_SET_VIDEO_MODE, orxNULL, orxNULL, &stPayload);
}
else
{
/* Deletes banks */
orxBank_Delete(sstDisplay.pstBitmapBank);
sstDisplay.pstBitmapBank = orxNULL;
orxBank_Delete(sstDisplay.pstShaderBank);
sstDisplay.pstShaderBank = orxNULL;
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
}
else
{
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
void orxFASTCALL orxDisplay_Android_Exit()
{
if(sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY)
{
/* Removes event handler */
orxEvent_RemoveHandler(orxEVENT_TYPE_RENDER, orxDisplay_Android_EventHandler);
orxEvent_RemoveHandler(orxANDROID_EVENT_TYPE_SURFACE, orxDisplay_Android_EventHandler);
/* Deletes default shaders */
orxDisplay_DeleteShader(sstDisplay.pstDefaultShader);
orxDisplay_DeleteShader(sstDisplay.pstNoTextureShader);
sstDisplay.u32Flags = orxDISPLAY_KU32_STATIC_FLAG_NONE;
glDeleteFramebuffers(1, &sstDisplay.uiFrameBuffer);
glASSERT();
/* Has index buffer? */
if(sstDisplay.uiIndexBuffer != 0)
{
/* Deletes it */
glDeleteBuffers(1, &(sstDisplay.uiIndexBuffer));
glASSERT();
sstDisplay.uiIndexBuffer = 0;
}
/* Deletes banks */
orxBank_Delete(sstDisplay.pstBitmapBank);
orxBank_Delete(sstDisplay.pstShaderBank);
if (sstDisplay.display != EGL_NO_DISPLAY)
{
eglMakeCurrent(sstDisplay.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglASSERT();
if (sstDisplay.context != EGL_NO_CONTEXT)
{
eglDestroyContext(sstDisplay.display, sstDisplay.context);
eglASSERT();
sstDisplay.context = EGL_NO_CONTEXT;
}
if (sstDisplay.surface != EGL_NO_SURFACE)
{
eglDestroySurface(sstDisplay.display, sstDisplay.surface);
eglASSERT();
sstDisplay.surface = EGL_NO_SURFACE;
}
eglTerminate(sstDisplay.display);
eglASSERT();
sstDisplay.display = EGL_NO_DISPLAY;
}
/* Cleans static controller */
orxMemory_Zero(&sstDisplay, sizeof(orxDISPLAY_STATIC));
}
/* Done! */
return;
}
orxBOOL orxFASTCALL orxDisplay_Android_HasShaderSupport()
{
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Done! */
return orxTRUE;
}
orxHANDLE orxFASTCALL orxDisplay_Android_CreateShader(const orxSTRING *_azCodeList, orxU32 _u32Size, const orxLINKLIST *_pstParamList, orxBOOL _bUseCustomParam)
{
orxHANDLE hResult = orxHANDLE_UNDEFINED;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
/* Has shader support? */
if(orxFLAG_TEST(sstDisplay.u32Flags, orxDISPLAY_KU32_STATIC_FLAG_SHADER))
{
/* Valid? */
if((_azCodeList != orxNULL) && (_u32Size > 0))
{
orxDISPLAY_SHADER *pstShader;
/* Creates a new shader */
pstShader = (orxDISPLAY_SHADER *)orxBank_Allocate(sstDisplay.pstShaderBank);
/* Successful? */
if(pstShader != orxNULL)
{
orxCHAR *pc, *pcReplace;
orxS32 s32Free, s32Offset;
orxU32 i;
/* Inits shader code buffer */
sstDisplay.acShaderCodeBuffer[0] = sstDisplay.acShaderCodeBuffer[orxDISPLAY_KU32_SHADER_BUFFER_SIZE - 1] = orxCHAR_NULL;
pc = sstDisplay.acShaderCodeBuffer;
s32Free = orxDISPLAY_KU32_SHADER_BUFFER_SIZE - 1;
/* Has parameters? */
if(_pstParamList != orxNULL)
{
orxSHADER_PARAM *pstParam;
/* Adds wrapping code */
s32Offset = orxString_NPrint(pc, s32Free, "precision mediump float;\nvarying vec2 _gl_TexCoord0_;\nvarying vec4 _Color0_;\n");
pc += s32Offset;
s32Free -= s32Offset;
/* For all parameters */
for(pstParam = (orxSHADER_PARAM *)orxLinkList_GetFirst(_pstParamList);
pstParam != orxNULL;
pstParam = (orxSHADER_PARAM *)orxLinkList_GetNext(&(pstParam->stNode)))
{
/* Depending on type */
switch(pstParam->eType)
{
case orxSHADER_PARAM_TYPE_FLOAT:
case orxSHADER_PARAM_TYPE_TIME:
{
/* Adds its literal value */
s32Offset = (pstParam->u32ArraySize >= 1) ? orxString_NPrint(pc, s32Free, "uniform float %s[%u];\n", pstParam->zName, pstParam->u32ArraySize) : orxString_NPrint(pc, s32Free, "uniform float %s;\n", pstParam->zName);
pc += s32Offset;
s32Free -= s32Offset;
break;
}
case orxSHADER_PARAM_TYPE_TEXTURE:
{
/* Adds its literal value and automated coordinates */
s32Offset = (pstParam->u32ArraySize >= 1) ? orxString_NPrint(pc, s32Free, "uniform sampler2D %s[%u];\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_TOP "[%u];\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_LEFT "[%u];\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_BOTTOM "[%u];\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_RIGHT "[%u];\n", pstParam->zName, pstParam->u32ArraySize, pstParam->zName, pstParam->u32ArraySize, pstParam->zName, pstParam->u32ArraySize, pstParam->zName, pstParam->u32ArraySize, pstParam->zName, pstParam->u32ArraySize) : orxString_NPrint(pc, s32Free, "uniform sampler2D %s;\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_TOP ";\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_LEFT ";\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_BOTTOM ";\nuniform float %s" orxDISPLAY_KZ_SHADER_SUFFIX_RIGHT ";\n", pstParam->zName, pstParam->zName, pstParam->zName, pstParam->zName, pstParam->zName);
pc += s32Offset;
s32Free -= s32Offset;
break;
}
case orxSHADER_PARAM_TYPE_VECTOR:
{
/* Adds its literal value */
s32Offset = (pstParam->u32ArraySize >= 1) ? orxString_NPrint(pc, s32Free, "uniform vec3 %s[%u];\n", pstParam->zName, pstParam->u32ArraySize) : orxString_NPrint(pc, s32Free, "uniform vec3 %s;\n", pstParam->zName);
pc += s32Offset;
s32Free -= s32Offset;
break;
}
default:
{
break;
}
}
}
}
/* Adds line directive */
s32Offset = orxString_NPrint(pc, s32Free, "#line 0\n");
pc += s32Offset;
s32Free -= s32Offset;
/* Adds all code fragments */
for(i = 0; i < _u32Size; i++)
{
s32Offset = orxString_NPrint(pc, s32Free, "%s\n", _azCodeList[i]);
pc += s32Offset;
s32Free -= s32Offset;
}
/* For all gl_TexCoord[0] */
for(pcReplace = (orxCHAR *)orxString_SearchString(sstDisplay.acShaderCodeBuffer, "gl_TexCoord[0]");
pcReplace != orxNULL;
pcReplace = (orxCHAR *)orxString_SearchString(pcReplace + 14 * sizeof(orxCHAR), "gl_TexCoord[0]"))
{
/* Replaces it */
orxMemory_Copy(pcReplace, "_gl_TexCoord0_", 14 * sizeof(orxCHAR));
}
/* For all gl_Color */
for(pcReplace = (orxCHAR *)orxString_SearchString(sstDisplay.acShaderCodeBuffer, "gl_Color");
pcReplace != orxNULL;
pcReplace = (orxCHAR *)orxString_SearchString(pcReplace + 8 * sizeof(orxCHAR), "gl_Color"))
{
/* Replaces it */
orxMemory_Copy(pcReplace, "_Color0_", 8 * sizeof(orxCHAR));
}
/* Inits shader */
orxMemory_Zero(&(pstShader->stNode), sizeof(orxLINKLIST_NODE));
pstShader->uiProgram = (GLuint)orxU32_UNDEFINED;
pstShader->iTextureCount = 0;
pstShader->s32ParamCount = 0;
pstShader->bPending = orxFALSE;
pstShader->bUseCustomParam = _bUseCustomParam;
pstShader->zCode = orxString_Duplicate(sstDisplay.acShaderCodeBuffer);
pstShader->astTextureInfoList = (orxDISPLAY_TEXTURE_INFO *)orxMemory_Allocate(sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_TEXTURE_INFO), orxMEMORY_TYPE_MAIN);
pstShader->astParamInfoList = (orxDISPLAY_PARAM_INFO *)orxMemory_Allocate(sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_PARAM_INFO), orxMEMORY_TYPE_MAIN);
orxMemory_Zero(pstShader->astTextureInfoList, sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_TEXTURE_INFO));
orxMemory_Zero(pstShader->astParamInfoList, sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_PARAM_INFO));
/* Compiles it */
if(orxDisplay_Android_CompileShader(pstShader) != orxSTATUS_FAILURE)
{
/* Updates result */
hResult = (orxHANDLE)pstShader;
}
else
{
/* Deletes code */
orxString_Delete(pstShader->zCode);
/* Deletes texture info list */
orxMemory_Free(pstShader->astTextureInfoList);
/* Deletes param info list */
orxMemory_Free(pstShader->astParamInfoList);
/* Frees shader */
orxBank_Free(sstDisplay.pstShaderBank, pstShader);
}
}
}
}
/* Done! */
return hResult;
}
void orxFASTCALL orxDisplay_Android_DeleteShader(orxHANDLE _hShader)
{
orxDISPLAY_SHADER *pstShader;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_hShader != orxHANDLE_UNDEFINED) && (_hShader != orxNULL));
/* Gets shader */
pstShader = (orxDISPLAY_SHADER *)_hShader;
/* Deletes its program */
glDeleteProgram(pstShader->uiProgram);
glASSERT();
/* Deletes its code */
orxString_Delete(pstShader->zCode);
/* Deletes its texture info list */
orxMemory_Free(pstShader->astTextureInfoList);
/* Deletes its param info list */
orxMemory_Free(pstShader->astParamInfoList);
/* Frees it */
orxBank_Free(sstDisplay.pstShaderBank, pstShader);
return;
}
orxSTATUS orxFASTCALL orxDisplay_Android_StartShader(orxHANDLE _hShader)
{
orxDISPLAY_SHADER *pstShader;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_hShader != orxHANDLE_UNDEFINED) && (_hShader != orxNULL));
/* Gets shader */
pstShader = (orxDISPLAY_SHADER *)_hShader;
/* Not pending or use custom param? */
if((pstShader->bPending == orxFALSE) || (pstShader->bUseCustomParam != orxFALSE))
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Adds it to the active list */
orxLinkList_AddEnd(&(sstDisplay.stActiveShaderList), &(pstShader->stNode));
}
else
{
/* Resets its pending status */
pstShader->bPending = orxFALSE;
/* Updates count */
sstDisplay.s32PendingShaderCount--;
}
/* Uses its program */
glUseProgram(pstShader->uiProgram);
glASSERT();
/* Updates projection matrix */
glUNIFORM(Matrix4fv, pstShader->iProjectionMatrixLocation, 1, GL_FALSE, (GLfloat *)&(sstDisplay.mProjectionMatrix.aafValueList[0][0]));
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_StopShader(orxHANDLE _hShader)
{
orxDISPLAY_SHADER *pstShader;
orxBOOL bResetShader = orxTRUE;
orxSTATUS eResult = orxSTATUS_SUCCESS;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT(_hShader != orxHANDLE_UNDEFINED);
/* Gets shader */
pstShader = (orxDISPLAY_SHADER *)_hShader;
/* Has shader? */
if(pstShader != orxNULL)
{
/* Not already removed? */
if((orxLinkList_GetList(&(pstShader->stNode)) != orxNULL)
&& (pstShader->bPending == orxFALSE))
{
/* Empty buffer? */
if(sstDisplay.s32BufferIndex == 0)
{
orxDISPLAY_SHADER *pstActive, *pstNextActive;
/* For all active shaders */
for(pstActive = (orxDISPLAY_SHADER *)orxLinkList_GetFirst(&(sstDisplay.stActiveShaderList));
pstActive != orxNULL;
pstActive = pstNextActive)
{
/* Gets next shader */
pstNextActive = (orxDISPLAY_SHADER *)orxLinkList_GetNext(&(pstActive->stNode));
/* Was pending removal? */
if(pstActive->bPending != orxFALSE)
{
/* Clears its texture count */
pstActive->iTextureCount = 0;
/* Clears its texture info list */
orxMemory_Zero(pstActive->astTextureInfoList, sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_TEXTURE_INFO));
/* Removes its pending status */
pstActive->bPending = orxFALSE;
/* Removes it from active list */
orxLinkList_Remove(&(pstActive->stNode));
/* Updates count */
sstDisplay.s32PendingShaderCount--;
}
}
/* Clears texture count */
pstShader->iTextureCount = 0;
/* Clears its texture info list */
orxMemory_Zero(pstShader->astTextureInfoList, sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_TEXTURE_INFO));
/* Removes it from active list */
orxLinkList_Remove(&(pstShader->stNode));
}
/* Using custom param? */
else if(pstShader->bUseCustomParam != orxFALSE)
{
/* Has something to display? */
if(sstDisplay.s32BufferIndex > 0)
{
/* Draws arrays */
orxDisplay_Android_DrawArrays();
/* Don't reset shader */
bResetShader = orxFALSE;
}
/* Clears texture count */
pstShader->iTextureCount = 0;
/* Clears texture info list */
orxMemory_Zero(pstShader->astTextureInfoList, sstDisplay.iTextureUnitNumber * sizeof(orxDISPLAY_TEXTURE_INFO));
/* Removes it from active list */
orxLinkList_Remove(&(pstShader->stNode));
}
else
{
/* Marks it as pending */
pstShader->bPending = orxTRUE;
/* Updates count */
sstDisplay.s32PendingShaderCount++;
}
/* Updates projection matrix */
glUNIFORM(Matrix4fv, sstDisplay.pstDefaultShader->iProjectionMatrixLocation, 1, GL_FALSE, (GLfloat *)&(sstDisplay.mProjectionMatrix.aafValueList[0][0]));
}
else
{
/* Don't reset shader */
bResetShader = orxFALSE;
}
}
/* Should reset shader? */
if(bResetShader != orxFALSE)
{
/* Uses default program */
glUseProgram(sstDisplay.pstDefaultShader->uiProgram);
glASSERT();
/* Updates its texture unit */
glUNIFORM(1i, sstDisplay.pstDefaultShader->iTextureLocation, sstDisplay.s32ActiveTextureUnit);
/* Updates projection matrix */
glUNIFORM(Matrix4fv, sstDisplay.pstDefaultShader->iProjectionMatrixLocation, 1, GL_FALSE, (GLfloat *)&(sstDisplay.mProjectionMatrix.aafValueList[0][0]));
}
/* Done! */
return eResult;
}
orxS32 orxFASTCALL orxDisplay_Android_GetParameterID(const orxHANDLE _hShader, const orxSTRING _zParam, orxS32 _s32Index, orxBOOL _bIsTexture)
{
orxDISPLAY_SHADER *pstShader;
orxS32 s32Result;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_hShader != orxHANDLE_UNDEFINED) && (_hShader != orxNULL));
orxASSERT(_zParam != orxNULL);
/* Gets shader */
pstShader = (orxDISPLAY_SHADER *)_hShader;
/* Is a texture? */
if(_bIsTexture != orxFALSE)
{
orxDISPLAY_PARAM_INFO *pstInfo;
orxCHAR acBuffer[256];
/* Checks */
orxASSERT(pstShader->s32ParamCount < sstDisplay.iTextureUnitNumber);
/* Inits buffer */
acBuffer[sizeof(acBuffer) - 1] = orxCHAR_NULL;
/* Gets corresponding param info */
pstInfo = &pstShader->astParamInfoList[pstShader->s32ParamCount];
/* Updates result */
s32Result = pstShader->s32ParamCount++;
/* Array? */
if(_s32Index >= 0)
{
/* Prints its name */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s[%d]", _zParam, _s32Index);
/* Gets parameter location */
pstInfo->iLocation = glGetUniformLocation(pstShader->uiProgram, acBuffer);
glASSERT();
/* Gets top parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_TOP "[%d]", _zParam, _s32Index);
pstInfo->iLocationTop = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
/* Gets left parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_LEFT "[%d]", _zParam, _s32Index);
pstInfo->iLocationLeft = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
/* Gets bottom parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_BOTTOM "[%d]", _zParam, _s32Index);
pstInfo->iLocationBottom = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
/* Gets right parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_RIGHT "[%d]", _zParam, _s32Index);
pstInfo->iLocationRight = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
}
else
{
/* Gets parameter location */
pstInfo->iLocation = glGetUniformLocation(pstShader->uiProgram, (const char *)_zParam);
glASSERT();
/* Gets top parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_TOP, _zParam);
pstInfo->iLocationTop = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
/* Gets left parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_LEFT, _zParam);
pstInfo->iLocationLeft = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
/* Gets bottom parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_BOTTOM, _zParam);
pstInfo->iLocationBottom = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
/* Gets right parameter location */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s" orxDISPLAY_KZ_SHADER_SUFFIX_RIGHT, _zParam);
pstInfo->iLocationRight = glGetUniformLocation(pstShader->uiProgram, (const char *)acBuffer);
glASSERT();
}
}
else
{
/* Array? */
if(_s32Index >= 0)
{
orxCHAR acBuffer[256];
/* Prints its name */
orxString_NPrint(acBuffer, sizeof(acBuffer) - 1, "%s[%d]", _zParam, _s32Index);
acBuffer[sizeof(acBuffer) - 1] = orxCHAR_NULL;
/* Gets parameter location */
s32Result = (orxS32)glGetUniformLocation(pstShader->uiProgram, acBuffer);
glASSERT();
}
else
{
/* Gets parameter location */
s32Result = (orxS32)glGetUniformLocation(pstShader->uiProgram, (const char *)_zParam);
glASSERT();
}
}
/* Done! */
return s32Result;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetShaderBitmap(orxHANDLE _hShader, orxS32 _s32ID, const orxBITMAP *_pstValue)
{
orxDISPLAY_SHADER *pstShader;
orxSTATUS eResult = orxSTATUS_FAILURE;
orxS32 i;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_hShader != orxHANDLE_UNDEFINED) && (_hShader != orxNULL));
orxASSERT((_pstValue != sstDisplay.pstScreen) && "Can't use screen bitmap as texture parameter (ID <%d>) for fragment shader.", _s32ID);
/* Gets shader */
pstShader = (orxDISPLAY_SHADER *)_hShader;
/* For all already used texture units */
for(i = 0; i < pstShader->iTextureCount; i++)
{
/* Same location? */
if(pstShader->astTextureInfoList[i].iLocation == pstShader->astParamInfoList[_s32ID].iLocation)
{
/* Different texture? */
if(pstShader->astTextureInfoList[i].pstBitmap != _pstValue)
{
/* Draws remaining items */
orxDisplay_Android_DrawArrays();
/* Updates texture info */
pstShader->astTextureInfoList[i].pstBitmap = _pstValue;
/* Updates corner values */
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationTop, (GLfloat)((_pstValue->fRecRealHeight * _pstValue->stClip.vTL.fY)));
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationLeft, (GLfloat)(_pstValue->fRecRealWidth * _pstValue->stClip.vTL.fX));
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationBottom, (GLfloat)((_pstValue->fRecRealHeight * _pstValue->stClip.vBR.fY)));
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationRight, (GLfloat)(_pstValue->fRecRealWidth * _pstValue->stClip.vBR.fX));
}
/* Updates result */
eResult = orxSTATUS_SUCCESS;
break;
}
}
/* Not already done? */
if(eResult == orxSTATUS_FAILURE)
{
/* Has free texture unit left? */
if(pstShader->iTextureCount < sstDisplay.iTextureUnitNumber)
{
/* Valid? */
if(_s32ID >= 0)
{
/* No bitmap? */
if(_pstValue == orxNULL)
{
/* Uses screen bitmap */
_pstValue = sstDisplay.pstScreen;
}
/* Updates texture info */
pstShader->astTextureInfoList[pstShader->iTextureCount].iLocation = pstShader->astParamInfoList[_s32ID].iLocation;
pstShader->astTextureInfoList[pstShader->iTextureCount].pstBitmap = _pstValue;
/* Updates corner values */
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationTop, (GLfloat)((_pstValue->fRecRealHeight * _pstValue->stClip.vTL.fY)));
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationLeft, (GLfloat)(_pstValue->fRecRealWidth * _pstValue->stClip.vTL.fX));
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationBottom, (GLfloat)((_pstValue->fRecRealHeight * _pstValue->stClip.vBR.fY)));
glUNIFORM(1f, pstShader->astParamInfoList[_s32ID].iLocationRight, (GLfloat)(_pstValue->fRecRealWidth * _pstValue->stClip.vBR.fX));
/* Updates texture count */
pstShader->iTextureCount++;
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Outputs log */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't bind texture parameter (ID <%d>) for fragment shader: invalid ID.", _s32ID);
}
}
else
{
/* Outputs log */
orxDEBUG_PRINT(orxDEBUG_LEVEL_DISPLAY, "Can't bind texture parameter (ID <%d>) for fragment shader: all the texture units are used.", _s32ID);
}
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetShaderFloat(orxHANDLE _hShader, orxS32 _s32ID, orxFLOAT _fValue)
{
orxSTATUS eResult;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_hShader != orxHANDLE_UNDEFINED) && (_hShader != orxNULL));
/* Valid? */
if(_s32ID >= 0)
{
/* Updates its value (no glASSERT() as this can be set more than once per use and would trigger it) */
glUNIFORM_NO_ASSERT(1f, (GLint)_s32ID, (GLfloat)_fValue);
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
orxSTATUS orxFASTCALL orxDisplay_Android_SetShaderVector(orxHANDLE _hShader, orxS32 _s32ID, const orxVECTOR *_pvValue)
{
orxSTATUS eResult;
/* Checks */
orxASSERT((sstDisplay.u32Flags & orxDISPLAY_KU32_STATIC_FLAG_READY) == orxDISPLAY_KU32_STATIC_FLAG_READY);
orxASSERT((_hShader != orxHANDLE_UNDEFINED) && (_hShader != orxNULL));
orxASSERT(_pvValue != orxNULL);
/* Valid? */
if(_s32ID >= 0)
{
/* Updates its value (no glASSERT() as this can be set more than once per use and would trigger it) */
glUNIFORM_NO_ASSERT(3f, (GLint)_s32ID, (GLfloat)_pvValue->fX, (GLfloat)_pvValue->fY, (GLfloat)_pvValue->fZ);
/* Updates result */
eResult = orxSTATUS_SUCCESS;
}
else
{
/* Updates result */
eResult = orxSTATUS_FAILURE;
}
/* Done! */
return eResult;
}
/***************************************************************************
* Plugin Related *
***************************************************************************/
orxPLUGIN_USER_CORE_FUNCTION_START(DISPLAY);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_Init, DISPLAY, INIT);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_Exit, DISPLAY, EXIT);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_Swap, DISPLAY, SWAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_CreateBitmap, DISPLAY, CREATE_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DeleteBitmap, DISPLAY, DELETE_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SaveBitmap, DISPLAY, SAVE_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetTempBitmap, DISPLAY, SET_TEMP_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetTempBitmap, DISPLAY, GET_TEMP_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetDestinationBitmaps, DISPLAY, SET_DESTINATION_BITMAPS);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_TransformBitmap, DISPLAY, TRANSFORM_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_TransformText, DISPLAY, TRANSFORM_TEXT);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_LoadBitmap, DISPLAY, LOAD_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetBitmapSize, DISPLAY, GET_BITMAP_SIZE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetScreenSize, DISPLAY, GET_SCREEN_SIZE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetScreenBitmap, DISPLAY, GET_SCREEN_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_ClearBitmap, DISPLAY, CLEAR_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetBlendMode, DISPLAY, SET_BLEND_MODE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetBitmapClipping, DISPLAY, SET_BITMAP_CLIPPING);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetBitmapID, DISPLAY, GET_BITMAP_ID);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetBitmapData, DISPLAY, SET_BITMAP_DATA);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetBitmapData, DISPLAY, GET_BITMAP_DATA);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DrawLine, DISPLAY, DRAW_LINE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DrawPolyline, DISPLAY, DRAW_POLYLINE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DrawPolygon, DISPLAY, DRAW_POLYGON);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DrawCircle, DISPLAY, DRAW_CIRCLE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DrawOBox, DISPLAY, DRAW_OBOX);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DrawMesh, DISPLAY, DRAW_MESH);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_HasShaderSupport, DISPLAY, HAS_SHADER_SUPPORT);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_CreateShader, DISPLAY, CREATE_SHADER);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_DeleteShader, DISPLAY, DELETE_SHADER);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_StartShader, DISPLAY, START_SHADER);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_StopShader, DISPLAY, STOP_SHADER);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetParameterID, DISPLAY, GET_PARAMETER_ID);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetShaderBitmap, DISPLAY, SET_SHADER_BITMAP);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetShaderFloat, DISPLAY, SET_SHADER_FLOAT);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetShaderVector, DISPLAY, SET_SHADER_VECTOR);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_EnableVSync, DISPLAY, ENABLE_VSYNC);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_IsVSyncEnabled, DISPLAY, IS_VSYNC_ENABLED);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetFullScreen, DISPLAY, SET_FULL_SCREEN);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_IsFullScreen, DISPLAY, IS_FULL_SCREEN);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetVideoModeCount, DISPLAY, GET_VIDEO_MODE_COUNT);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_GetVideoMode, DISPLAY, GET_VIDEO_MODE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_SetVideoMode, DISPLAY, SET_VIDEO_MODE);
orxPLUGIN_USER_CORE_FUNCTION_ADD(orxDisplay_Android_IsVideoModeAvailable, DISPLAY, IS_VIDEO_MODE_AVAILABLE);
orxPLUGIN_USER_CORE_FUNCTION_END();
| 35.014653 | 931 | 0.657132 | [
"mesh",
"render",
"object"
] |
d0ef50bf930ad747abe7b4510521f8ad79923ba5 | 59,750 | c | C | drivers/gpu/drm/i915/intel_ringbuffer.c | YFShiftFinance/Unix | b82f0634af26793369af6df5fa9d374d0e09a54c | [
"MIT"
] | 1 | 2020-09-20T03:48:15.000Z | 2020-09-20T03:48:15.000Z | drivers/gpu/drm/i915/intel_ringbuffer.c | YFShiftFinance/Unix | b82f0634af26793369af6df5fa9d374d0e09a54c | [
"MIT"
] | null | null | null | drivers/gpu/drm/i915/intel_ringbuffer.c | YFShiftFinance/Unix | b82f0634af26793369af6df5fa9d374d0e09a54c | [
"MIT"
] | null | null | null | /*
* Copyright © 2008-2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eric Anholt <eric@anholt.net>
* Zou Nan hai <nanhai.zou@intel.com>
* Xiang Hai hao<haihao.xiang@intel.com>
*
*/
#include <linux/log2.h>
#include <drm/drmP.h>
#include <drm/i915_drm.h>
#include "i915_drv.h"
#include "i915_gem_render_state.h"
#include "i915_trace.h"
#include "intel_drv.h"
#include "intel_workarounds.h"
/* Rough estimate of the typical request size, performing a flush,
* set-context and then emitting the batch.
*/
#define LEGACY_REQUEST_SIZE 200
static unsigned int __intel_ring_space(unsigned int head,
unsigned int tail,
unsigned int size)
{
/*
* "If the Ring Buffer Head Pointer and the Tail Pointer are on the
* same cacheline, the Head Pointer must not be greater than the Tail
* Pointer."
*/
GEM_BUG_ON(!is_power_of_2(size));
return (head - tail - CACHELINE_BYTES) & (size - 1);
}
unsigned int intel_ring_update_space(struct intel_ring *ring)
{
unsigned int space;
space = __intel_ring_space(ring->head, ring->emit, ring->size);
ring->space = space;
return space;
}
static int
gen2_render_ring_flush(struct i915_request *rq, u32 mode)
{
u32 cmd, *cs;
cmd = MI_FLUSH;
if (mode & EMIT_INVALIDATE)
cmd |= MI_READ_FLUSH;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = cmd;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static int
gen4_render_ring_flush(struct i915_request *rq, u32 mode)
{
u32 cmd, *cs;
/*
* read/write caches:
*
* I915_GEM_DOMAIN_RENDER is always invalidated, but is
* only flushed if MI_NO_WRITE_FLUSH is unset. On 965, it is
* also flushed at 2d versus 3d pipeline switches.
*
* read-only caches:
*
* I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
* MI_READ_FLUSH is set, and is always flushed on 965.
*
* I915_GEM_DOMAIN_COMMAND may not exist?
*
* I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
* invalidated when MI_EXE_FLUSH is set.
*
* I915_GEM_DOMAIN_VERTEX, which exists on 965, is
* invalidated with every MI_FLUSH.
*
* TLBs:
*
* On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
* and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
* I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
* are flushed at any MI_FLUSH.
*/
cmd = MI_FLUSH;
if (mode & EMIT_INVALIDATE) {
cmd |= MI_EXE_FLUSH;
if (IS_G4X(rq->i915) || IS_GEN5(rq->i915))
cmd |= MI_INVALIDATE_ISP;
}
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = cmd;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
/*
* Emits a PIPE_CONTROL with a non-zero post-sync operation, for
* implementing two workarounds on gen6. From section 1.4.7.1
* "PIPE_CONTROL" of the Sandy Bridge PRM volume 2 part 1:
*
* [DevSNB-C+{W/A}] Before any depth stall flush (including those
* produced by non-pipelined state commands), software needs to first
* send a PIPE_CONTROL with no bits set except Post-Sync Operation !=
* 0.
*
* [Dev-SNB{W/A}]: Before a PIPE_CONTROL with Write Cache Flush Enable
* =1, a PIPE_CONTROL with any non-zero post-sync-op is required.
*
* And the workaround for these two requires this workaround first:
*
* [Dev-SNB{W/A}]: Pipe-control with CS-stall bit set must be sent
* BEFORE the pipe-control with a post-sync op and no write-cache
* flushes.
*
* And this last workaround is tricky because of the requirements on
* that bit. From section 1.4.7.2.3 "Stall" of the Sandy Bridge PRM
* volume 2 part 1:
*
* "1 of the following must also be set:
* - Render Target Cache Flush Enable ([12] of DW1)
* - Depth Cache Flush Enable ([0] of DW1)
* - Stall at Pixel Scoreboard ([1] of DW1)
* - Depth Stall ([13] of DW1)
* - Post-Sync Operation ([13] of DW1)
* - Notify Enable ([8] of DW1)"
*
* The cache flushes require the workaround flush that triggered this
* one, so we can't use it. Depth stall would trigger the same.
* Post-sync nonzero is what triggered this second workaround, so we
* can't use that one either. Notify enable is IRQs, which aren't
* really our business. That leaves only stall at scoreboard.
*/
static int
intel_emit_post_sync_nonzero_flush(struct i915_request *rq)
{
u32 scratch_addr =
i915_ggtt_offset(rq->engine->scratch) + 2 * CACHELINE_BYTES;
u32 *cs;
cs = intel_ring_begin(rq, 6);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = GFX_OP_PIPE_CONTROL(5);
*cs++ = PIPE_CONTROL_CS_STALL | PIPE_CONTROL_STALL_AT_SCOREBOARD;
*cs++ = scratch_addr | PIPE_CONTROL_GLOBAL_GTT;
*cs++ = 0; /* low dword */
*cs++ = 0; /* high dword */
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
cs = intel_ring_begin(rq, 6);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = GFX_OP_PIPE_CONTROL(5);
*cs++ = PIPE_CONTROL_QW_WRITE;
*cs++ = scratch_addr | PIPE_CONTROL_GLOBAL_GTT;
*cs++ = 0;
*cs++ = 0;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static int
gen6_render_ring_flush(struct i915_request *rq, u32 mode)
{
u32 scratch_addr =
i915_ggtt_offset(rq->engine->scratch) + 2 * CACHELINE_BYTES;
u32 *cs, flags = 0;
int ret;
/* Force SNB workarounds for PIPE_CONTROL flushes */
ret = intel_emit_post_sync_nonzero_flush(rq);
if (ret)
return ret;
/* Just flush everything. Experiments have shown that reducing the
* number of bits based on the write domains has little performance
* impact.
*/
if (mode & EMIT_FLUSH) {
flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
/*
* Ensure that any following seqno writes only happen
* when the render cache is indeed flushed.
*/
flags |= PIPE_CONTROL_CS_STALL;
}
if (mode & EMIT_INVALIDATE) {
flags |= PIPE_CONTROL_TLB_INVALIDATE;
flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
/*
* TLB invalidate requires a post-sync write.
*/
flags |= PIPE_CONTROL_QW_WRITE | PIPE_CONTROL_CS_STALL;
}
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = GFX_OP_PIPE_CONTROL(4);
*cs++ = flags;
*cs++ = scratch_addr | PIPE_CONTROL_GLOBAL_GTT;
*cs++ = 0;
intel_ring_advance(rq, cs);
return 0;
}
static int
gen7_render_ring_cs_stall_wa(struct i915_request *rq)
{
u32 *cs;
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = GFX_OP_PIPE_CONTROL(4);
*cs++ = PIPE_CONTROL_CS_STALL | PIPE_CONTROL_STALL_AT_SCOREBOARD;
*cs++ = 0;
*cs++ = 0;
intel_ring_advance(rq, cs);
return 0;
}
static int
gen7_render_ring_flush(struct i915_request *rq, u32 mode)
{
u32 scratch_addr =
i915_ggtt_offset(rq->engine->scratch) + 2 * CACHELINE_BYTES;
u32 *cs, flags = 0;
/*
* Ensure that any following seqno writes only happen when the render
* cache is indeed flushed.
*
* Workaround: 4th PIPE_CONTROL command (except the ones with only
* read-cache invalidate bits set) must have the CS_STALL bit set. We
* don't try to be clever and just set it unconditionally.
*/
flags |= PIPE_CONTROL_CS_STALL;
/* Just flush everything. Experiments have shown that reducing the
* number of bits based on the write domains has little performance
* impact.
*/
if (mode & EMIT_FLUSH) {
flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
flags |= PIPE_CONTROL_FLUSH_ENABLE;
}
if (mode & EMIT_INVALIDATE) {
flags |= PIPE_CONTROL_TLB_INVALIDATE;
flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_MEDIA_STATE_CLEAR;
/*
* TLB invalidate requires a post-sync write.
*/
flags |= PIPE_CONTROL_QW_WRITE;
flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
/* Workaround: we must issue a pipe_control with CS-stall bit
* set before a pipe_control command that has the state cache
* invalidate bit set. */
gen7_render_ring_cs_stall_wa(rq);
}
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = GFX_OP_PIPE_CONTROL(4);
*cs++ = flags;
*cs++ = scratch_addr;
*cs++ = 0;
intel_ring_advance(rq, cs);
return 0;
}
static void ring_setup_phys_status_page(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
struct page *page = virt_to_page(engine->status_page.page_addr);
phys_addr_t phys = PFN_PHYS(page_to_pfn(page));
u32 addr;
addr = lower_32_bits(phys);
if (INTEL_GEN(dev_priv) >= 4)
addr |= (phys >> 28) & 0xf0;
I915_WRITE(HWS_PGA, addr);
}
static void intel_ring_setup_status_page(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
i915_reg_t mmio;
/* The ring status page addresses are no longer next to the rest of
* the ring registers as of gen7.
*/
if (IS_GEN7(dev_priv)) {
switch (engine->id) {
/*
* No more rings exist on Gen7. Default case is only to shut up
* gcc switch check warning.
*/
default:
GEM_BUG_ON(engine->id);
case RCS:
mmio = RENDER_HWS_PGA_GEN7;
break;
case BCS:
mmio = BLT_HWS_PGA_GEN7;
break;
case VCS:
mmio = BSD_HWS_PGA_GEN7;
break;
case VECS:
mmio = VEBOX_HWS_PGA_GEN7;
break;
}
} else if (IS_GEN6(dev_priv)) {
mmio = RING_HWS_PGA_GEN6(engine->mmio_base);
} else {
mmio = RING_HWS_PGA(engine->mmio_base);
}
if (INTEL_GEN(dev_priv) >= 6) {
u32 mask = ~0u;
/*
* Keep the render interrupt unmasked as this papers over
* lost interrupts following a reset.
*/
if (engine->id == RCS)
mask &= ~BIT(0);
I915_WRITE(RING_HWSTAM(engine->mmio_base), mask);
}
I915_WRITE(mmio, engine->status_page.ggtt_offset);
POSTING_READ(mmio);
/* Flush the TLB for this page */
if (IS_GEN(dev_priv, 6, 7)) {
i915_reg_t reg = RING_INSTPM(engine->mmio_base);
/* ring should be idle before issuing a sync flush*/
WARN_ON((I915_READ_MODE(engine) & MODE_IDLE) == 0);
I915_WRITE(reg,
_MASKED_BIT_ENABLE(INSTPM_TLB_INVALIDATE |
INSTPM_SYNC_FLUSH));
if (intel_wait_for_register(dev_priv,
reg, INSTPM_SYNC_FLUSH, 0,
1000))
DRM_ERROR("%s: wait for SyncFlush to complete for TLB invalidation timed out\n",
engine->name);
}
}
static bool stop_ring(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
if (INTEL_GEN(dev_priv) > 2) {
I915_WRITE_MODE(engine, _MASKED_BIT_ENABLE(STOP_RING));
if (intel_wait_for_register(dev_priv,
RING_MI_MODE(engine->mmio_base),
MODE_IDLE,
MODE_IDLE,
1000)) {
DRM_ERROR("%s : timed out trying to stop ring\n",
engine->name);
/* Sometimes we observe that the idle flag is not
* set even though the ring is empty. So double
* check before giving up.
*/
if (I915_READ_HEAD(engine) != I915_READ_TAIL(engine))
return false;
}
}
I915_WRITE_HEAD(engine, I915_READ_TAIL(engine));
I915_WRITE_HEAD(engine, 0);
I915_WRITE_TAIL(engine, 0);
/* The ring must be empty before it is disabled */
I915_WRITE_CTL(engine, 0);
return (I915_READ_HEAD(engine) & HEAD_ADDR) == 0;
}
static int init_ring_common(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
struct intel_ring *ring = engine->buffer;
int ret = 0;
intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
if (!stop_ring(engine)) {
/* G45 ring initialization often fails to reset head to zero */
DRM_DEBUG_DRIVER("%s head not reset to zero "
"ctl %08x head %08x tail %08x start %08x\n",
engine->name,
I915_READ_CTL(engine),
I915_READ_HEAD(engine),
I915_READ_TAIL(engine),
I915_READ_START(engine));
if (!stop_ring(engine)) {
DRM_ERROR("failed to set %s head to zero "
"ctl %08x head %08x tail %08x start %08x\n",
engine->name,
I915_READ_CTL(engine),
I915_READ_HEAD(engine),
I915_READ_TAIL(engine),
I915_READ_START(engine));
ret = -EIO;
goto out;
}
}
if (HWS_NEEDS_PHYSICAL(dev_priv))
ring_setup_phys_status_page(engine);
else
intel_ring_setup_status_page(engine);
intel_engine_reset_breadcrumbs(engine);
/* Enforce ordering by reading HEAD register back */
I915_READ_HEAD(engine);
/* Initialize the ring. This must happen _after_ we've cleared the ring
* registers with the above sequence (the readback of the HEAD registers
* also enforces ordering), otherwise the hw might lose the new ring
* register values. */
I915_WRITE_START(engine, i915_ggtt_offset(ring->vma));
/* WaClearRingBufHeadRegAtInit:ctg,elk */
if (I915_READ_HEAD(engine))
DRM_DEBUG_DRIVER("%s initialization failed [head=%08x], fudging\n",
engine->name, I915_READ_HEAD(engine));
/* Check that the ring offsets point within the ring! */
GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->head));
GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->tail));
intel_ring_update_space(ring);
I915_WRITE_HEAD(engine, ring->head);
I915_WRITE_TAIL(engine, ring->tail);
(void)I915_READ_TAIL(engine);
I915_WRITE_CTL(engine, RING_CTL_SIZE(ring->size) | RING_VALID);
/* If the head is still not zero, the ring is dead */
if (intel_wait_for_register(dev_priv, RING_CTL(engine->mmio_base),
RING_VALID, RING_VALID,
50)) {
DRM_ERROR("%s initialization failed "
"ctl %08x (valid? %d) head %08x [%08x] tail %08x [%08x] start %08x [expected %08x]\n",
engine->name,
I915_READ_CTL(engine),
I915_READ_CTL(engine) & RING_VALID,
I915_READ_HEAD(engine), ring->head,
I915_READ_TAIL(engine), ring->tail,
I915_READ_START(engine),
i915_ggtt_offset(ring->vma));
ret = -EIO;
goto out;
}
if (INTEL_GEN(dev_priv) > 2)
I915_WRITE_MODE(engine, _MASKED_BIT_DISABLE(STOP_RING));
/* Papering over lost _interrupts_ immediately following the restart */
intel_engine_wakeup(engine);
out:
intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
return ret;
}
static struct i915_request *reset_prepare(struct intel_engine_cs *engine)
{
intel_engine_stop_cs(engine);
if (engine->irq_seqno_barrier)
engine->irq_seqno_barrier(engine);
return i915_gem_find_active_request(engine);
}
static void skip_request(struct i915_request *rq)
{
void *vaddr = rq->ring->vaddr;
u32 head;
head = rq->infix;
if (rq->postfix < head) {
memset32(vaddr + head, MI_NOOP,
(rq->ring->size - head) / sizeof(u32));
head = 0;
}
memset32(vaddr + head, MI_NOOP, (rq->postfix - head) / sizeof(u32));
}
static void reset_ring(struct intel_engine_cs *engine, struct i915_request *rq)
{
GEM_TRACE("%s seqno=%x\n", engine->name, rq ? rq->global_seqno : 0);
/*
* Try to restore the logical GPU state to match the continuation
* of the request queue. If we skip the context/PD restore, then
* the next request may try to execute assuming that its context
* is valid and loaded on the GPU and so may try to access invalid
* memory, prompting repeated GPU hangs.
*
* If the request was guilty, we still restore the logical state
* in case the next request requires it (e.g. the aliasing ppgtt),
* but skip over the hung batch.
*
* If the request was innocent, we try to replay the request with
* the restored context.
*/
if (rq) {
/* If the rq hung, jump to its breadcrumb and skip the batch */
rq->ring->head = intel_ring_wrap(rq->ring, rq->head);
if (rq->fence.error == -EIO)
skip_request(rq);
}
}
static void reset_finish(struct intel_engine_cs *engine)
{
}
static int intel_rcs_ctx_init(struct i915_request *rq)
{
int ret;
ret = intel_ctx_workarounds_emit(rq);
if (ret != 0)
return ret;
ret = i915_gem_render_state_emit(rq);
if (ret)
return ret;
return 0;
}
static int init_render_ring(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
int ret = init_ring_common(engine);
if (ret)
return ret;
intel_whitelist_workarounds_apply(engine);
/* WaTimedSingleVertexDispatch:cl,bw,ctg,elk,ilk,snb */
if (IS_GEN(dev_priv, 4, 6))
I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(VS_TIMER_DISPATCH));
/* We need to disable the AsyncFlip performance optimisations in order
* to use MI_WAIT_FOR_EVENT within the CS. It should already be
* programmed to '1' on all products.
*
* WaDisableAsyncFlipPerfMode:snb,ivb,hsw,vlv
*/
if (IS_GEN(dev_priv, 6, 7))
I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
/* Required for the hardware to program scanline values for waiting */
/* WaEnableFlushTlbInvalidationMode:snb */
if (IS_GEN6(dev_priv))
I915_WRITE(GFX_MODE,
_MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_EXPLICIT));
/* WaBCSVCSTlbInvalidationMode:ivb,vlv,hsw */
if (IS_GEN7(dev_priv))
I915_WRITE(GFX_MODE_GEN7,
_MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_EXPLICIT) |
_MASKED_BIT_ENABLE(GFX_REPLAY_MODE));
if (IS_GEN6(dev_priv)) {
/* From the Sandybridge PRM, volume 1 part 3, page 24:
* "If this bit is set, STCunit will have LRA as replacement
* policy. [...] This bit must be reset. LRA replacement
* policy is not supported."
*/
I915_WRITE(CACHE_MODE_0,
_MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
}
if (IS_GEN(dev_priv, 6, 7))
I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
if (INTEL_GEN(dev_priv) >= 6)
I915_WRITE_IMR(engine, ~engine->irq_keep_mask);
return 0;
}
static u32 *gen6_signal(struct i915_request *rq, u32 *cs)
{
struct drm_i915_private *dev_priv = rq->i915;
struct intel_engine_cs *engine;
enum intel_engine_id id;
int num_rings = 0;
for_each_engine(engine, dev_priv, id) {
i915_reg_t mbox_reg;
if (!(BIT(engine->hw_id) & GEN6_SEMAPHORES_MASK))
continue;
mbox_reg = rq->engine->semaphore.mbox.signal[engine->hw_id];
if (i915_mmio_reg_valid(mbox_reg)) {
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = i915_mmio_reg_offset(mbox_reg);
*cs++ = rq->global_seqno;
num_rings++;
}
}
if (num_rings & 1)
*cs++ = MI_NOOP;
return cs;
}
static void cancel_requests(struct intel_engine_cs *engine)
{
struct i915_request *request;
unsigned long flags;
spin_lock_irqsave(&engine->timeline.lock, flags);
/* Mark all submitted requests as skipped. */
list_for_each_entry(request, &engine->timeline.requests, link) {
GEM_BUG_ON(!request->global_seqno);
if (!i915_request_completed(request))
dma_fence_set_error(&request->fence, -EIO);
}
/* Remaining _unready_ requests will be nop'ed when submitted */
spin_unlock_irqrestore(&engine->timeline.lock, flags);
}
static void i9xx_submit_request(struct i915_request *request)
{
struct drm_i915_private *dev_priv = request->i915;
i915_request_submit(request);
I915_WRITE_TAIL(request->engine,
intel_ring_set_tail(request->ring, request->tail));
}
static void i9xx_emit_breadcrumb(struct i915_request *rq, u32 *cs)
{
*cs++ = MI_STORE_DWORD_INDEX;
*cs++ = I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT;
*cs++ = rq->global_seqno;
*cs++ = MI_USER_INTERRUPT;
rq->tail = intel_ring_offset(rq, cs);
assert_ring_tail_valid(rq->ring, rq->tail);
}
static const int i9xx_emit_breadcrumb_sz = 4;
static void gen6_sema_emit_breadcrumb(struct i915_request *rq, u32 *cs)
{
return i9xx_emit_breadcrumb(rq, rq->engine->semaphore.signal(rq, cs));
}
static int
gen6_ring_sync_to(struct i915_request *rq, struct i915_request *signal)
{
u32 dw1 = MI_SEMAPHORE_MBOX |
MI_SEMAPHORE_COMPARE |
MI_SEMAPHORE_REGISTER;
u32 wait_mbox = signal->engine->semaphore.mbox.wait[rq->engine->hw_id];
u32 *cs;
WARN_ON(wait_mbox == MI_SEMAPHORE_SYNC_INVALID);
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = dw1 | wait_mbox;
/* Throughout all of the GEM code, seqno passed implies our current
* seqno is >= the last seqno executed. However for hardware the
* comparison is strictly greater than.
*/
*cs++ = signal->global_seqno - 1;
*cs++ = 0;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static void
gen5_seqno_barrier(struct intel_engine_cs *engine)
{
/* MI_STORE are internally buffered by the GPU and not flushed
* either by MI_FLUSH or SyncFlush or any other combination of
* MI commands.
*
* "Only the submission of the store operation is guaranteed.
* The write result will be complete (coherent) some time later
* (this is practically a finite period but there is no guaranteed
* latency)."
*
* Empirically, we observe that we need a delay of at least 75us to
* be sure that the seqno write is visible by the CPU.
*/
usleep_range(125, 250);
}
static void
gen6_seqno_barrier(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
/* Workaround to force correct ordering between irq and seqno writes on
* ivb (and maybe also on snb) by reading from a CS register (like
* ACTHD) before reading the status page.
*
* Note that this effectively stalls the read by the time it takes to
* do a memory transaction, which more or less ensures that the write
* from the GPU has sufficient time to invalidate the CPU cacheline.
* Alternatively we could delay the interrupt from the CS ring to give
* the write time to land, but that would incur a delay after every
* batch i.e. much more frequent than a delay when waiting for the
* interrupt (with the same net latency).
*
* Also note that to prevent whole machine hangs on gen7, we have to
* take the spinlock to guard against concurrent cacheline access.
*/
spin_lock_irq(&dev_priv->uncore.lock);
POSTING_READ_FW(RING_ACTHD(engine->mmio_base));
spin_unlock_irq(&dev_priv->uncore.lock);
}
static void
gen5_irq_enable(struct intel_engine_cs *engine)
{
gen5_enable_gt_irq(engine->i915, engine->irq_enable_mask);
}
static void
gen5_irq_disable(struct intel_engine_cs *engine)
{
gen5_disable_gt_irq(engine->i915, engine->irq_enable_mask);
}
static void
i9xx_irq_enable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
dev_priv->irq_mask &= ~engine->irq_enable_mask;
I915_WRITE(IMR, dev_priv->irq_mask);
POSTING_READ_FW(RING_IMR(engine->mmio_base));
}
static void
i9xx_irq_disable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
dev_priv->irq_mask |= engine->irq_enable_mask;
I915_WRITE(IMR, dev_priv->irq_mask);
}
static void
i8xx_irq_enable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
dev_priv->irq_mask &= ~engine->irq_enable_mask;
I915_WRITE16(IMR, dev_priv->irq_mask);
POSTING_READ16(RING_IMR(engine->mmio_base));
}
static void
i8xx_irq_disable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
dev_priv->irq_mask |= engine->irq_enable_mask;
I915_WRITE16(IMR, dev_priv->irq_mask);
}
static int
bsd_ring_flush(struct i915_request *rq, u32 mode)
{
u32 *cs;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_FLUSH;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static void
gen6_irq_enable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
I915_WRITE_IMR(engine,
~(engine->irq_enable_mask |
engine->irq_keep_mask));
gen5_enable_gt_irq(dev_priv, engine->irq_enable_mask);
}
static void
gen6_irq_disable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
I915_WRITE_IMR(engine, ~engine->irq_keep_mask);
gen5_disable_gt_irq(dev_priv, engine->irq_enable_mask);
}
static void
hsw_vebox_irq_enable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
I915_WRITE_IMR(engine, ~engine->irq_enable_mask);
gen6_unmask_pm_irq(dev_priv, engine->irq_enable_mask);
}
static void
hsw_vebox_irq_disable(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
I915_WRITE_IMR(engine, ~0);
gen6_mask_pm_irq(dev_priv, engine->irq_enable_mask);
}
static int
i965_emit_bb_start(struct i915_request *rq,
u64 offset, u32 length,
unsigned int dispatch_flags)
{
u32 *cs;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT | (dispatch_flags &
I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE_I965);
*cs++ = offset;
intel_ring_advance(rq, cs);
return 0;
}
/* Just userspace ABI convention to limit the wa batch bo to a resonable size */
#define I830_BATCH_LIMIT (256*1024)
#define I830_TLB_ENTRIES (2)
#define I830_WA_SIZE max(I830_TLB_ENTRIES*4096, I830_BATCH_LIMIT)
static int
i830_emit_bb_start(struct i915_request *rq,
u64 offset, u32 len,
unsigned int dispatch_flags)
{
u32 *cs, cs_offset = i915_ggtt_offset(rq->engine->scratch);
cs = intel_ring_begin(rq, 6);
if (IS_ERR(cs))
return PTR_ERR(cs);
/* Evict the invalid PTE TLBs */
*cs++ = COLOR_BLT_CMD | BLT_WRITE_RGBA;
*cs++ = BLT_DEPTH_32 | BLT_ROP_COLOR_COPY | 4096;
*cs++ = I830_TLB_ENTRIES << 16 | 4; /* load each page */
*cs++ = cs_offset;
*cs++ = 0xdeadbeef;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
if ((dispatch_flags & I915_DISPATCH_PINNED) == 0) {
if (len > I830_BATCH_LIMIT)
return -ENOSPC;
cs = intel_ring_begin(rq, 6 + 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
/* Blit the batch (which has now all relocs applied) to the
* stable batch scratch bo area (so that the CS never
* stumbles over its tlb invalidation bug) ...
*/
*cs++ = SRC_COPY_BLT_CMD | BLT_WRITE_RGBA;
*cs++ = BLT_DEPTH_32 | BLT_ROP_SRC_COPY | 4096;
*cs++ = DIV_ROUND_UP(len, 4096) << 16 | 4096;
*cs++ = cs_offset;
*cs++ = 4096;
*cs++ = offset;
*cs++ = MI_FLUSH;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
/* ... and execute it. */
offset = cs_offset;
}
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
*cs++ = offset | (dispatch_flags & I915_DISPATCH_SECURE ? 0 :
MI_BATCH_NON_SECURE);
intel_ring_advance(rq, cs);
return 0;
}
static int
i915_emit_bb_start(struct i915_request *rq,
u64 offset, u32 len,
unsigned int dispatch_flags)
{
u32 *cs;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
*cs++ = offset | (dispatch_flags & I915_DISPATCH_SECURE ? 0 :
MI_BATCH_NON_SECURE);
intel_ring_advance(rq, cs);
return 0;
}
int intel_ring_pin(struct intel_ring *ring)
{
struct i915_vma *vma = ring->vma;
enum i915_map_type map =
HAS_LLC(vma->vm->i915) ? I915_MAP_WB : I915_MAP_WC;
unsigned int flags;
void *addr;
int ret;
GEM_BUG_ON(ring->vaddr);
flags = PIN_GLOBAL;
/* Ring wraparound at offset 0 sometimes hangs. No idea why. */
flags |= PIN_OFFSET_BIAS | i915_ggtt_pin_bias(vma);
if (vma->obj->stolen)
flags |= PIN_MAPPABLE;
else
flags |= PIN_HIGH;
if (!(vma->flags & I915_VMA_GLOBAL_BIND)) {
if (flags & PIN_MAPPABLE || map == I915_MAP_WC)
ret = i915_gem_object_set_to_gtt_domain(vma->obj, true);
else
ret = i915_gem_object_set_to_cpu_domain(vma->obj, true);
if (unlikely(ret))
return ret;
}
ret = i915_vma_pin(vma, 0, 0, flags);
if (unlikely(ret))
return ret;
if (i915_vma_is_map_and_fenceable(vma))
addr = (void __force *)i915_vma_pin_iomap(vma);
else
addr = i915_gem_object_pin_map(vma->obj, map);
if (IS_ERR(addr))
goto err;
vma->obj->pin_global++;
ring->vaddr = addr;
return 0;
err:
i915_vma_unpin(vma);
return PTR_ERR(addr);
}
void intel_ring_reset(struct intel_ring *ring, u32 tail)
{
GEM_BUG_ON(!intel_ring_offset_valid(ring, tail));
ring->tail = tail;
ring->head = tail;
ring->emit = tail;
intel_ring_update_space(ring);
}
void intel_ring_unpin(struct intel_ring *ring)
{
GEM_BUG_ON(!ring->vma);
GEM_BUG_ON(!ring->vaddr);
/* Discard any unused bytes beyond that submitted to hw. */
intel_ring_reset(ring, ring->tail);
if (i915_vma_is_map_and_fenceable(ring->vma))
i915_vma_unpin_iomap(ring->vma);
else
i915_gem_object_unpin_map(ring->vma->obj);
ring->vaddr = NULL;
ring->vma->obj->pin_global--;
i915_vma_unpin(ring->vma);
}
static struct i915_vma *
intel_ring_create_vma(struct drm_i915_private *dev_priv, int size)
{
struct i915_address_space *vm = &dev_priv->ggtt.vm;
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
obj = i915_gem_object_create_stolen(dev_priv, size);
if (!obj)
obj = i915_gem_object_create_internal(dev_priv, size);
if (IS_ERR(obj))
return ERR_CAST(obj);
/*
* Mark ring buffers as read-only from GPU side (so no stray overwrites)
* if supported by the platform's GGTT.
*/
if (vm->has_read_only)
i915_gem_object_set_readonly(obj);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma))
goto err;
return vma;
err:
i915_gem_object_put(obj);
return vma;
}
struct intel_ring *
intel_engine_create_ring(struct intel_engine_cs *engine,
struct i915_timeline *timeline,
int size)
{
struct intel_ring *ring;
struct i915_vma *vma;
GEM_BUG_ON(!is_power_of_2(size));
GEM_BUG_ON(RING_CTL_SIZE(size) & ~RING_NR_PAGES);
GEM_BUG_ON(timeline == &engine->timeline);
lockdep_assert_held(&engine->i915->drm.struct_mutex);
ring = kzalloc(sizeof(*ring), GFP_KERNEL);
if (!ring)
return ERR_PTR(-ENOMEM);
INIT_LIST_HEAD(&ring->request_list);
ring->timeline = i915_timeline_get(timeline);
ring->size = size;
/* Workaround an erratum on the i830 which causes a hang if
* the TAIL pointer points to within the last 2 cachelines
* of the buffer.
*/
ring->effective_size = size;
if (IS_I830(engine->i915) || IS_I845G(engine->i915))
ring->effective_size -= 2 * CACHELINE_BYTES;
intel_ring_update_space(ring);
vma = intel_ring_create_vma(engine->i915, size);
if (IS_ERR(vma)) {
kfree(ring);
return ERR_CAST(vma);
}
ring->vma = vma;
return ring;
}
void
intel_ring_free(struct intel_ring *ring)
{
struct drm_i915_gem_object *obj = ring->vma->obj;
i915_vma_close(ring->vma);
__i915_gem_object_release_unless_active(obj);
i915_timeline_put(ring->timeline);
kfree(ring);
}
static void intel_ring_context_destroy(struct intel_context *ce)
{
GEM_BUG_ON(ce->pin_count);
if (!ce->state)
return;
GEM_BUG_ON(i915_gem_object_is_active(ce->state->obj));
i915_gem_object_put(ce->state->obj);
}
static int __context_pin_ppgtt(struct i915_gem_context *ctx)
{
struct i915_hw_ppgtt *ppgtt;
int err = 0;
ppgtt = ctx->ppgtt ?: ctx->i915->mm.aliasing_ppgtt;
if (ppgtt)
err = gen6_ppgtt_pin(ppgtt);
return err;
}
static void __context_unpin_ppgtt(struct i915_gem_context *ctx)
{
struct i915_hw_ppgtt *ppgtt;
ppgtt = ctx->ppgtt ?: ctx->i915->mm.aliasing_ppgtt;
if (ppgtt)
gen6_ppgtt_unpin(ppgtt);
}
static int __context_pin(struct intel_context *ce)
{
struct i915_vma *vma;
int err;
vma = ce->state;
if (!vma)
return 0;
/*
* Clear this page out of any CPU caches for coherent swap-in/out.
* We only want to do this on the first bind so that we do not stall
* on an active context (which by nature is already on the GPU).
*/
if (!(vma->flags & I915_VMA_GLOBAL_BIND)) {
err = i915_gem_object_set_to_gtt_domain(vma->obj, true);
if (err)
return err;
}
err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
if (err)
return err;
/*
* And mark is as a globally pinned object to let the shrinker know
* it cannot reclaim the object until we release it.
*/
vma->obj->pin_global++;
return 0;
}
static void __context_unpin(struct intel_context *ce)
{
struct i915_vma *vma;
vma = ce->state;
if (!vma)
return;
vma->obj->pin_global--;
i915_vma_unpin(vma);
}
static void intel_ring_context_unpin(struct intel_context *ce)
{
__context_unpin_ppgtt(ce->gem_context);
__context_unpin(ce);
i915_gem_context_put(ce->gem_context);
}
static struct i915_vma *
alloc_context_vma(struct intel_engine_cs *engine)
{
struct drm_i915_private *i915 = engine->i915;
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
int err;
obj = i915_gem_object_create(i915, engine->context_size);
if (IS_ERR(obj))
return ERR_CAST(obj);
if (engine->default_state) {
void *defaults, *vaddr;
vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
if (IS_ERR(vaddr)) {
err = PTR_ERR(vaddr);
goto err_obj;
}
defaults = i915_gem_object_pin_map(engine->default_state,
I915_MAP_WB);
if (IS_ERR(defaults)) {
err = PTR_ERR(defaults);
goto err_map;
}
memcpy(vaddr, defaults, engine->context_size);
i915_gem_object_unpin_map(engine->default_state);
i915_gem_object_unpin_map(obj);
}
/*
* Try to make the context utilize L3 as well as LLC.
*
* On VLV we don't have L3 controls in the PTEs so we
* shouldn't touch the cache level, especially as that
* would make the object snooped which might have a
* negative performance impact.
*
* Snooping is required on non-llc platforms in execlist
* mode, but since all GGTT accesses use PAT entry 0 we
* get snooping anyway regardless of cache_level.
*
* This is only applicable for Ivy Bridge devices since
* later platforms don't have L3 control bits in the PTE.
*/
if (IS_IVYBRIDGE(i915)) {
/* Ignore any error, regard it as a simple optimisation */
i915_gem_object_set_cache_level(obj, I915_CACHE_L3_LLC);
}
vma = i915_vma_instance(obj, &i915->ggtt.vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_obj;
}
return vma;
err_map:
i915_gem_object_unpin_map(obj);
err_obj:
i915_gem_object_put(obj);
return ERR_PTR(err);
}
static struct intel_context *
__ring_context_pin(struct intel_engine_cs *engine,
struct i915_gem_context *ctx,
struct intel_context *ce)
{
int err;
if (!ce->state && engine->context_size) {
struct i915_vma *vma;
vma = alloc_context_vma(engine);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err;
}
ce->state = vma;
}
err = __context_pin(ce);
if (err)
goto err;
err = __context_pin_ppgtt(ce->gem_context);
if (err)
goto err_unpin;
i915_gem_context_get(ctx);
/* One ringbuffer to rule them all */
GEM_BUG_ON(!engine->buffer);
ce->ring = engine->buffer;
return ce;
err_unpin:
__context_unpin(ce);
err:
ce->pin_count = 0;
return ERR_PTR(err);
}
static const struct intel_context_ops ring_context_ops = {
.unpin = intel_ring_context_unpin,
.destroy = intel_ring_context_destroy,
};
static struct intel_context *
intel_ring_context_pin(struct intel_engine_cs *engine,
struct i915_gem_context *ctx)
{
struct intel_context *ce = to_intel_context(ctx, engine);
lockdep_assert_held(&ctx->i915->drm.struct_mutex);
if (likely(ce->pin_count++))
return ce;
GEM_BUG_ON(!ce->pin_count); /* no overflow please! */
ce->ops = &ring_context_ops;
return __ring_context_pin(engine, ctx, ce);
}
static int intel_init_ring_buffer(struct intel_engine_cs *engine)
{
struct i915_timeline *timeline;
struct intel_ring *ring;
unsigned int size;
int err;
intel_engine_setup_common(engine);
timeline = i915_timeline_create(engine->i915, engine->name);
if (IS_ERR(timeline)) {
err = PTR_ERR(timeline);
goto err;
}
ring = intel_engine_create_ring(engine, timeline, 32 * PAGE_SIZE);
i915_timeline_put(timeline);
if (IS_ERR(ring)) {
err = PTR_ERR(ring);
goto err;
}
err = intel_ring_pin(ring);
if (err)
goto err_ring;
GEM_BUG_ON(engine->buffer);
engine->buffer = ring;
size = PAGE_SIZE;
if (HAS_BROKEN_CS_TLB(engine->i915))
size = I830_WA_SIZE;
err = intel_engine_create_scratch(engine, size);
if (err)
goto err_unpin;
err = intel_engine_init_common(engine);
if (err)
goto err_scratch;
return 0;
err_scratch:
intel_engine_cleanup_scratch(engine);
err_unpin:
intel_ring_unpin(ring);
err_ring:
intel_ring_free(ring);
err:
intel_engine_cleanup_common(engine);
return err;
}
void intel_engine_cleanup(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
WARN_ON(INTEL_GEN(dev_priv) > 2 &&
(I915_READ_MODE(engine) & MODE_IDLE) == 0);
intel_ring_unpin(engine->buffer);
intel_ring_free(engine->buffer);
if (engine->cleanup)
engine->cleanup(engine);
intel_engine_cleanup_common(engine);
dev_priv->engine[engine->id] = NULL;
kfree(engine);
}
void intel_legacy_submission_resume(struct drm_i915_private *dev_priv)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
/* Restart from the beginning of the rings for convenience */
for_each_engine(engine, dev_priv, id)
intel_ring_reset(engine->buffer, 0);
}
static int load_pd_dir(struct i915_request *rq,
const struct i915_hw_ppgtt *ppgtt)
{
const struct intel_engine_cs * const engine = rq->engine;
u32 *cs;
cs = intel_ring_begin(rq, 6);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = i915_mmio_reg_offset(RING_PP_DIR_DCLV(engine));
*cs++ = PP_DIR_DCLV_2G;
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = i915_mmio_reg_offset(RING_PP_DIR_BASE(engine));
*cs++ = ppgtt->pd.base.ggtt_offset << 10;
intel_ring_advance(rq, cs);
return 0;
}
static int flush_pd_dir(struct i915_request *rq)
{
const struct intel_engine_cs * const engine = rq->engine;
u32 *cs;
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
/* Stall until the page table load is complete */
*cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
*cs++ = i915_mmio_reg_offset(RING_PP_DIR_BASE(engine));
*cs++ = i915_ggtt_offset(engine->scratch);
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static inline int mi_set_context(struct i915_request *rq, u32 flags)
{
struct drm_i915_private *i915 = rq->i915;
struct intel_engine_cs *engine = rq->engine;
enum intel_engine_id id;
const int num_rings =
/* Use an extended w/a on gen7 if signalling from other rings */
(HAS_LEGACY_SEMAPHORES(i915) && IS_GEN7(i915)) ?
INTEL_INFO(i915)->num_rings - 1 :
0;
bool force_restore = false;
int len;
u32 *cs;
flags |= MI_MM_SPACE_GTT;
if (IS_HASWELL(i915))
/* These flags are for resource streamer on HSW+ */
flags |= HSW_MI_RS_SAVE_STATE_EN | HSW_MI_RS_RESTORE_STATE_EN;
else
flags |= MI_SAVE_EXT_STATE_EN | MI_RESTORE_EXT_STATE_EN;
len = 4;
if (IS_GEN7(i915))
len += 2 + (num_rings ? 4*num_rings + 6 : 0);
if (flags & MI_FORCE_RESTORE) {
GEM_BUG_ON(flags & MI_RESTORE_INHIBIT);
flags &= ~MI_FORCE_RESTORE;
force_restore = true;
len += 2;
}
cs = intel_ring_begin(rq, len);
if (IS_ERR(cs))
return PTR_ERR(cs);
/* WaProgramMiArbOnOffAroundMiSetContext:ivb,vlv,hsw,bdw,chv */
if (IS_GEN7(i915)) {
*cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
if (num_rings) {
struct intel_engine_cs *signaller;
*cs++ = MI_LOAD_REGISTER_IMM(num_rings);
for_each_engine(signaller, i915, id) {
if (signaller == engine)
continue;
*cs++ = i915_mmio_reg_offset(
RING_PSMI_CTL(signaller->mmio_base));
*cs++ = _MASKED_BIT_ENABLE(
GEN6_PSMI_SLEEP_MSG_DISABLE);
}
}
}
if (force_restore) {
/*
* The HW doesn't handle being told to restore the current
* context very well. Quite often it likes goes to go off and
* sulk, especially when it is meant to be reloading PP_DIR.
* A very simple fix to force the reload is to simply switch
* away from the current context and back again.
*
* Note that the kernel_context will contain random state
* following the INHIBIT_RESTORE. We accept this since we
* never use the kernel_context state; it is merely a
* placeholder we use to flush other contexts.
*/
*cs++ = MI_SET_CONTEXT;
*cs++ = i915_ggtt_offset(to_intel_context(i915->kernel_context,
engine)->state) |
MI_MM_SPACE_GTT |
MI_RESTORE_INHIBIT;
}
*cs++ = MI_NOOP;
*cs++ = MI_SET_CONTEXT;
*cs++ = i915_ggtt_offset(rq->hw_context->state) | flags;
/*
* w/a: MI_SET_CONTEXT must always be followed by MI_NOOP
* WaMiSetContext_Hang:snb,ivb,vlv
*/
*cs++ = MI_NOOP;
if (IS_GEN7(i915)) {
if (num_rings) {
struct intel_engine_cs *signaller;
i915_reg_t last_reg = {}; /* keep gcc quiet */
*cs++ = MI_LOAD_REGISTER_IMM(num_rings);
for_each_engine(signaller, i915, id) {
if (signaller == engine)
continue;
last_reg = RING_PSMI_CTL(signaller->mmio_base);
*cs++ = i915_mmio_reg_offset(last_reg);
*cs++ = _MASKED_BIT_DISABLE(
GEN6_PSMI_SLEEP_MSG_DISABLE);
}
/* Insert a delay before the next switch! */
*cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
*cs++ = i915_mmio_reg_offset(last_reg);
*cs++ = i915_ggtt_offset(engine->scratch);
*cs++ = MI_NOOP;
}
*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
}
intel_ring_advance(rq, cs);
return 0;
}
static int remap_l3(struct i915_request *rq, int slice)
{
u32 *cs, *remap_info = rq->i915->l3_parity.remap_info[slice];
int i;
if (!remap_info)
return 0;
cs = intel_ring_begin(rq, GEN7_L3LOG_SIZE/4 * 2 + 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
/*
* Note: We do not worry about the concurrent register cacheline hang
* here because no other code should access these registers other than
* at initialization time.
*/
*cs++ = MI_LOAD_REGISTER_IMM(GEN7_L3LOG_SIZE/4);
for (i = 0; i < GEN7_L3LOG_SIZE/4; i++) {
*cs++ = i915_mmio_reg_offset(GEN7_L3LOG(slice, i));
*cs++ = remap_info[i];
}
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static int switch_context(struct i915_request *rq)
{
struct intel_engine_cs *engine = rq->engine;
struct i915_gem_context *ctx = rq->gem_context;
struct i915_hw_ppgtt *ppgtt = ctx->ppgtt ?: rq->i915->mm.aliasing_ppgtt;
unsigned int unwind_mm = 0;
u32 hw_flags = 0;
int ret, i;
lockdep_assert_held(&rq->i915->drm.struct_mutex);
GEM_BUG_ON(HAS_EXECLISTS(rq->i915));
if (ppgtt) {
int loops;
/*
* Baytail takes a little more convincing that it really needs
* to reload the PD between contexts. It is not just a little
* longer, as adding more stalls after the load_pd_dir (i.e.
* adding a long loop around flush_pd_dir) is not as effective
* as reloading the PD umpteen times. 32 is derived from
* experimentation (gem_exec_parallel/fds) and has no good
* explanation.
*/
loops = 1;
if (engine->id == BCS && IS_VALLEYVIEW(engine->i915))
loops = 32;
do {
ret = load_pd_dir(rq, ppgtt);
if (ret)
goto err;
} while (--loops);
if (intel_engine_flag(engine) & ppgtt->pd_dirty_rings) {
unwind_mm = intel_engine_flag(engine);
ppgtt->pd_dirty_rings &= ~unwind_mm;
hw_flags = MI_FORCE_RESTORE;
}
}
if (rq->hw_context->state) {
GEM_BUG_ON(engine->id != RCS);
/*
* The kernel context(s) is treated as pure scratch and is not
* expected to retain any state (as we sacrifice it during
* suspend and on resume it may be corrupted). This is ok,
* as nothing actually executes using the kernel context; it
* is purely used for flushing user contexts.
*/
if (i915_gem_context_is_kernel(ctx))
hw_flags = MI_RESTORE_INHIBIT;
ret = mi_set_context(rq, hw_flags);
if (ret)
goto err_mm;
}
if (ppgtt) {
ret = engine->emit_flush(rq, EMIT_INVALIDATE);
if (ret)
goto err_mm;
ret = flush_pd_dir(rq);
if (ret)
goto err_mm;
/*
* Not only do we need a full barrier (post-sync write) after
* invalidating the TLBs, but we need to wait a little bit
* longer. Whether this is merely delaying us, or the
* subsequent flush is a key part of serialising with the
* post-sync op, this extra pass appears vital before a
* mm switch!
*/
ret = engine->emit_flush(rq, EMIT_INVALIDATE);
if (ret)
goto err_mm;
ret = engine->emit_flush(rq, EMIT_FLUSH);
if (ret)
goto err_mm;
}
if (ctx->remap_slice) {
for (i = 0; i < MAX_L3_SLICES; i++) {
if (!(ctx->remap_slice & BIT(i)))
continue;
ret = remap_l3(rq, i);
if (ret)
goto err_mm;
}
ctx->remap_slice = 0;
}
return 0;
err_mm:
if (unwind_mm)
ppgtt->pd_dirty_rings |= unwind_mm;
err:
return ret;
}
static int ring_request_alloc(struct i915_request *request)
{
int ret;
GEM_BUG_ON(!request->hw_context->pin_count);
/* Flush enough space to reduce the likelihood of waiting after
* we start building the request - in which case we will just
* have to repeat work.
*/
request->reserved_space += LEGACY_REQUEST_SIZE;
ret = intel_ring_wait_for_space(request->ring, request->reserved_space);
if (ret)
return ret;
ret = switch_context(request);
if (ret)
return ret;
request->reserved_space -= LEGACY_REQUEST_SIZE;
return 0;
}
static noinline int wait_for_space(struct intel_ring *ring, unsigned int bytes)
{
struct i915_request *target;
long timeout;
lockdep_assert_held(&ring->vma->vm->i915->drm.struct_mutex);
if (intel_ring_update_space(ring) >= bytes)
return 0;
GEM_BUG_ON(list_empty(&ring->request_list));
list_for_each_entry(target, &ring->request_list, ring_link) {
/* Would completion of this request free enough space? */
if (bytes <= __intel_ring_space(target->postfix,
ring->emit, ring->size))
break;
}
if (WARN_ON(&target->ring_link == &ring->request_list))
return -ENOSPC;
timeout = i915_request_wait(target,
I915_WAIT_INTERRUPTIBLE | I915_WAIT_LOCKED,
MAX_SCHEDULE_TIMEOUT);
if (timeout < 0)
return timeout;
i915_request_retire_upto(target);
intel_ring_update_space(ring);
GEM_BUG_ON(ring->space < bytes);
return 0;
}
int intel_ring_wait_for_space(struct intel_ring *ring, unsigned int bytes)
{
GEM_BUG_ON(bytes > ring->effective_size);
if (unlikely(bytes > ring->effective_size - ring->emit))
bytes += ring->size - ring->emit;
if (unlikely(bytes > ring->space)) {
int ret = wait_for_space(ring, bytes);
if (unlikely(ret))
return ret;
}
GEM_BUG_ON(ring->space < bytes);
return 0;
}
u32 *intel_ring_begin(struct i915_request *rq, unsigned int num_dwords)
{
struct intel_ring *ring = rq->ring;
const unsigned int remain_usable = ring->effective_size - ring->emit;
const unsigned int bytes = num_dwords * sizeof(u32);
unsigned int need_wrap = 0;
unsigned int total_bytes;
u32 *cs;
/* Packets must be qword aligned. */
GEM_BUG_ON(num_dwords & 1);
total_bytes = bytes + rq->reserved_space;
GEM_BUG_ON(total_bytes > ring->effective_size);
if (unlikely(total_bytes > remain_usable)) {
const int remain_actual = ring->size - ring->emit;
if (bytes > remain_usable) {
/*
* Not enough space for the basic request. So need to
* flush out the remainder and then wait for
* base + reserved.
*/
total_bytes += remain_actual;
need_wrap = remain_actual | 1;
} else {
/*
* The base request will fit but the reserved space
* falls off the end. So we don't need an immediate
* wrap and only need to effectively wait for the
* reserved size from the start of ringbuffer.
*/
total_bytes = rq->reserved_space + remain_actual;
}
}
if (unlikely(total_bytes > ring->space)) {
int ret;
/*
* Space is reserved in the ringbuffer for finalising the
* request, as that cannot be allowed to fail. During request
* finalisation, reserved_space is set to 0 to stop the
* overallocation and the assumption is that then we never need
* to wait (which has the risk of failing with EINTR).
*
* See also i915_request_alloc() and i915_request_add().
*/
GEM_BUG_ON(!rq->reserved_space);
ret = wait_for_space(ring, total_bytes);
if (unlikely(ret))
return ERR_PTR(ret);
}
if (unlikely(need_wrap)) {
need_wrap &= ~1;
GEM_BUG_ON(need_wrap > ring->space);
GEM_BUG_ON(ring->emit + need_wrap > ring->size);
GEM_BUG_ON(!IS_ALIGNED(need_wrap, sizeof(u64)));
/* Fill the tail with MI_NOOP */
memset64(ring->vaddr + ring->emit, 0, need_wrap / sizeof(u64));
ring->space -= need_wrap;
ring->emit = 0;
}
GEM_BUG_ON(ring->emit > ring->size - bytes);
GEM_BUG_ON(ring->space < bytes);
cs = ring->vaddr + ring->emit;
GEM_DEBUG_EXEC(memset32(cs, POISON_INUSE, bytes / sizeof(*cs)));
ring->emit += bytes;
ring->space -= bytes;
return cs;
}
/* Align the ring tail to a cacheline boundary */
int intel_ring_cacheline_align(struct i915_request *rq)
{
int num_dwords;
void *cs;
num_dwords = (rq->ring->emit & (CACHELINE_BYTES - 1)) / sizeof(u32);
if (num_dwords == 0)
return 0;
num_dwords = CACHELINE_DWORDS - num_dwords;
GEM_BUG_ON(num_dwords & 1);
cs = intel_ring_begin(rq, num_dwords);
if (IS_ERR(cs))
return PTR_ERR(cs);
memset64(cs, (u64)MI_NOOP << 32 | MI_NOOP, num_dwords / 2);
intel_ring_advance(rq, cs);
GEM_BUG_ON(rq->ring->emit & (CACHELINE_BYTES - 1));
return 0;
}
static void gen6_bsd_submit_request(struct i915_request *request)
{
struct drm_i915_private *dev_priv = request->i915;
intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
/* Every tail move must follow the sequence below */
/* Disable notification that the ring is IDLE. The GT
* will then assume that it is busy and bring it out of rc6.
*/
I915_WRITE_FW(GEN6_BSD_SLEEP_PSMI_CONTROL,
_MASKED_BIT_ENABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
/* Clear the context id. Here be magic! */
I915_WRITE64_FW(GEN6_BSD_RNCID, 0x0);
/* Wait for the ring not to be idle, i.e. for it to wake up. */
if (__intel_wait_for_register_fw(dev_priv,
GEN6_BSD_SLEEP_PSMI_CONTROL,
GEN6_BSD_SLEEP_INDICATOR,
0,
1000, 0, NULL))
DRM_ERROR("timed out waiting for the BSD ring to wake up\n");
/* Now that the ring is fully powered up, update the tail */
i9xx_submit_request(request);
/* Let the ring send IDLE messages to the GT again,
* and so let it sleep to conserve power when idle.
*/
I915_WRITE_FW(GEN6_BSD_SLEEP_PSMI_CONTROL,
_MASKED_BIT_DISABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
}
static int mi_flush_dw(struct i915_request *rq, u32 flags)
{
u32 cmd, *cs;
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
cmd = MI_FLUSH_DW;
/*
* We always require a command barrier so that subsequent
* commands, such as breadcrumb interrupts, are strictly ordered
* wrt the contents of the write cache being flushed to memory
* (and thus being coherent from the CPU).
*/
cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
/*
* Bspec vol 1c.3 - blitter engine command streamer:
* "If ENABLED, all TLBs will be invalidated once the flush
* operation is complete. This bit is only valid when the
* Post-Sync Operation field is a value of 1h or 3h."
*/
cmd |= flags;
*cs++ = cmd;
*cs++ = I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT;
*cs++ = 0;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static int gen6_flush_dw(struct i915_request *rq, u32 mode, u32 invflags)
{
return mi_flush_dw(rq, mode & EMIT_INVALIDATE ? invflags : 0);
}
static int gen6_bsd_ring_flush(struct i915_request *rq, u32 mode)
{
return gen6_flush_dw(rq, mode, MI_INVALIDATE_TLB | MI_INVALIDATE_BSD);
}
static int
hsw_emit_bb_start(struct i915_request *rq,
u64 offset, u32 len,
unsigned int dispatch_flags)
{
u32 *cs;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | (dispatch_flags & I915_DISPATCH_SECURE ?
0 : MI_BATCH_PPGTT_HSW | MI_BATCH_NON_SECURE_HSW);
/* bit0-7 is the length on GEN6+ */
*cs++ = offset;
intel_ring_advance(rq, cs);
return 0;
}
static int
gen6_emit_bb_start(struct i915_request *rq,
u64 offset, u32 len,
unsigned int dispatch_flags)
{
u32 *cs;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | (dispatch_flags & I915_DISPATCH_SECURE ?
0 : MI_BATCH_NON_SECURE_I965);
/* bit0-7 is the length on GEN6+ */
*cs++ = offset;
intel_ring_advance(rq, cs);
return 0;
}
/* Blitter support (SandyBridge+) */
static int gen6_ring_flush(struct i915_request *rq, u32 mode)
{
return gen6_flush_dw(rq, mode, MI_INVALIDATE_TLB);
}
static void intel_ring_init_semaphores(struct drm_i915_private *dev_priv,
struct intel_engine_cs *engine)
{
int i;
if (!HAS_LEGACY_SEMAPHORES(dev_priv))
return;
GEM_BUG_ON(INTEL_GEN(dev_priv) < 6);
engine->semaphore.sync_to = gen6_ring_sync_to;
engine->semaphore.signal = gen6_signal;
/*
* The current semaphore is only applied on pre-gen8
* platform. And there is no VCS2 ring on the pre-gen8
* platform. So the semaphore between RCS and VCS2 is
* initialized as INVALID.
*/
for (i = 0; i < GEN6_NUM_SEMAPHORES; i++) {
static const struct {
u32 wait_mbox;
i915_reg_t mbox_reg;
} sem_data[GEN6_NUM_SEMAPHORES][GEN6_NUM_SEMAPHORES] = {
[RCS_HW] = {
[VCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_RV, .mbox_reg = GEN6_VRSYNC },
[BCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_RB, .mbox_reg = GEN6_BRSYNC },
[VECS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_RVE, .mbox_reg = GEN6_VERSYNC },
},
[VCS_HW] = {
[RCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_VR, .mbox_reg = GEN6_RVSYNC },
[BCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_VB, .mbox_reg = GEN6_BVSYNC },
[VECS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_VVE, .mbox_reg = GEN6_VEVSYNC },
},
[BCS_HW] = {
[RCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_BR, .mbox_reg = GEN6_RBSYNC },
[VCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_BV, .mbox_reg = GEN6_VBSYNC },
[VECS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_BVE, .mbox_reg = GEN6_VEBSYNC },
},
[VECS_HW] = {
[RCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_VER, .mbox_reg = GEN6_RVESYNC },
[VCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_VEV, .mbox_reg = GEN6_VVESYNC },
[BCS_HW] = { .wait_mbox = MI_SEMAPHORE_SYNC_VEB, .mbox_reg = GEN6_BVESYNC },
},
};
u32 wait_mbox;
i915_reg_t mbox_reg;
if (i == engine->hw_id) {
wait_mbox = MI_SEMAPHORE_SYNC_INVALID;
mbox_reg = GEN6_NOSYNC;
} else {
wait_mbox = sem_data[engine->hw_id][i].wait_mbox;
mbox_reg = sem_data[engine->hw_id][i].mbox_reg;
}
engine->semaphore.mbox.wait[i] = wait_mbox;
engine->semaphore.mbox.signal[i] = mbox_reg;
}
}
static void intel_ring_init_irq(struct drm_i915_private *dev_priv,
struct intel_engine_cs *engine)
{
if (INTEL_GEN(dev_priv) >= 6) {
engine->irq_enable = gen6_irq_enable;
engine->irq_disable = gen6_irq_disable;
engine->irq_seqno_barrier = gen6_seqno_barrier;
} else if (INTEL_GEN(dev_priv) >= 5) {
engine->irq_enable = gen5_irq_enable;
engine->irq_disable = gen5_irq_disable;
engine->irq_seqno_barrier = gen5_seqno_barrier;
} else if (INTEL_GEN(dev_priv) >= 3) {
engine->irq_enable = i9xx_irq_enable;
engine->irq_disable = i9xx_irq_disable;
} else {
engine->irq_enable = i8xx_irq_enable;
engine->irq_disable = i8xx_irq_disable;
}
}
static void i9xx_set_default_submission(struct intel_engine_cs *engine)
{
engine->submit_request = i9xx_submit_request;
engine->cancel_requests = cancel_requests;
engine->park = NULL;
engine->unpark = NULL;
}
static void gen6_bsd_set_default_submission(struct intel_engine_cs *engine)
{
i9xx_set_default_submission(engine);
engine->submit_request = gen6_bsd_submit_request;
}
static void intel_ring_default_vfuncs(struct drm_i915_private *dev_priv,
struct intel_engine_cs *engine)
{
/* gen8+ are only supported with execlists */
GEM_BUG_ON(INTEL_GEN(dev_priv) >= 8);
intel_ring_init_irq(dev_priv, engine);
intel_ring_init_semaphores(dev_priv, engine);
engine->init_hw = init_ring_common;
engine->reset.prepare = reset_prepare;
engine->reset.reset = reset_ring;
engine->reset.finish = reset_finish;
engine->context_pin = intel_ring_context_pin;
engine->request_alloc = ring_request_alloc;
engine->emit_breadcrumb = i9xx_emit_breadcrumb;
engine->emit_breadcrumb_sz = i9xx_emit_breadcrumb_sz;
if (HAS_LEGACY_SEMAPHORES(dev_priv)) {
int num_rings;
engine->emit_breadcrumb = gen6_sema_emit_breadcrumb;
num_rings = INTEL_INFO(dev_priv)->num_rings - 1;
engine->emit_breadcrumb_sz += num_rings * 3;
if (num_rings & 1)
engine->emit_breadcrumb_sz++;
}
engine->set_default_submission = i9xx_set_default_submission;
if (INTEL_GEN(dev_priv) >= 6)
engine->emit_bb_start = gen6_emit_bb_start;
else if (INTEL_GEN(dev_priv) >= 4)
engine->emit_bb_start = i965_emit_bb_start;
else if (IS_I830(dev_priv) || IS_I845G(dev_priv))
engine->emit_bb_start = i830_emit_bb_start;
else
engine->emit_bb_start = i915_emit_bb_start;
}
int intel_init_render_ring_buffer(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
int ret;
intel_ring_default_vfuncs(dev_priv, engine);
if (HAS_L3_DPF(dev_priv))
engine->irq_keep_mask = GT_RENDER_L3_PARITY_ERROR_INTERRUPT;
engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT;
if (INTEL_GEN(dev_priv) >= 6) {
engine->init_context = intel_rcs_ctx_init;
engine->emit_flush = gen7_render_ring_flush;
if (IS_GEN6(dev_priv))
engine->emit_flush = gen6_render_ring_flush;
} else if (IS_GEN5(dev_priv)) {
engine->emit_flush = gen4_render_ring_flush;
} else {
if (INTEL_GEN(dev_priv) < 4)
engine->emit_flush = gen2_render_ring_flush;
else
engine->emit_flush = gen4_render_ring_flush;
engine->irq_enable_mask = I915_USER_INTERRUPT;
}
if (IS_HASWELL(dev_priv))
engine->emit_bb_start = hsw_emit_bb_start;
engine->init_hw = init_render_ring;
ret = intel_init_ring_buffer(engine);
if (ret)
return ret;
return 0;
}
int intel_init_bsd_ring_buffer(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
intel_ring_default_vfuncs(dev_priv, engine);
if (INTEL_GEN(dev_priv) >= 6) {
/* gen6 bsd needs a special wa for tail updates */
if (IS_GEN6(dev_priv))
engine->set_default_submission = gen6_bsd_set_default_submission;
engine->emit_flush = gen6_bsd_ring_flush;
engine->irq_enable_mask = GT_BSD_USER_INTERRUPT;
} else {
engine->emit_flush = bsd_ring_flush;
if (IS_GEN5(dev_priv))
engine->irq_enable_mask = ILK_BSD_USER_INTERRUPT;
else
engine->irq_enable_mask = I915_BSD_USER_INTERRUPT;
}
return intel_init_ring_buffer(engine);
}
int intel_init_blt_ring_buffer(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
intel_ring_default_vfuncs(dev_priv, engine);
engine->emit_flush = gen6_ring_flush;
engine->irq_enable_mask = GT_BLT_USER_INTERRUPT;
return intel_init_ring_buffer(engine);
}
int intel_init_vebox_ring_buffer(struct intel_engine_cs *engine)
{
struct drm_i915_private *dev_priv = engine->i915;
intel_ring_default_vfuncs(dev_priv, engine);
engine->emit_flush = gen6_ring_flush;
engine->irq_enable_mask = PM_VEBOX_USER_INTERRUPT;
engine->irq_enable = hsw_vebox_irq_enable;
engine->irq_disable = hsw_vebox_irq_disable;
return intel_init_ring_buffer(engine);
}
| 25.93316 | 91 | 0.717038 | [
"render",
"object",
"3d"
] |
d0ef7eefa6ae5cda5f3e00379663ad8ba3f4eef9 | 1,071 | h | C | System/Library/Frameworks/Metal.framework/MTLDebugInstrumentationData.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | 2 | 2020-07-26T20:30:54.000Z | 2020-08-10T04:26:23.000Z | System/Library/Frameworks/Metal.framework/MTLDebugInstrumentationData.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | 1 | 2020-07-26T20:45:31.000Z | 2020-08-09T09:30:46.000Z | System/Library/Frameworks/Metal.framework/MTLDebugInstrumentationData.h | lechium/tvOS135Headers | 46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, June 7, 2020 at 11:12:36 AM Mountain Standard Time
* Operating System: Version 13.4.5 (Build 17L562)
* Image Source: /System/Library/Frameworks/Metal.framework/Metal
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@protocol OS_dispatch_data;
#import <Metal/Metal-Structs.h>
@class NSObject;
@interface MTLDebugInstrumentationData : NSObject {
NSObject*<OS_dispatch_data> _dataMap;
const MTLSerializedDebugInstrumentationData* _data;
vector<const __CFString *, std::__1::allocator<const __CFString *> >* _strings;
vector<MTLDebugLocation *, std::__1::allocator<MTLDebugLocation *> >* _debugLocations;
vector<MTLDebugSubProgram *, std::__1::allocator<MTLDebugSubProgram *> >* _debugSubPrograms;
}
@property (nonatomic,readonly) BOOL hasBacktrackingFailures;
-(void)dealloc;
-(id)initWithData:(id)arg1 ;
-(id)debugSubProgramForID:(unsigned)arg1 ;
-(id)debugLocationForID:(unsigned)arg1 ;
-(id)stringForID:(unsigned)arg1 ;
-(BOOL)hasBacktrackingFailures;
@end
| 32.454545 | 93 | 0.773109 | [
"vector"
] |
d0f4ca8a5fe5e854897090522cdc63d3cb32014b | 6,888 | h | C | src/ray/core_worker/lib/java/jni_utils.h | tonymackinnon/ray | 14a1419682bdba40d2c8bf226e1727cf44abcaa4 | [
"Apache-2.0"
] | 1 | 2020-09-27T08:48:11.000Z | 2020-09-27T08:48:11.000Z | src/ray/core_worker/lib/java/jni_utils.h | tonymackinnon/ray | 14a1419682bdba40d2c8bf226e1727cf44abcaa4 | [
"Apache-2.0"
] | null | null | null | src/ray/core_worker/lib/java/jni_utils.h | tonymackinnon/ray | 14a1419682bdba40d2c8bf226e1727cf44abcaa4 | [
"Apache-2.0"
] | 1 | 2020-01-13T07:58:05.000Z | 2020-01-13T07:58:05.000Z | #ifndef RAY_COMMON_JAVA_JNI_HELPER_H
#define RAY_COMMON_JAVA_JNI_HELPER_H
#include <jni.h>
#include "ray/common/buffer.h"
#include "ray/common/id.h"
#include "ray/common/status.h"
#include "ray/core_worker/store_provider/store_provider.h"
/// Boolean class
extern jclass java_boolean_class;
/// Constructor of Boolean class
extern jmethodID java_boolean_init;
/// List class
extern jclass java_list_class;
/// size method of List class
extern jmethodID java_list_size;
/// get method of List class
extern jmethodID java_list_get;
/// add method of List class
extern jmethodID java_list_add;
/// ArrayList class
extern jclass java_array_list_class;
/// Constructor of ArrayList class
extern jmethodID java_array_list_init;
/// Constructor of ArrayList class with single parameter capacity
extern jmethodID java_array_list_init_with_capacity;
/// RayException class
extern jclass java_ray_exception_class;
/// NativeRayObject class
extern jclass java_native_ray_object_class;
/// Constructor of NativeRayObject class
extern jmethodID java_native_ray_object_init;
/// data field of NativeRayObject class
extern jfieldID java_native_ray_object_data;
/// metadata field of NativeRayObject class
extern jfieldID java_native_ray_object_metadata;
/// Throws a Java RayException if the status is not OK.
#define THROW_EXCEPTION_AND_RETURN_IF_NOT_OK(env, status, ret) \
{ \
if (!(status).ok()) { \
(env)->ThrowNew(java_ray_exception_class, (status).message().c_str()); \
return (ret); \
} \
}
/// Convert a Java byte array to a C++ UniqueID.
template <typename ID>
inline ID JavaByteArrayToId(JNIEnv *env, const jbyteArray &bytes) {
std::string id_str(ID::Size(), 0);
env->GetByteArrayRegion(bytes, 0, ID::Size(),
reinterpret_cast<jbyte *>(&id_str.front()));
return ID::FromBinary(id_str);
}
/// Convert C++ UniqueID to a Java byte array.
template <typename ID>
inline jbyteArray IdToJavaByteArray(JNIEnv *env, const ID &id) {
jbyteArray array = env->NewByteArray(ID::Size());
env->SetByteArrayRegion(array, 0, ID::Size(),
reinterpret_cast<const jbyte *>(id.Data()));
return array;
}
/// Convert C++ UniqueID to a Java ByteBuffer.
template <typename ID>
inline jobject IdToJavaByteBuffer(JNIEnv *env, const ID &id) {
return env->NewDirectByteBuffer(
reinterpret_cast<void *>(const_cast<uint8_t *>(id.Data())), id.Size());
}
/// Convert a Java String to C++ std::string.
inline std::string JavaStringToNativeString(JNIEnv *env, jstring jstr) {
const char *c_str = env->GetStringUTFChars(jstr, nullptr);
std::string result(c_str);
env->ReleaseStringUTFChars(static_cast<jstring>(jstr), c_str);
return result;
}
/// Convert a Java List to C++ std::vector.
template <typename NativeT>
inline void JavaListToNativeVector(
JNIEnv *env, jobject java_list, std::vector<NativeT> *native_vector,
std::function<NativeT(JNIEnv *, jobject)> element_converter) {
int size = env->CallIntMethod(java_list, java_list_size);
native_vector->clear();
for (int i = 0; i < size; i++) {
native_vector->emplace_back(
element_converter(env, env->CallObjectMethod(java_list, java_list_get, (jint)i)));
}
}
/// Convert a C++ std::vector to a Java List.
template <typename NativeT>
inline jobject NativeVectorToJavaList(
JNIEnv *env, const std::vector<NativeT> &native_vector,
std::function<jobject(JNIEnv *, const NativeT &)> element_converter) {
jobject java_list =
env->NewObject(java_array_list_class, java_array_list_init_with_capacity,
(jint)native_vector.size());
for (const auto &item : native_vector) {
env->CallVoidMethod(java_list, java_list_add, element_converter(env, item));
}
return java_list;
}
/// Convert a C++ ray::Buffer to a Java byte array.
inline jbyteArray NativeBufferToJavaByteArray(JNIEnv *env,
const std::shared_ptr<ray::Buffer> buffer) {
if (!buffer) {
return nullptr;
}
jbyteArray java_byte_array = env->NewByteArray(buffer->Size());
if (buffer->Size() > 0) {
env->SetByteArrayRegion(java_byte_array, 0, buffer->Size(),
reinterpret_cast<const jbyte *>(buffer->Data()));
}
return java_byte_array;
}
/// A helper method to help access a Java NativeRayObject instance and ensure memory
/// safety.
///
/// \param[in] java_obj The Java NativeRayObject object.
/// \param[in] reader The callback function to access a C++ ray::RayObject instance.
/// \return The return value of callback function.
template <typename ReturnT>
inline ReturnT ReadJavaNativeRayObject(
JNIEnv *env, const jobject &java_obj,
std::function<ReturnT(const std::shared_ptr<ray::RayObject> &)> reader) {
if (!java_obj) {
return reader(nullptr);
}
auto java_data = (jbyteArray)env->GetObjectField(java_obj, java_native_ray_object_data);
auto java_metadata =
(jbyteArray)env->GetObjectField(java_obj, java_native_ray_object_metadata);
auto data_size = env->GetArrayLength(java_data);
jbyte *data = data_size > 0 ? env->GetByteArrayElements(java_data, nullptr) : nullptr;
auto metadata_size = java_metadata ? env->GetArrayLength(java_metadata) : 0;
jbyte *metadata =
metadata_size > 0 ? env->GetByteArrayElements(java_metadata, nullptr) : nullptr;
auto data_buffer = std::make_shared<ray::LocalMemoryBuffer>(
reinterpret_cast<uint8_t *>(data), data_size);
auto metadata_buffer = java_metadata
? std::make_shared<ray::LocalMemoryBuffer>(
reinterpret_cast<uint8_t *>(metadata), metadata_size)
: nullptr;
auto native_obj = std::make_shared<ray::RayObject>(data_buffer, metadata_buffer);
auto result = reader(native_obj);
if (data) {
env->ReleaseByteArrayElements(java_data, data, JNI_ABORT);
}
if (metadata) {
env->ReleaseByteArrayElements(java_metadata, metadata, JNI_ABORT);
}
return result;
}
/// Convert a C++ ray::RayObject to a Java NativeRayObject.
inline jobject ToJavaNativeRayObject(JNIEnv *env,
const std::shared_ptr<ray::RayObject> &rayObject) {
if (!rayObject) {
return nullptr;
}
auto java_data = NativeBufferToJavaByteArray(env, rayObject->GetData());
auto java_metadata = NativeBufferToJavaByteArray(env, rayObject->GetMetadata());
auto java_obj = env->NewObject(java_native_ray_object_class,
java_native_ray_object_init, java_data, java_metadata);
return java_obj;
}
#endif // RAY_COMMON_JAVA_JNI_HELPER_H
| 38.055249 | 90 | 0.683943 | [
"object",
"vector"
] |
d0f5cf7fb47057ced18c6cedee58ea23108a96f3 | 11,226 | h | C | Matlab-code/SelfExSR/external/imrender/vgg/trw-s/typePotts.h | echowjm/Personal-Summarize | 9896d13ce151126c6e42f761b78905d8dd76dd56 | [
"Apache-2.0"
] | 70 | 2018-09-07T05:51:31.000Z | 2022-03-21T08:48:38.000Z | Matlab-code/SelfExSR/external/imrender/vgg/trw-s/typePotts.h | echowjm/Personal-Summarize | 9896d13ce151126c6e42f761b78905d8dd76dd56 | [
"Apache-2.0"
] | 6 | 2019-02-11T05:25:34.000Z | 2020-09-17T12:31:52.000Z | Matlab-code/SelfExSR/external/imrender/vgg/trw-s/typePotts.h | echowjm/Personal-Summarize | 9896d13ce151126c6e42f761b78905d8dd76dd56 | [
"Apache-2.0"
] | 28 | 2018-10-12T12:28:19.000Z | 2021-12-11T09:41:30.000Z | /******************************************************************
typePotts.h
Energy function with Potts interactions:
E(x) = \sum_i D_i(x_i) + \sum_ij V_ij(x_i,x_j)
where x_i \in {0, 1, ..., K-1},
V_ij(ki, kj) = 0 if ki==kj, and lambda_ij otherwise.
lambda_ij must be non-negative.
Example usage:
Minimize function E(x,y) = Dx(x) + Dy(y) + lambda*[x != y] where
x,y \in {0,1,2},
Dx(0) = 0, Dx(1) = 1, Dx(2) = 2,
Dy(0) = 3, Dy(1) = 4, Dy(2) = 5,
lambda = 6,
[.] is 1 if it's argument is true, and 0 otherwise.
#include <stdio.h>
#include "MRFEnergy.h"
void testPotts()
{
MRFEnergy<TypePotts>* mrf;
MRFEnergy<TypePotts>::NodeId* nodes;
MRFEnergy<TypePotts>::Options options;
TypePotts::REAL energy, lowerBound;
const int nodeNum = 2; // number of nodes
const int K = 3; // number of labels
TypePotts::REAL D[K];
int x, y;
mrf = new MRFEnergy<TypePotts>(TypePotts::GlobalSize(K));
nodes = new MRFEnergy<TypePotts>::NodeId[nodeNum];
// construct energy
D[0] = 0; D[1] = 1; D[2] = 2;
nodes[0] = mrf->AddNode(TypePotts::LocalSize(), TypePotts::NodeData(D));
D[0] = 3; D[1] = 4; D[2] = 5;
nodes[1] = mrf->AddNode(TypePotts::LocalSize(), TypePotts::NodeData(D));
mrf->AddEdge(nodes[0], nodes[1], TypePotts::EdgeData(6));
// Function below is optional - it may help if, for example, nodes are added in a random order
// mrf->SetAutomaticOrdering();
/////////////////////// TRW-S algorithm //////////////////////
options.m_iterMax = 30; // maximum number of iterations
mrf->Minimize_TRW_S(options, lowerBound, energy);
// read solution
x = mrf->GetSolution(nodes[0]);
y = mrf->GetSolution(nodes[1]);
printf("Solution: %d %d\n", x, y);
//////////////////////// BP algorithm ////////////////////////
mrf->ZeroMessages(); // in general not necessary - it may be faster to start
// with messages computed in previous iterations
options.m_iterMax = 30; // maximum number of iterations
mrf->Minimize_BP(options, energy);
// read solution
x = mrf->GetSolution(nodes[0]);
y = mrf->GetSolution(nodes[1]);
printf("Solution: %d %d\n", x, y);
// done
delete nodes;
delete mrf;
}
*******************************************************************/
#ifndef __TYPEPOTTS_H__
#define __TYPEPOTTS_H__
#include <string.h>
#include <assert.h>
template <class T> class MRFEnergy;
class TypePotts
{
public:
// types declarations
struct Edge; // stores edge information and either forward or backward message
struct Vector; // node parameters and messages
typedef int Label;
typedef double REAL;
struct GlobalSize; // global information about number of labels
struct LocalSize; // local information about number of labels (stored at each node)
struct NodeData; // argument to MRFEnergy::AddNode()
struct EdgeData; // argument to MRFEnergy::AddEdge()
struct GlobalSize
{
GlobalSize(int K);
private:
friend struct Vector;
friend struct Edge;
int m_K; // number of labels
};
struct LocalSize // number of labels is stored at MRFEnergy::m_Kglobal
{
};
struct NodeData
{
NodeData(REAL* data); // data = pointer to array of size MRFEnergy::m_Kglobal
private:
friend struct Vector;
friend struct Edge;
REAL* m_data;
};
struct EdgeData
{
EdgeData(REAL lambdaPotts);
private:
friend struct Vector;
friend struct Edge;
REAL m_lambdaPotts;
};
//////////////////////////////////////////////////////////////////////////////////
////////////////////////// Visible only to MRFEnergy /////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
friend class MRFEnergy<TypePotts>;
struct Vector
{
static int GetSizeInBytes(GlobalSize Kglobal, LocalSize K); // returns -1 if invalid K's
void Initialize(GlobalSize Kglobal, LocalSize K, NodeData data); // called once when user adds a node
void Add(GlobalSize Kglobal, LocalSize K, NodeData data); // called once when user calls MRFEnergy::AddNodeData()
void SetZero(GlobalSize Kglobal, LocalSize K); // set this[k] = 0
void Copy(GlobalSize Kglobal, LocalSize K, Vector* V); // set this[k] = V[k]
void Add(GlobalSize Kglobal, LocalSize K, Vector* V); // set this[k] = this[k] + V[k]
REAL GetValue(GlobalSize Kglobal, LocalSize K, Label k); // return this[k]
REAL ComputeMin(GlobalSize Kglobal, LocalSize K, Label& kMin); // return vMin = min_k { this[k] }, set kMin
REAL ComputeAndSubtractMin(GlobalSize Kglobal, LocalSize K); // same as previous, but additionally set this[k] -= vMin (and kMin is not returned)
private:
friend struct Edge;
REAL m_data[1]; // actual size is MRFEnergy::m_Kglobal
};
struct Edge
{
static int GetSizeInBytes(GlobalSize Kglobal, LocalSize Ki, LocalSize Kj, EdgeData data); // returns -1 if invalid data
static int GetBufSizeInBytes(int vectorMaxSizeInBytes); // returns size of buffer need for UpdateMessage()
void Initialize(GlobalSize Kglobal, LocalSize Ki, LocalSize Kj, EdgeData data, Vector* Di, Vector* Dj); // called once when user adds an edge
Vector* GetMessagePtr();
void Swap(GlobalSize Kglobal, LocalSize Ki, LocalSize Kj); // if the client calls this function, then the meaning of 'dir'
// in distance transform functions is swapped
// When UpdateMessage() is called, edge contains message from dest to source.
// The function must replace it with the message from source to dest.
// The update rule is given below assuming that source corresponds to tail (i) and dest corresponds
// to head (j) (which is the case if dir==0).
//
// 1. Compute Di[ki] = gamma*source[ki] - message[ki]. (Note: message = message from j to i).
// 2. Compute distance transform: set
// message[kj] = min_{ki} (Di[ki] + V(ki,kj)). (Note: message = message from i to j).
// 3. Compute vMin = min_{kj} m_message[kj].
// 4. Set m_message[kj] -= vMin.
// 5. Return vMin.
//
// If dir==1 then source corresponds to j, sink corresponds to i. Then the update rule is
//
// 1. Compute Dj[kj] = gamma*source[kj] - message[kj]. (Note: message = message from i to j).
// 2. Compute distance transform: set
// message[ki] = min_{kj} (Dj[kj] + V(ki,kj)). (Note: message = message from j to i).
// 3. Compute vMin = min_{ki} m_message[ki].
// 4. Set m_message[ki] -= vMin.
// 5. Return vMin.
//
// If Edge::Swap has been called odd number of times, then the meaning of dir is swapped.
//
// Vector 'source' must not be modified. Function may use 'buf' as a temporary storage.
REAL UpdateMessage(GlobalSize Kglobal, LocalSize Ksource, LocalSize Kdest, Vector* source, REAL gamma, int dir, void* buf);
// If dir==0, then sets dest[kj] += V(ksource,kj).
// If dir==1, then sets dest[ki] += V(ki,ksource).
// If Swap() has been called odd number of times, then the meaning of dir is swapped.
void AddColumn(GlobalSize Kglobal, LocalSize Ksource, LocalSize Kdest, Label ksource, Vector* dest, int dir);
private:
// edge information
REAL m_lambdaPotts;
// message
Vector m_message;
};
};
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Implementation ///////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
inline TypePotts::GlobalSize::GlobalSize(int K)
{
m_K = K;
}
///////////////////// NodeData and EdgeData ///////////////////////
inline TypePotts::NodeData::NodeData(REAL* data)
{
m_data = data;
}
inline TypePotts::EdgeData::EdgeData(REAL lambdaPotts)
{
m_lambdaPotts = lambdaPotts;
}
///////////////////// Vector ///////////////////////
inline int TypePotts::Vector::GetSizeInBytes(GlobalSize Kglobal, LocalSize K)
{
if (Kglobal.m_K < 1)
{
return -1;
}
return Kglobal.m_K*sizeof(REAL);
}
inline void TypePotts::Vector::Initialize(GlobalSize Kglobal, LocalSize K, NodeData data)
{
memcpy(m_data, data.m_data, Kglobal.m_K*sizeof(REAL));
}
inline void TypePotts::Vector::Add(GlobalSize Kglobal, LocalSize K, NodeData data)
{
for (int k=0; k<Kglobal.m_K; k++)
{
m_data[k] += data.m_data[k];
}
}
inline void TypePotts::Vector::SetZero(GlobalSize Kglobal, LocalSize K)
{
memset(m_data, 0, Kglobal.m_K*sizeof(REAL));
}
inline void TypePotts::Vector::Copy(GlobalSize Kglobal, LocalSize K, Vector* V)
{
memcpy(m_data, V->m_data, Kglobal.m_K*sizeof(REAL));
}
inline void TypePotts::Vector::Add(GlobalSize Kglobal, LocalSize K, Vector* V)
{
for (int k=0; k<Kglobal.m_K; k++)
{
m_data[k] += V->m_data[k];
}
}
inline TypePotts::REAL TypePotts::Vector::GetValue(GlobalSize Kglobal, LocalSize K, Label k)
{
assert(k>=0 && k<Kglobal.m_K);
return m_data[k];
}
inline TypePotts::REAL TypePotts::Vector::ComputeMin(GlobalSize Kglobal, LocalSize K, Label& kMin)
{
REAL vMin = m_data[0];
kMin = 0;
for (int k=1; k<Kglobal.m_K; k++)
{
if (vMin > m_data[k])
{
vMin = m_data[k];
kMin = k;
}
}
return vMin;
}
inline TypePotts::REAL TypePotts::Vector::ComputeAndSubtractMin(GlobalSize Kglobal, LocalSize K)
{
REAL vMin = m_data[0];
for (int k=1; k<Kglobal.m_K; k++)
{
if (vMin > m_data[k])
{
vMin = m_data[k];
}
}
for (int k=0; k<Kglobal.m_K; k++)
{
m_data[k] -= vMin;
}
return vMin;
}
///////////////////// EdgeDataAndMessage implementation /////////////////////////
inline int TypePotts::Edge::GetSizeInBytes(GlobalSize Kglobal, LocalSize Ki, LocalSize Kj, EdgeData data)
{
if (data.m_lambdaPotts < 0)
{
return -1;
}
return sizeof(Edge) - sizeof(Vector) + Kglobal.m_K*sizeof(REAL);
}
inline int TypePotts::Edge::GetBufSizeInBytes(int vectorMaxSizeInBytes)
{
return 0;
}
inline void TypePotts::Edge::Initialize(GlobalSize Kglobal, LocalSize Ki, LocalSize Kj, EdgeData data, Vector* Di, Vector* Dj)
{
m_lambdaPotts = data.m_lambdaPotts;
}
inline TypePotts::Vector* TypePotts::Edge::GetMessagePtr()
{
return &m_message;
}
inline void TypePotts::Edge::Swap(GlobalSize Kglobal, LocalSize Ki, LocalSize Kj)
{
}
inline TypePotts::REAL TypePotts::Edge::UpdateMessage(GlobalSize Kglobal, LocalSize Ksource, LocalSize Kdest, Vector* source, REAL gamma, int dir, void* buf)
{
int k;
REAL vMin;
m_message.m_data[0] = gamma*source->m_data[0] - m_message.m_data[0];
vMin = m_message.m_data[0];
for (k=1; k<Kglobal.m_K; k++)
{
m_message.m_data[k] = gamma*source->m_data[k] - m_message.m_data[k];
if (vMin > m_message.m_data[k])
{
vMin = m_message.m_data[k];
}
}
for (k=0; k<Kglobal.m_K; k++)
{
m_message.m_data[k] -= vMin;
if (m_message.m_data[k] > m_lambdaPotts)
{
m_message.m_data[k] = m_lambdaPotts;
}
}
return vMin;
}
inline void TypePotts::Edge::AddColumn(GlobalSize Kglobal, LocalSize Ksource, LocalSize Kdest, Label ksource, Vector* dest, int dir)
{
assert(ksource>=0 && ksource<Kglobal.m_K);
int k;
for (k=0; k<ksource; k++)
{
dest->m_data[k] += m_lambdaPotts;
}
for (k++; k<Kglobal.m_K; k++)
{
dest->m_data[k] += m_lambdaPotts;
}
}
//////////////////////////////////////////////////////////////////////////////////
#endif
| 26.920863 | 160 | 0.621058 | [
"vector",
"transform"
] |
d0fb19dd128f188a9294499893fee7a4ed120d3f | 7,636 | h | C | table/mock_table.h | royguo/terarkdb | e68146930e813eee2332e02adc514867f859123a | [
"Apache-2.0",
"BSD-3-Clause"
] | 1,658 | 2020-12-21T04:53:44.000Z | 2022-03-30T16:16:07.000Z | table/mock_table.h | royguo/terarkdb | e68146930e813eee2332e02adc514867f859123a | [
"Apache-2.0",
"BSD-3-Clause"
] | 105 | 2020-12-21T09:09:55.000Z | 2022-03-28T09:57:36.000Z | table/mock_table.h | weilewei/terarkdb | 6e0eeaae853f6746b80e93e8ae4c9d8e95b8467a | [
"Apache-2.0",
"BSD-3-Clause"
] | 151 | 2020-12-21T09:25:34.000Z | 2022-03-13T08:58:37.000Z | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#pragma once
#include <db/version_edit.h>
#include <algorithm>
#include <atomic>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "port/port.h"
#include "rocksdb/comparator.h"
#include "rocksdb/table.h"
#include "rocksdb/terark_namespace.h"
#include "table/internal_iterator.h"
#include "table/table_builder.h"
#include "table/table_reader.h"
#include "util/kv_map.h"
#include "util/mutexlock.h"
#include "util/testharness.h"
#include "util/testutil.h"
namespace TERARKDB_NAMESPACE {
namespace mock {
stl_wrappers::KVMap MakeMockFile(
std::initializer_list<std::pair<const std::string, std::string>> l = {});
struct MockTableFileSystem {
port::Mutex mutex;
struct FileData {
stl_wrappers::KVMap table;
stl_wrappers::KVMap tombstone;
std::shared_ptr<const TableProperties> prop;
};
std::map<uint32_t, FileData> files;
};
class MockTableReader : public TableReader {
public:
MockTableReader(const MockTableFileSystem::FileData& file_data)
: file_data_(file_data) {}
InternalIterator* NewIterator(const ReadOptions&,
const SliceTransform* prefix_extractor,
Arena* arena = nullptr,
bool skip_filters = false,
bool for_compaction = false) override;
Status Get(const ReadOptions& readOptions, const Slice& key,
GetContext* get_context, const SliceTransform* prefix_extractor,
bool skip_filters = false) override;
uint64_t ApproximateOffsetOf(const Slice& /*key*/) override { return 0; }
virtual size_t ApproximateMemoryUsage() const override { return 0; }
uint64_t FileNumber() const override { return uint64_t(-1); }
void SetupForCompaction() override {}
std::shared_ptr<const TableProperties> GetTableProperties() const override;
FragmentedRangeTombstoneIterator* NewRangeTombstoneIterator(
const ReadOptions& /*read_options*/) override;
~MockTableReader() {}
private:
const MockTableFileSystem::FileData& file_data_;
};
template <class ValueType>
class MockTableIterator : public InternalIteratorBase<ValueType> {
public:
explicit MockTableIterator(const stl_wrappers::KVMap& table) : table_(table) {
itr_ = table_.end();
}
bool Valid() const override { return itr_ != table_.end(); }
void SeekToFirst() override { itr_ = table_.begin(); }
void SeekToLast() override {
itr_ = table_.end();
Prev();
}
void Seek(const Slice& target) override {
std::string str_target(target.data(), target.size());
itr_ = table_.lower_bound(str_target);
}
void SeekForPrev(const Slice& target) override {
std::string str_target(target.data(), target.size());
itr_ = table_.upper_bound(str_target);
Prev();
}
void Next() override { ++itr_; }
void Prev() override {
if (itr_ == table_.begin()) {
itr_ = table_.end();
} else {
--itr_;
}
}
Slice key() const override { return Slice(itr_->first); }
ValueType value() const override { return ValueType(itr_->second); }
Status status() const override { return Status::OK(); }
private:
const stl_wrappers::KVMap& table_;
stl_wrappers::KVMap::const_iterator itr_;
};
class MockTableBuilder : public TableBuilder {
public:
MockTableBuilder(uint32_t id, MockTableFileSystem* file_system)
: id_(id), file_system_(file_system) {
file_data_.table = MakeMockFile({});
file_data_.tombstone = MakeMockFile({});
}
// REQUIRES: Either Finish() or Abandon() has been called.
~MockTableBuilder() {}
Status AddToTable(const Slice& key, const LazyBuffer& value,
stl_wrappers::KVMap& table) {
auto s = value.fetch();
if (!s.ok()) {
return s;
}
table.insert({key.ToString(), value.ToString()});
return Status::OK();
}
// Add key,value to the table being constructed.
// REQUIRES: key is after any previously added key according to comparator.
// REQUIRES: Finish(), Abandon() have not been called
Status Add(const Slice& key, const LazyBuffer& value) override {
return AddToTable(key, value, file_data_.table);
}
Status AddTombstone(const Slice& key, const LazyBuffer& value) override {
return AddToTable(key, value, file_data_.tombstone);
}
Status Finish(const TablePropertyCache* prop, const std::vector<uint64_t>*,
const std::vector<uint64_t>* inheritance_tree) override {
prop_.num_entries = file_data_.table.size();
prop_.raw_key_size = file_data_.table.size();
prop_.raw_value_size = file_data_.table.size();
if (prop != nullptr) {
prop_.purpose = prop->purpose;
prop_.max_read_amp = prop->max_read_amp;
prop_.read_amp = prop->read_amp;
prop_.dependence = prop->dependence;
}
if (inheritance_tree != nullptr) {
prop_.inheritance_tree = *inheritance_tree;
}
file_data_.prop = std::make_shared<const TableProperties>(prop_);
MutexLock lock_guard(&file_system_->mutex);
file_system_->files.emplace(id_, file_data_);
return Status::OK();
}
void Abandon() override {}
uint64_t NumEntries() const override {
return file_data_.table.size() + file_data_.tombstone.size();
}
uint64_t FileSize() const override {
return file_data_.table.size() + file_data_.tombstone.size();
}
TableProperties GetTableProperties() const override { return prop_; }
private:
uint32_t id_;
MockTableFileSystem* file_system_;
MockTableFileSystem::FileData file_data_;
TableProperties prop_;
};
class MockTableFactory : public TableFactory {
public:
MockTableFactory();
const char* Name() const override { return "MockTable"; }
Status NewTableReader(
const TableReaderOptions& table_reader_options,
std::unique_ptr<RandomAccessFileReader>&& file, uint64_t file_size,
std::unique_ptr<TableReader>* table_reader,
bool prefetch_index_and_filter_in_cache = true) const override;
TableBuilder* NewTableBuilder(
const TableBuilderOptions& table_builder_options,
uint32_t column_familly_id, WritableFileWriter* file) const override;
// This function will directly create mock table instead of going through
// MockTableBuilder. file_contents has to have a format of <internal_key,
// value>. Those key-value pairs will then be inserted into the mock table.
Status CreateMockTable(Env* env, const std::string& fname,
stl_wrappers::KVMap file_contents);
virtual Status SanitizeOptions(
const DBOptions& /*db_opts*/,
const ColumnFamilyOptions& /*cf_opts*/) const override {
return Status::OK();
}
virtual std::string GetPrintableTableOptions() const override {
return std::string();
}
// This function will assert that only a single file exists and that the
// contents are equal to file_contents
void AssertSingleFile(const stl_wrappers::KVMap& file_contents,
const stl_wrappers::KVMap& range_deletions);
void AssertLatestFile(const stl_wrappers::KVMap& file_contents);
private:
uint32_t GetAndWriteNextID(WritableFileWriter* file) const;
uint32_t GetIDFromFile(RandomAccessFileReader* file) const;
mutable MockTableFileSystem file_system_;
mutable std::atomic<uint32_t> next_id_;
};
} // namespace mock
} // namespace TERARKDB_NAMESPACE
| 31.423868 | 80 | 0.700891 | [
"vector"
] |
19022c082aaef6d315ce0c746a44cfedbbb74ceb | 17,935 | c | C | third_party/gst-plugins-good/ext/jack/gstjackaudioclient.c | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 6 | 2020-09-22T18:07:15.000Z | 2021-10-21T01:34:04.000Z | third_party/gst-plugins-good/ext/jack/gstjackaudioclient.c | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 2 | 2020-11-10T13:17:39.000Z | 2022-03-30T11:22:14.000Z | third_party/gst-plugins-good/ext/jack/gstjackaudioclient.c | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 3 | 2020-09-26T08:40:35.000Z | 2021-10-21T01:33:56.000Z | /* GStreamer
* Copyright (C) 2006 Wim Taymans <wim@fluendo.com>
*
* gstjackaudioclient.c: jack audio client implementation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <string.h>
#include "gstjackaudioclient.h"
#include "gstjack.h"
#include <gst/glib-compat-private.h>
GST_DEBUG_CATEGORY_STATIC (gst_jack_audio_client_debug);
#define GST_CAT_DEFAULT gst_jack_audio_client_debug
static void
jack_log_error (const gchar * msg)
{
GST_ERROR ("%s", msg);
}
static void
jack_info_error (const gchar * msg)
{
GST_INFO ("%s", msg);
}
void
gst_jack_audio_client_init (void)
{
GST_DEBUG_CATEGORY_INIT (gst_jack_audio_client_debug, "jackclient", 0,
"jackclient helpers");
jack_set_error_function (jack_log_error);
jack_set_info_function (jack_info_error);
}
/* a list of global connections indexed by id and server. */
G_LOCK_DEFINE_STATIC (connections_lock);
static GList *connections;
/* the connection to a server */
typedef struct
{
gint refcount;
GMutex lock;
GCond flush_cond;
/* id/server pair and the connection */
gchar *id;
gchar *server;
jack_client_t *client;
/* lists of GstJackAudioClients */
gint n_clients;
GList *src_clients;
GList *sink_clients;
/* transport state handling */
gint cur_ts;
GstState transport_state;
} GstJackAudioConnection;
/* an object sharing a jack_client_t connection. */
struct _GstJackAudioClient
{
GstJackAudioConnection *conn;
GstJackClientType type;
gboolean active;
gboolean deactivate;
gboolean server_down;
JackShutdownCallback shutdown;
JackProcessCallback process;
JackBufferSizeCallback buffer_size;
JackSampleRateCallback sample_rate;
gpointer user_data;
};
typedef struct
{
jack_nframes_t nframes;
gpointer user_data;
} JackCB;
static gboolean
jack_handle_transport_change (GstJackAudioClient * client, GstState state)
{
GstObject *obj = GST_OBJECT_PARENT (client->user_data);
guint mode;
g_object_get (obj, "transport", &mode, NULL);
if ((mode & GST_JACK_TRANSPORT_SLAVE) && (GST_STATE (obj) != state)) {
GST_INFO_OBJECT (obj, "requesting state change: %s",
gst_element_state_get_name (state));
gst_element_post_message (GST_ELEMENT (obj),
gst_message_new_request_state (obj, state));
return TRUE;
}
return FALSE;
}
static int
jack_process_cb (jack_nframes_t nframes, void *arg)
{
GstJackAudioConnection *conn = (GstJackAudioConnection *) arg;
GList *walk;
int res = 0;
jack_transport_state_t ts = jack_transport_query (conn->client, NULL);
if (ts != conn->cur_ts) {
conn->cur_ts = ts;
switch (ts) {
case JackTransportStopped:
GST_DEBUG ("transport state is 'stopped'");
conn->transport_state = GST_STATE_PAUSED;
break;
case JackTransportStarting:
GST_DEBUG ("transport state is 'starting'");
conn->transport_state = GST_STATE_READY;
break;
case JackTransportRolling:
GST_DEBUG ("transport state is 'rolling'");
conn->transport_state = GST_STATE_PLAYING;
break;
default:
break;
}
GST_DEBUG ("num of clients: src=%d, sink=%d",
g_list_length (conn->src_clients), g_list_length (conn->sink_clients));
}
g_mutex_lock (&conn->lock);
/* call sources first, then sinks. Sources will either push data into the
* ringbuffer of the sinks, which will then pull the data out of it, or
* sinks will pull the data from the sources. */
for (walk = conn->src_clients; walk; walk = g_list_next (walk)) {
GstJackAudioClient *client = (GstJackAudioClient *) walk->data;
/* only call active clients */
if ((client->active || client->deactivate) && client->process) {
res = client->process (nframes, client->user_data);
if (client->deactivate) {
client->deactivate = FALSE;
g_cond_signal (&conn->flush_cond);
}
}
}
for (walk = conn->sink_clients; walk; walk = g_list_next (walk)) {
GstJackAudioClient *client = (GstJackAudioClient *) walk->data;
/* only call active clients */
if ((client->active || client->deactivate) && client->process) {
res = client->process (nframes, client->user_data);
if (client->deactivate) {
client->deactivate = FALSE;
g_cond_signal (&conn->flush_cond);
}
}
}
/* handle transport state requisition, do sinks first, stop after the first
* element that handled it */
if (conn->transport_state != GST_STATE_VOID_PENDING) {
for (walk = conn->sink_clients; walk; walk = g_list_next (walk)) {
if (jack_handle_transport_change ((GstJackAudioClient *) walk->data,
conn->transport_state)) {
conn->transport_state = GST_STATE_VOID_PENDING;
break;
}
}
}
if (conn->transport_state != GST_STATE_VOID_PENDING) {
for (walk = conn->src_clients; walk; walk = g_list_next (walk)) {
if (jack_handle_transport_change ((GstJackAudioClient *) walk->data,
conn->transport_state)) {
conn->transport_state = GST_STATE_VOID_PENDING;
break;
}
}
}
g_mutex_unlock (&conn->lock);
return res;
}
static void
jack_shutdown_cb (void *arg)
{
GstJackAudioConnection *conn = (GstJackAudioConnection *) arg;
GList *walk;
GST_DEBUG ("disconnect client %s from server %s", conn->id,
GST_STR_NULL (conn->server));
g_mutex_lock (&conn->lock);
for (walk = conn->src_clients; walk; walk = g_list_next (walk)) {
GstJackAudioClient *client = (GstJackAudioClient *) walk->data;
client->server_down = TRUE;
g_cond_signal (&conn->flush_cond);
if (client->shutdown)
client->shutdown (client->user_data);
}
for (walk = conn->sink_clients; walk; walk = g_list_next (walk)) {
GstJackAudioClient *client = (GstJackAudioClient *) walk->data;
client->server_down = TRUE;
g_cond_signal (&conn->flush_cond);
if (client->shutdown)
client->shutdown (client->user_data);
}
g_mutex_unlock (&conn->lock);
}
/* we error out */
static int
jack_sample_rate_cb (jack_nframes_t nframes, void *arg)
{
jack_shutdown_cb (arg);
return 0;
}
/* we error out */
static int
jack_buffer_size_cb (jack_nframes_t nframes, void *arg)
{
jack_shutdown_cb (arg);
return 0;
}
typedef struct
{
const gchar *id;
const gchar *server;
} FindData;
static gint
connection_find (GstJackAudioConnection * conn, FindData * data)
{
/* id's must match */
if (strcmp (conn->id, data->id))
return 1;
/* both the same or NULL */
if (conn->server == data->server)
return 0;
/* we cannot compare NULL */
if (conn->server == NULL || data->server == NULL)
return 1;
if (strcmp (conn->server, data->server))
return 1;
return 0;
}
/* make a connection with @id and @server. Returns NULL on failure with the
* status set. */
static GstJackAudioConnection *
gst_jack_audio_make_connection (const gchar * id, const gchar * server,
jack_client_t * jclient, jack_status_t * status)
{
GstJackAudioConnection *conn;
jack_options_t options;
gint res;
*status = 0;
GST_DEBUG ("new client %s, connecting to server %s", id,
GST_STR_NULL (server));
/* never start a server */
options = JackNoStartServer;
/* if we have a servername, use it */
if (server != NULL)
options |= JackServerName;
/* open the client */
if (jclient == NULL)
jclient = jack_client_open (id, options, status, server);
if (jclient == NULL)
goto could_not_open;
/* now create object */
conn = g_new (GstJackAudioConnection, 1);
conn->refcount = 1;
g_mutex_init (&conn->lock);
g_cond_init (&conn->flush_cond);
conn->id = g_strdup (id);
conn->server = g_strdup (server);
conn->client = jclient;
conn->n_clients = 0;
conn->src_clients = NULL;
conn->sink_clients = NULL;
conn->cur_ts = -1;
conn->transport_state = GST_STATE_VOID_PENDING;
/* set our callbacks */
jack_set_process_callback (jclient, jack_process_cb, conn);
/* these callbacks cause us to error */
jack_set_buffer_size_callback (jclient, jack_buffer_size_cb, conn);
jack_set_sample_rate_callback (jclient, jack_sample_rate_cb, conn);
jack_on_shutdown (jclient, jack_shutdown_cb, conn);
/* all callbacks are set, activate the client */
GST_INFO ("activate jack_client %p", jclient);
if ((res = jack_activate (jclient)))
goto could_not_activate;
GST_DEBUG ("opened connection %p", conn);
return conn;
/* ERRORS */
could_not_open:
{
GST_DEBUG ("failed to open jack client, %d", *status);
return NULL;
}
could_not_activate:
{
GST_ERROR ("Could not activate client (%d)", res);
*status = JackFailure;
g_mutex_clear (&conn->lock);
g_free (conn->id);
g_free (conn->server);
g_free (conn);
return NULL;
}
}
static GstJackAudioConnection *
gst_jack_audio_get_connection (const gchar * id, const gchar * server,
jack_client_t * jclient, jack_status_t * status)
{
GstJackAudioConnection *conn;
GList *found;
FindData data;
GST_DEBUG ("getting connection for id %s, server %s", id,
GST_STR_NULL (server));
data.id = id;
data.server = server;
G_LOCK (connections_lock);
found =
g_list_find_custom (connections, &data, (GCompareFunc) connection_find);
if (found != NULL && jclient != NULL) {
/* we found it, increase refcount and return it */
conn = (GstJackAudioConnection *) found->data;
conn->refcount++;
GST_DEBUG ("found connection %p", conn);
} else {
/* make new connection */
conn = gst_jack_audio_make_connection (id, server, jclient, status);
if (conn != NULL) {
GST_DEBUG ("created connection %p", conn);
/* add to list on success */
connections = g_list_prepend (connections, conn);
} else {
GST_WARNING ("could not create connection");
}
}
G_UNLOCK (connections_lock);
return conn;
}
static void
gst_jack_audio_unref_connection (GstJackAudioConnection * conn)
{
gint res;
gboolean zero;
GST_DEBUG ("unref connection %p refcnt %d", conn, conn->refcount);
G_LOCK (connections_lock);
conn->refcount--;
if ((zero = (conn->refcount == 0))) {
GST_DEBUG ("closing connection %p", conn);
/* remove from list, we can release the mutex after removing the connection
* from the list because after that, nobody can access the connection anymore. */
connections = g_list_remove (connections, conn);
}
G_UNLOCK (connections_lock);
/* if we are zero, close and cleanup the connection */
if (zero) {
/* don't use conn->lock here. two reasons:
*
* 1) its not necessary: jack_deactivate() will not return until the JACK thread
* associated with this connection is cleaned up by a thread join, hence
* no more callbacks can occur or be in progress.
*
* 2) it would deadlock anyway, because jack_deactivate() will sleep
* waiting for the JACK thread, and can thus cause deadlock in
* jack_process_cb()
*/
GST_INFO ("deactivate jack_client %p", conn->client);
if ((res = jack_deactivate (conn->client))) {
/* we only warn, this means the server is probably shut down and the client
* is gone anyway. */
GST_WARNING ("Could not deactivate Jack client (%d)", res);
}
/* close connection */
if ((res = jack_client_close (conn->client))) {
/* we assume the client is gone. */
GST_WARNING ("close failed (%d)", res);
}
/* free resources */
g_mutex_clear (&conn->lock);
g_cond_clear (&conn->flush_cond);
g_free (conn->id);
g_free (conn->server);
g_free (conn);
}
}
static void
gst_jack_audio_connection_add_client (GstJackAudioConnection * conn,
GstJackAudioClient * client)
{
g_mutex_lock (&conn->lock);
switch (client->type) {
case GST_JACK_CLIENT_SOURCE:
conn->src_clients = g_list_append (conn->src_clients, client);
conn->n_clients++;
break;
case GST_JACK_CLIENT_SINK:
conn->sink_clients = g_list_append (conn->sink_clients, client);
conn->n_clients++;
break;
default:
g_warning ("trying to add unknown client type");
break;
}
g_mutex_unlock (&conn->lock);
}
static void
gst_jack_audio_connection_remove_client (GstJackAudioConnection * conn,
GstJackAudioClient * client)
{
g_mutex_lock (&conn->lock);
switch (client->type) {
case GST_JACK_CLIENT_SOURCE:
conn->src_clients = g_list_remove (conn->src_clients, client);
conn->n_clients--;
break;
case GST_JACK_CLIENT_SINK:
conn->sink_clients = g_list_remove (conn->sink_clients, client);
conn->n_clients--;
break;
default:
g_warning ("trying to remove unknown client type");
break;
}
g_mutex_unlock (&conn->lock);
}
/**
* gst_jack_audio_client_get:
* @id: the client id
* @server: the server to connect to or NULL for the default server
* @type: the client type
* @shutdown: a callback when the jack server shuts down
* @process: a callback when samples are available
* @buffer_size: a callback when the buffer_size changes
* @sample_rate: a callback when the sample_rate changes
* @user_data: user data passed to the callbacks
* @status: pointer to hold the jack status code in case of errors
*
* Get the jack client connection for @id and @server. Connections to the same
* @id and @server will receive the same physical Jack client connection and
* will therefore be scheduled in the same process callback.
*
* Returns: a #GstJackAudioClient.
*/
GstJackAudioClient *
gst_jack_audio_client_new (const gchar * id, const gchar * server,
jack_client_t * jclient, GstJackClientType type,
void (*shutdown) (void *arg), JackProcessCallback process,
JackBufferSizeCallback buffer_size, JackSampleRateCallback sample_rate,
gpointer user_data, jack_status_t * status)
{
GstJackAudioClient *client;
GstJackAudioConnection *conn;
g_return_val_if_fail (id != NULL, NULL);
g_return_val_if_fail (status != NULL, NULL);
/* first get a connection for the id/server pair */
conn = gst_jack_audio_get_connection (id, server, jclient, status);
if (conn == NULL)
goto no_connection;
GST_INFO ("new client %s", id);
/* make new client using the connection */
client = g_new (GstJackAudioClient, 1);
client->active = client->deactivate = FALSE;
client->conn = conn;
client->type = type;
client->shutdown = shutdown;
client->process = process;
client->buffer_size = buffer_size;
client->sample_rate = sample_rate;
client->user_data = user_data;
client->server_down = FALSE;
/* add the client to the connection */
gst_jack_audio_connection_add_client (conn, client);
return client;
/* ERRORS */
no_connection:
{
GST_DEBUG ("Could not get server connection (%d)", *status);
return NULL;
}
}
/**
* gst_jack_audio_client_free:
* @client: a #GstJackAudioClient
*
* Free the resources used by @client.
*/
void
gst_jack_audio_client_free (GstJackAudioClient * client)
{
GstJackAudioConnection *conn;
g_return_if_fail (client != NULL);
GST_INFO ("free client");
conn = client->conn;
/* remove from connection first so that it's not scheduled anymore after this
* call */
gst_jack_audio_connection_remove_client (conn, client);
gst_jack_audio_unref_connection (conn);
g_free (client);
}
/**
* gst_jack_audio_client_get_client:
* @client: a #GstJackAudioClient
*
* Get the jack audio client for @client. This function is used to perform
* operations on the jack server from this client.
*
* Returns: The jack audio client.
*/
jack_client_t *
gst_jack_audio_client_get_client (GstJackAudioClient * client)
{
g_return_val_if_fail (client != NULL, NULL);
/* no lock needed, the connection and the client does not change
* once the client is created. */
return client->conn->client;
}
/**
* gst_jack_audio_client_set_active:
* @client: a #GstJackAudioClient
* @active: new mode for the client
*
* Activate or deactive @client. When a client is activated it will receive
* callbacks when data should be processed.
*
* Returns: 0 if all ok.
*/
gint
gst_jack_audio_client_set_active (GstJackAudioClient * client, gboolean active)
{
g_return_val_if_fail (client != NULL, -1);
/* make sure that we are not dispatching the client */
g_mutex_lock (&client->conn->lock);
if (client->active && !active) {
/* we need to process once more to flush the port */
client->deactivate = TRUE;
/* need to wait for process_cb run once more */
while (client->deactivate && !client->server_down)
g_cond_wait (&client->conn->flush_cond, &client->conn->lock);
}
client->active = active;
g_mutex_unlock (&client->conn->lock);
return 0;
}
/**
* gst_jack_audio_client_get_transport_state:
* @client: a #GstJackAudioClient
*
* Check the current transport state. The client can use this to request a state
* change from the application.
*
* Returns: the state, %GST_STATE_VOID_PENDING for no change in the transport
* state
*/
GstState
gst_jack_audio_client_get_transport_state (GstJackAudioClient * client)
{
GstState state = client->conn->transport_state;
client->conn->transport_state = GST_STATE_VOID_PENDING;
return state;
}
| 28.111285 | 85 | 0.691107 | [
"object"
] |
1905ce5f01c002d8417ee72b01abd6d63a2f5535 | 3,844 | h | C | src/grpc/transcoding/transcoder_factory.h | JLXIA/esp | 250565bdc591aea431d3701285f033e07dfaa5d0 | [
"BSD-2-Clause"
] | 275 | 2017-07-12T17:05:22.000Z | 2022-03-27T14:25:21.000Z | src/grpc/transcoding/transcoder_factory.h | JLXIA/esp | 250565bdc591aea431d3701285f033e07dfaa5d0 | [
"BSD-2-Clause"
] | 322 | 2017-06-07T21:56:10.000Z | 2022-03-26T14:46:34.000Z | src/grpc/transcoding/transcoder_factory.h | JLXIA/esp | 250565bdc591aea431d3701285f033e07dfaa5d0 | [
"BSD-2-Clause"
] | 125 | 2017-06-07T20:51:25.000Z | 2022-03-12T15:30:12.000Z | /* Copyright (C) Extensible Service Proxy Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GRPC_TRANSCODING_TRANSODER_FACTORY_H_
#define GRPC_TRANSCODING_TRANSODER_FACTORY_H_
#include <memory>
#include "google/api/service.pb.h"
#include "google/protobuf/io/zero_copy_stream.h"
#include "google/protobuf/stubs/status.h"
#include "google/protobuf/util/json_util.h"
#include "grpc_transcoding/transcoder.h"
#include "grpc_transcoding/transcoder_input_stream.h"
#include "grpc_transcoding/type_helper.h"
#include "include/api_manager/method_call_info.h"
namespace google {
namespace api_manager {
namespace transcoding {
// Transcoder factory for a specific service config. Holds the preprocessed
// service config and creates a Transcoder per each client request using the
// following information:
// - method call information
// - RPC method info
// - request & response message types
// - request & response streaming flags
// - HTTP body field path
// - request variable bindings
// - Values for certain fields to be injected into the request message.
// - request input stream for the request JSON coming from the client,
// - response input stream for the response proto coming from the backend.
//
// EXAMPLE:
// TranscoderFactory factory(service_config);
//
// ::google::protobuf::io::ZeroCopyInputStream *request_downstream =
// CreateClientJsonRequestStream();
//
// ::google::protobuf::io::ZeroCopyInputStream *response_upstream =
// CreateBackendProtoResponseStream();
//
// unique_ptr<Transcoder> transcoder;
// status = factory.Create(request_info,
// request_downstream,
// response_upstream,
// &transcoder);
//
class TranscoderFactory {
public:
// service - The service config for which the factory is created
TranscoderFactory(
const ::google::api::Service& service_config,
const ::google::protobuf::util::JsonPrintOptions& json_print_options =
::google::protobuf::util::JsonPrintOptions());
// Creates a Transcoder object to transcode a single client request
// call_info - contains all the necessary info for setting up transcoding
// request_input - ZeroCopyInputStream that carries the JSON request coming
// from the client
// response_input - ZeroCopyInputStream that carries the proto response
// coming from the backend
// transcoder - the output Transcoder object
::google::protobuf::util::Status Create(
const MethodCallInfo& call_info,
::google::protobuf::io::ZeroCopyInputStream* request_input,
::google::grpc::transcoding::TranscoderInputStream* response_input,
std::unique_ptr<::google::grpc::transcoding::Transcoder>* transcoder);
// The resolver to convert status proto to JSON
::google::protobuf::util::TypeResolver* GetStatusResolver() {
return status_resolver_.get();
}
private:
::google::grpc::transcoding::TypeHelper type_helper_;
::google::protobuf::util::JsonPrintOptions json_print_options_;
std::unique_ptr<::google::protobuf::util::TypeResolver> status_resolver_;
};
} // namespace transcoding
} // namespace api_manager
} // namespace google
#endif // API_MANAGER_TRANSCODING_TRANSODER_FACTORY_H_
| 39.22449 | 77 | 0.726587 | [
"object"
] |
190ad64c695f0901ea7f974d394ef9f4f16aff75 | 2,509 | h | C | include/ModelLoader.h | CracklyBody/Skelan | c88aabc14ff064e325ea36896dcb0af322fbcc60 | [
"MIT"
] | 4 | 2020-06-24T20:49:44.000Z | 2020-08-07T14:29:05.000Z | include/ModelLoader.h | CracklyBody/Skelan | c88aabc14ff064e325ea36896dcb0af322fbcc60 | [
"MIT"
] | null | null | null | include/ModelLoader.h | CracklyBody/Skelan | c88aabc14ff064e325ea36896dcb0af322fbcc60 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <SOIL/stb_image_aug.h>
#include <SOIL/SOIL.h>
#include "loadshader.h"
#include "convert.h"
#include "animation.h"
#include "SMesh.h"
#include "bone.h"
#include "skeleton.h"
using namespace std;
using namespace glm;
using namespace Assimp;
class ModelLoader
{
private:
vector < Bone* > bones; //here we load bones data
vector < SMesh* > meshes; //here we load meshes data
vector < smesh::Texture > textures_loaded; //here we keep the loaded textures to optimize resources
string directory; //this is the directory where the model is kept
Skeleton* skeleton;
Importer import; //assimp`s importer
const aiScene* scene; //here assimp stores all the loaded data
vector < aiNode* > nodes; //we need this vector to store important information into bones in future. Actually in aiNode the transformation matrix of the particular bone is kept
vector < aiNodeAnim* > nodesAnim; //here the transformation animation data of the particular bone is kept
void processNode(aiNode* node); //this method is needed to fill the nodes vector above
void processNodeAnim(); //this method is needed to fill the nodesAnim vector above
void processBone(); //here we extract bones data from assimp into our format
void processMeshes(aiNode* node); //extract meshes data
SMesh* processMesh(aiMesh* mesh); //extract the single mesh data
vector < smesh::Texture > loadMaterialTextures(aiMaterial* mat, aiTextureType type, string typeName); //extract textures data
unsigned int textureFromFile(const char* path); //load textures from file
Bone* findBone(string name); //find the bone via it`s name
int findBoneId(string name); //find bone`s index in bones vector via it`s name
aiNode* findAiNode(string name); //find aiNode via it`s name
aiNodeAnim* findAiNodeAnim(string name); //find aiNodeAnim via it`s Name
public:
ModelLoader();
void loadModel(string path); //call this to load the model
void getModelData(Skeleton*& skeleton, vector < SMesh* >& meshes); //this method is used to get the loaded data and then to store it into the gameobject
~ModelLoader();
};
| 36.897059 | 181 | 0.732961 | [
"mesh",
"vector",
"model"
] |
190bbc6901efc2d7127f097b98ba7cdcfdde6c1a | 9,284 | h | C | pdb/src/pipeline/headers/sources/JoinedShuffleJoinSource.h | SeraphL/plinycompute | 7788bc2b01d83f4ff579c13441d0ba90734b54a2 | [
"Apache-2.0"
] | 3 | 2019-05-04T05:17:30.000Z | 2020-02-21T05:01:59.000Z | pdb/src/pipeline/headers/sources/JoinedShuffleJoinSource.h | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 3 | 2020-02-20T19:50:46.000Z | 2020-06-25T14:31:51.000Z | pdb/src/pipeline/headers/sources/JoinedShuffleJoinSource.h | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 5 | 2019-02-19T23:17:24.000Z | 2020-08-03T01:08:04.000Z | #pragma once
#include <ComputeSource.h>
#include <JoinPairArray.h>
namespace pdb {
template<typename LHS>
class JoinedShuffleJoinSource : public ComputeSource {
private:
// and the tuple set we return
TupleSetPtr output;
// the size of the last output
uint64_t outputSize = 0;
// the buffer we use if we generate to many records
TupleSetPtr buffer;
// number of records left in the buffer
uint64_t bufferSize = 0;
// to setup the output tuple set
TupleSetSetupMachine rhsMachine;
// the source we are going to grab the rhs tuples from
RHSShuffleJoinSourceBasePtr rhsSource;
// the attribute order of the records
std::vector<int> lhsRecordOrder;
// the left hand side maps
std::vector<Handle<JoinMap<LHS>>> lhsMaps;
// the iterators of the map
std::priority_queue<JoinMapIterator<LHS>, std::vector<JoinMapIterator<LHS>>, JoinIteratorComparator<LHS>> lhsIterators;
// pages that contain lhs side pages
std::vector<PDBPageHandle> lhsPages;
// this is the worker we are doing the processing for
uint64_t workerID = 0;
// the output columns of the tuple set
void **lhsColumns;
// the offset where the right input is going to be
int offset;
// the list of counts for matches of each of the rhs tuples. Basically if the count[3] = 99 the fourth tuple in the rhs tupleset will be repeated 99 times
std::vector<uint32_t> counts;
// list of iterators that are
std::vector<JoinMapIterator<LHS>> currIterators;
public:
JoinedShuffleJoinSource(TupleSpec &inputSchemaRHS,
TupleSpec &hashSchemaRHS,
TupleSpec &recordSchemaRHS,
const PDBAbstractPageSetPtr &lhsInputPageSet,
const std::vector<int> &lhsRecordOrder,
RHSShuffleJoinSourceBasePtr &rhsSource,
bool needToSwapLHSAndRhs,
uint64_t chunkSize,
uint64_t workerID) : lhsRecordOrder(lhsRecordOrder),
rhsMachine(inputSchemaRHS, recordSchemaRHS),
rhsSource(rhsSource),
workerID(workerID) {
PDBPageHandle page;
while((page = lhsInputPageSet->getNextPage(workerID)) != nullptr) {
// pin the page
page->repin();
// we grab the vector of hash maps
Handle<Vector<Handle<JoinMap<LHS>>>> returnVal = ((Record<Vector<Handle<JoinMap<LHS>>>> *) (page->getBytes()))->getRootObject();
// next we grab the join map we need
lhsMaps.push_back((*returnVal)[workerID]);
if(lhsMaps.back()->size() != 0) {
// insert the iterator
lhsIterators.push(lhsMaps.back()->begin());
// push the page
lhsPages.push_back(page);
}
}
// set up the output tuple and buffer
output = std::make_shared<TupleSet>();
buffer = std::make_shared<TupleSet>();
lhsColumns = new void *[lhsRecordOrder.size()];
// were the RHS and the LHS side swapped?
if (!needToSwapLHSAndRhs) {
// the right input will be put on offset-th column of the tuple set
offset = (int) lhsRecordOrder.size();
// the left input will be put at position 0
createCols<LHS>(lhsColumns, *output, 0, 0, lhsRecordOrder);
} else {
// the right input will be put at the begining of the tuple set
offset = 0;
// the left input will be put at the recordOrder.size()-th column
createCols<LHS>(lhsColumns, *output, (int) recordSchemaRHS.getAtts().size(), 0, lhsRecordOrder);
}
}
~JoinedShuffleJoinSource() override {
// unpin the pages
for_each (lhsPages.begin(), lhsPages.end(), [&](PDBPageHandle &page) { page->unpin(); });
// delete the columns
delete[] lhsColumns;
}
TupleSetPtr getNextTupleSet(const PDBTupleSetSizePolicy &policy) override {
/**
* 0. In case of failure we need to reprocess the input, copy the current stuff into the buffer
*/
// did we manage to process the input, if not move the records into the buffer
if(!policy.inputWasProcessed()) {
// merge the previous output into the buffer since we failed
TupleSet::merge(*buffer, *output);
bufferSize += outputSize;
outputSize = 0;
}
/**
* 1. We need to check if the buffer has something, if it does we need to process it.
*/
if(bufferSize != 0) {
// figure out how many records we want to grab (not more than the buffer size)
outputSize = std::min<uint64_t>(bufferSize, policy.getChunksSize());
// this one is a bit tricky basically it moves a outputSize number of records into the buffer
// by splitting on the outputSize-th position from the back of the buffer, since getting rows from the back is
// faster
TupleSet::split(*buffer, *output, bufferSize - outputSize);
bufferSize -= outputSize;
// return the output
return output;
}
// get the rhs tuple
auto rhsTuple = rhsSource->getNextTupleSet();
if(rhsTuple.first == nullptr) {
return nullptr;
}
// clear the counts from the previous call
counts.clear();
// go through the hashes
outputSize = 0;
for (auto &currHash : *rhsTuple.second) {
// clear the iterators from the previous iteration
currIterators.clear();
// get the hash and count
auto &rhsHash = currHash.first;
auto &rhsCount = currHash.second;
// at the beginning we assume that there were not matches for the rhs on the lhs side
for(int i = 0; i < rhsCount; ++i) {
counts.emplace_back(0);
}
/// 1. Figure out if there is an lhs hash equal to the rhs hash
// if the left hand side does not have any iterators just skip
if(lhsIterators.empty()) {
continue;
}
// check if the lhs hash is above the rhs hash if it is there is nothing to join, go to the next records
if(lhsIterators.top().getHash() > rhsHash) {
continue;
}
// iterate till we either find a lhs hash that is equal or greater to the rhs one, or finish
JoinMapIterator<LHS> curIterator;
size_t lhsHash{};
do {
// if we are out of iterators this means we are done, break out of this loop
if(lhsIterators.empty()) {
break;
}
// grab the current lhs hash
curIterator = lhsIterators.top();
lhsHash = curIterator.getHash();
// check if the lhs hash is above the rhs hash if it is there is nothing to join break out of this loop
if(lhsHash > rhsHash) {
break;
}
// move the iterator, and reinsert it into the queue since we either have a match or we are below the hash
lhsIterators.pop();
auto nextIterator = curIterator + 1;
if(!nextIterator.isDone()) {
lhsIterators.push(nextIterator);
}
} while (lhsHash < rhsHash);
// if we don't have a match skip this
if(lhsHash > rhsHash) {
continue;
}
// store the current iterator, since at this point it lhs and rhs have the same hash
currIterators.emplace_back(curIterator);
/// 1. Figure out if there are more iterators in the lhs that mach our rhs iterator
do {
// if we don't have stuff one iterator is enough
if(lhsIterators.empty()) {
break;
}
// check if we still have stuff to join
if(lhsIterators.top().getHash() == rhsHash) {
// update the current iterator
curIterator = lhsIterators.top();
lhsIterators.pop();
// store the current iterator
currIterators.emplace_back(curIterator);
// move the iterator
auto nextIterator = curIterator + 1;
if(!nextIterator.isDone()) {
lhsIterators.push(curIterator + 1);
}
continue;
}
// do we sill need to do stuff?
} while(lhsIterators.top().getHash() == rhsHash);
/// 2. Now for every rhs record we need to replicate every lhs record we could find
for(auto i = 0; i < rhsCount; ++i) {
// go through each iterator that has stuff in the lhs
for(auto &iterator : currIterators) {
auto it = *iterator;
auto &records = *it;
// update the counts
counts[counts.size() - rhsCount + i] += records.size();
// emit lhs records in this iterator
for (int which = 0; which < records.size(); which++) {
// do the unpack
unpack(records[which], outputSize++, 0, lhsColumns);
}
}
}
}
// truncate if we have extra
eraseEnd<LHS>(outputSize, 0, lhsColumns);
/// 3. Finally, we need to replicate the rhs records
rhsMachine.replicate(rhsTuple.first, output, counts, offset);
/// 4. if we have more than the chunks size buffer the extra rows
if(outputSize > policy.getChunksSize()) {
TupleSet::split(*output, *buffer, policy.getChunksSize());
bufferSize = outputSize - policy.getChunksSize();
outputSize = policy.getChunksSize();
}
return output;
}
};
}
| 30.142857 | 156 | 0.617514 | [
"vector"
] |
190bec86a1f1e815f3e6e3d9adb8e99fe592977a | 1,975 | h | C | common/crypto/pdo/ccf_transaction_processor/CCF/src/tls/base64.h | Harshdesa/Blockchain4 | c50e675d8af7c7dd6a69733bb9172a389151efb5 | [
"Apache-2.0"
] | 1 | 2020-02-03T21:57:22.000Z | 2020-02-03T21:57:22.000Z | src/tls/base64.h | kuychaco/CCF | e11acde3be6a7d2213fe5b406b959bb5bb64361d | [
"Apache-2.0"
] | null | null | null | src/tls/base64.h | kuychaco/CCF | e11acde3be6a7d2213fe5b406b959bb5bb64361d | [
"Apache-2.0"
] | 1 | 2021-04-08T12:55:28.000Z | 2021-04-08T12:55:28.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ds/logger.h"
#include "error_string.h"
#include <mbedtls/base64.h>
#include <string>
#include <vector>
namespace tls
{
inline std::vector<uint8_t> raw_from_b64(const std::string_view& b64_string)
{
size_t len_written = 0;
const auto data = reinterpret_cast<const uint8_t*>(b64_string.data());
const auto size = b64_string.size();
// Obtain the size of the output buffer
auto rc = mbedtls_base64_decode(nullptr, 0, &len_written, data, size);
if (rc != MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL)
{
LOG_FAIL_FMT(fmt::format(
"Could not obtain length of decoded base64 buffer: {}",
error_string(rc)));
}
std::vector<uint8_t> decoded(len_written);
rc = mbedtls_base64_decode(
decoded.data(), decoded.size(), &len_written, data, size);
if (rc != 0)
{
LOG_FAIL_FMT(
fmt::format("Could not decode base64 string: {}", error_string(rc)));
}
return decoded;
}
inline std::string b64_from_raw(const uint8_t* data, size_t size)
{
size_t len_written = 0;
// Obtain required size for output buffer
auto rc = mbedtls_base64_encode(nullptr, 0, &len_written, data, size);
if (rc != MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL)
{
LOG_FAIL_FMT(fmt::format(
"Could not obtain length required for encoded base64 buffer: {}",
error_string(rc)));
}
std::string b64_string(len_written, '\0');
auto dest = reinterpret_cast<uint8_t*>(b64_string.data());
rc =
mbedtls_base64_encode(dest, b64_string.size(), &len_written, data, size);
if (rc != 0)
{
LOG_FAIL_FMT(
fmt::format("Could not encode base64 string: {}", error_string(rc)));
}
// mbedtls includes the terminating null, but std-string provides this
// already
b64_string.pop_back();
return b64_string;
}
} | 27.430556 | 79 | 0.660253 | [
"vector"
] |
190c68d8bff6ee2e319c0e36b6726ba633b1ee5e | 9,343 | h | C | Scripts/Template/Headers/org/json/JSONStringer.h | mbeloded/J2ObjC-FrameworkMb | 35dc7171cb7d08edf6824ed3c9f34311c8be3347 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/org/json/JSONStringer.h | mbeloded/J2ObjC-FrameworkMb | 35dc7171cb7d08edf6824ed3c9f34311c8be3347 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/org/json/JSONStringer.h | mbeloded/J2ObjC-FrameworkMb | 35dc7171cb7d08edf6824ed3c9f34311c8be3347 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/json/src/main/java/org/json/JSONStringer.java
//
#include "../../J2ObjC_header.h"
#pragma push_macro("OrgJsonJSONStringer_INCLUDE_ALL")
#ifdef OrgJsonJSONStringer_RESTRICT
#define OrgJsonJSONStringer_INCLUDE_ALL 0
#else
#define OrgJsonJSONStringer_INCLUDE_ALL 1
#endif
#undef OrgJsonJSONStringer_RESTRICT
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if !defined (OrgJsonJSONStringer_) && (OrgJsonJSONStringer_INCLUDE_ALL || defined(OrgJsonJSONStringer_INCLUDE))
#define OrgJsonJSONStringer_
@class JavaLangStringBuilder;
@class OrgJsonJSONStringer_Scope;
/*!
@brief Implements <code>JSONObject.toString</code> and <code>JSONArray.toString</code>.
Most
application developers should use those methods directly and disregard this
API. For example:
@code
JSONObject object = ...
@endcode
<p>Stringers only encode well-formed JSON strings. In particular:
<ul>
<li>The stringer must have exactly one top-level array or object.
<li>Lexical scopes must be balanced: every call to <code>array</code> must
have a matching call to <code>endArray</code> and every call to <code>object</code>
must have a matching call to <code>endObject</code>.
<li>Arrays may not contain keys (property names).
<li>Objects must alternate keys (property names) and values.
<li>Values are inserted with either literal <code>value</code>
calls, or by nesting arrays or objects.
</ul>
Calls that would result in a malformed JSON string will fail with a
<code>JSONException</code>.
<p>This class provides no facility for pretty-printing (ie. indenting)
output. To encode indented output, use <code>JSONObject.toString(int)</code> or
<code>JSONArray.toString(int)</code>.
<p>Some implementations of the API support at most 20 levels of nesting.
Attempts to create more than 20 levels of nesting may fail with a <code>JSONException</code>
.
<p>Each stringer may be used to encode a single top level value. Instances of
this class are not thread safe. Although this class is nonfinal, it was not
designed for inheritance and should not be subclassed. In particular,
self-use by overrideable methods is not specified. See <i>Effective Java</i>
Item 17, "Design and Document or inheritance or else prohibit it" for further
information.
*/
@interface OrgJsonJSONStringer : NSObject {
@public
/*!
@brief The output data, containing at most one top-level array or object.
*/
JavaLangStringBuilder *out_;
}
#pragma mark Public
- (instancetype)init;
/*!
@brief Begins encoding a new array.
Each call to this method must be paired with
a call to <code>endArray</code>.
@return this stringer.
*/
- (OrgJsonJSONStringer *)array;
/*!
@brief Ends encoding the current array.
@return this stringer.
*/
- (OrgJsonJSONStringer *)endArray;
/*!
@brief Ends encoding the current object.
@return this stringer.
*/
- (OrgJsonJSONStringer *)endObject;
/*!
@brief Encodes the key (property name) to this stringer.
@param name the name of the forthcoming value. May not be null.
@return this stringer.
*/
- (OrgJsonJSONStringer *)keyWithNSString:(NSString *)name;
/*!
@brief Begins encoding a new object.
Each call to this method must be paired
with a call to <code>endObject</code>.
@return this stringer.
*/
- (OrgJsonJSONStringer *)object;
/*!
@brief Returns the encoded JSON string.
<p>If invoked with unterminated arrays or unclosed objects, this method's
return value is undefined.
<p><strong>Warning:</strong> although it contradicts the general contract
of <code>Object.toString</code>, this method returns null if the stringer
contains no data.
*/
- (NSString *)description;
/*!
@brief Encodes <code>value</code> to this stringer.
@return this stringer.
*/
- (OrgJsonJSONStringer *)valueWithBoolean:(jboolean)value;
/*!
@brief Encodes <code>value</code> to this stringer.
@param value a finite value. May not be <code>NaNs</code> or
<code>infinities</code>.
@return this stringer.
*/
- (OrgJsonJSONStringer *)valueWithDouble:(jdouble)value;
/*!
@brief Encodes <code>value</code> to this stringer.
@return this stringer.
*/
- (OrgJsonJSONStringer *)valueWithLong:(jlong)value;
/*!
@brief Encodes <code>value</code>.
@param value a <code>JSONObject</code>, <code>JSONArray</code>, String, Boolean,
Integer, Long, Double or null. May not be <code>NaNs</code>
or <code>infinities</code>.
@return this stringer.
*/
- (OrgJsonJSONStringer *)valueWithId:(id)value;
#pragma mark Package-Private
- (instancetype)initWithInt:(jint)indentSpaces;
/*!
@brief Closes the current scope by appending any necessary whitespace and the
given bracket.
*/
- (OrgJsonJSONStringer *)closeWithOrgJsonJSONStringer_Scope:(OrgJsonJSONStringer_Scope *)empty
withOrgJsonJSONStringer_Scope:(OrgJsonJSONStringer_Scope *)nonempty
withNSString:(NSString *)closeBracket;
/*!
@brief Enters a new scope by appending any necessary whitespace and the given
bracket.
*/
- (OrgJsonJSONStringer *)openWithOrgJsonJSONStringer_Scope:(OrgJsonJSONStringer_Scope *)empty
withNSString:(NSString *)openBracket;
@end
J2OBJC_EMPTY_STATIC_INIT(OrgJsonJSONStringer)
J2OBJC_FIELD_SETTER(OrgJsonJSONStringer, out_, JavaLangStringBuilder *)
FOUNDATION_EXPORT void OrgJsonJSONStringer_init(OrgJsonJSONStringer *self);
FOUNDATION_EXPORT OrgJsonJSONStringer *new_OrgJsonJSONStringer_init() NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void OrgJsonJSONStringer_initWithInt_(OrgJsonJSONStringer *self, jint indentSpaces);
FOUNDATION_EXPORT OrgJsonJSONStringer *new_OrgJsonJSONStringer_initWithInt_(jint indentSpaces) NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(OrgJsonJSONStringer)
#endif
#if !defined (OrgJsonJSONStringer_Scope_) && (OrgJsonJSONStringer_INCLUDE_ALL || defined(OrgJsonJSONStringer_Scope_INCLUDE))
#define OrgJsonJSONStringer_Scope_
#define JavaLangEnum_RESTRICT 1
#define JavaLangEnum_INCLUDE 1
#include "../../java/lang/Enum.h"
typedef NS_ENUM(NSUInteger, OrgJsonJSONStringer_Scope_Enum) {
OrgJsonJSONStringer_Scope_Enum_EMPTY_ARRAY = 0,
OrgJsonJSONStringer_Scope_Enum_NONEMPTY_ARRAY = 1,
OrgJsonJSONStringer_Scope_Enum_EMPTY_OBJECT = 2,
OrgJsonJSONStringer_Scope_Enum_DANGLING_KEY = 3,
OrgJsonJSONStringer_Scope_Enum_NONEMPTY_OBJECT = 4,
OrgJsonJSONStringer_Scope_Enum_NULL = 5,
};
/*!
@brief Lexical scoping elements within this stringer, necessary to insert the
appropriate separator characters (ie. commas and colons) and to detect
nesting errors.
*/
@interface OrgJsonJSONStringer_Scope : JavaLangEnum < NSCopying >
+ (OrgJsonJSONStringer_Scope *)EMPTY_ARRAY;
+ (OrgJsonJSONStringer_Scope *)NONEMPTY_ARRAY;
+ (OrgJsonJSONStringer_Scope *)EMPTY_OBJECT;
+ (OrgJsonJSONStringer_Scope *)DANGLING_KEY;
+ (OrgJsonJSONStringer_Scope *)NONEMPTY_OBJECT;
+ (OrgJsonJSONStringer_Scope *)NULL_;
#pragma mark Package-Private
+ (IOSObjectArray *)values;
+ (OrgJsonJSONStringer_Scope *)valueOfWithNSString:(NSString *)name;
- (id)copyWithZone:(NSZone *)zone;
- (OrgJsonJSONStringer_Scope_Enum)toNSEnum;
@end
J2OBJC_STATIC_INIT(OrgJsonJSONStringer_Scope)
/*! INTERNAL ONLY - Use enum accessors declared below. */
FOUNDATION_EXPORT OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_values_[];
/*!
@brief An array with no elements requires no separators or newlines before
it is closed.
*/
inline OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_get_EMPTY_ARRAY();
J2OBJC_ENUM_CONSTANT(OrgJsonJSONStringer_Scope, EMPTY_ARRAY)
/*!
@brief A array with at least one value requires a comma and newline before
the next element.
*/
inline OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_get_NONEMPTY_ARRAY();
J2OBJC_ENUM_CONSTANT(OrgJsonJSONStringer_Scope, NONEMPTY_ARRAY)
/*!
@brief An object with no keys or values requires no separators or newlines
before it is closed.
*/
inline OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_get_EMPTY_OBJECT();
J2OBJC_ENUM_CONSTANT(OrgJsonJSONStringer_Scope, EMPTY_OBJECT)
/*!
@brief An object whose most recent element is a key.
The next element must
be a value.
*/
inline OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_get_DANGLING_KEY();
J2OBJC_ENUM_CONSTANT(OrgJsonJSONStringer_Scope, DANGLING_KEY)
/*!
@brief An object with at least one name/value pair requires a comma and
newline before the next element.
*/
inline OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_get_NONEMPTY_OBJECT();
J2OBJC_ENUM_CONSTANT(OrgJsonJSONStringer_Scope, NONEMPTY_OBJECT)
/*!
@brief A special bracketless array needed by JSONStringer.join() and
JSONObject.quote() only.
Not used for JSON encoding.
*/
inline OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_get_NULL();
J2OBJC_ENUM_CONSTANT(OrgJsonJSONStringer_Scope, NULL)
FOUNDATION_EXPORT IOSObjectArray *OrgJsonJSONStringer_Scope_values();
FOUNDATION_EXPORT OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_valueOfWithNSString_(NSString *name);
FOUNDATION_EXPORT OrgJsonJSONStringer_Scope *OrgJsonJSONStringer_Scope_fromOrdinal(NSUInteger ordinal);
J2OBJC_TYPE_LITERAL_HEADER(OrgJsonJSONStringer_Scope)
#endif
#pragma clang diagnostic pop
#pragma pop_macro("OrgJsonJSONStringer_INCLUDE_ALL")
| 31.996575 | 124 | 0.782511 | [
"object"
] |
190dd12b974f52901da4a09f4c385afeb92b0edc | 21,225 | h | C | psol/include/third_party/serf/src/serf_bucket_types.h | sambacha/nginx2 | ed70546e69d0357831adfd982104c077ac23970b | [
"Apache-2.0"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | psol/include/third_party/serf/src/serf_bucket_types.h | sambacha/nginx2 | ed70546e69d0357831adfd982104c077ac23970b | [
"Apache-2.0"
] | 2 | 2019-01-16T10:34:54.000Z | 2019-02-03T10:59:39.000Z | psol/include/third_party/serf/src/serf_bucket_types.h | sambacha/nginx2 | ed70546e69d0357831adfd982104c077ac23970b | [
"Apache-2.0"
] | null | null | null | /* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
#ifndef SERF_BUCKET_TYPES_H
#define SERF_BUCKET_TYPES_H
#include <apr_mmap.h>
#include <apr_hash.h>
/* this header and serf.h refer to each other, so take a little extra care */
#ifndef SERF_H
#include "serf.h"
#endif
/**
* @file serf_bucket_types.h
* @brief serf-supported bucket types
*/
/* ### this whole file needs docco ... */
#ifdef __cplusplus
extern "C" {
#endif
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_request;
#define SERF_BUCKET_IS_REQUEST(b) SERF_BUCKET_CHECK((b), request)
serf_bucket_t *serf_bucket_request_create(
const char *method,
const char *URI,
serf_bucket_t *body,
serf_bucket_alloc_t *allocator);
/* Send a Content-Length header with @a len. The @a body bucket should
contain precisely that much data. */
void serf_bucket_request_set_CL(
serf_bucket_t *bucket,
apr_int64_t len);
serf_bucket_t *serf_bucket_request_get_headers(
serf_bucket_t *request);
void serf_bucket_request_become(
serf_bucket_t *bucket,
const char *method,
const char *uri,
serf_bucket_t *body);
/**
* Sets the root url of the remote host. If this request contains a relative
* url, it will be prefixed with the root url to form an absolute url.
* @a bucket is the request bucket. @a root_url is the absolute url of the
* root of the remote host, without the closing '/'.
*/
void serf_bucket_request_set_root(
serf_bucket_t *bucket,
const char *root_url);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_response;
#define SERF_BUCKET_IS_RESPONSE(b) SERF_BUCKET_CHECK((b), response)
serf_bucket_t *serf_bucket_response_create(
serf_bucket_t *stream,
serf_bucket_alloc_t *allocator);
#define SERF_HTTP_VERSION(major, minor) ((major) * 1000 + (minor))
#define SERF_HTTP_11 SERF_HTTP_VERSION(1, 1)
#define SERF_HTTP_10 SERF_HTTP_VERSION(1, 0)
#define SERF_HTTP_VERSION_MAJOR(shv) ((int)shv / 1000)
#define SERF_HTTP_VERSION_MINOR(shv) ((int)shv % 1000)
typedef struct {
int version;
int code;
const char *reason;
} serf_status_line;
/**
* Return the Status-Line information, if available. This function
* works like other bucket read functions: it may return APR_EAGAIN or
* APR_EOF to signal the state of the bucket for reading. A return
* value of APR_SUCCESS will always indicate that status line
* information was returned; for other return values the caller must
* check the version field in @a sline. A value of 0 means that the
* data is not (yet) present.
*/
apr_status_t serf_bucket_response_status(
serf_bucket_t *bkt,
serf_status_line *sline);
/**
* Wait for the HTTP headers to be processed for a @a response.
*
* If the headers are available, APR_SUCCESS is returned.
* If the headers aren't available, APR_EAGAIN is returned.
*/
apr_status_t serf_bucket_response_wait_for_headers(
serf_bucket_t *response);
/**
* Get the headers bucket for @a response.
*/
serf_bucket_t *serf_bucket_response_get_headers(
serf_bucket_t *response);
/**
* Advise the response @a bucket that this was from a HEAD request and
* that it should not expect to see a response body.
*/
void serf_bucket_response_set_head(
serf_bucket_t *bucket);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_response_body;
#define SERF_BUCKET_IS_RESPONSE_BODY(b) SERF_BUCKET_CHECK((b), response_body)
serf_bucket_t *serf_bucket_response_body_create(
serf_bucket_t *stream,
apr_uint64_t limit,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_bwtp_frame;
#define SERF_BUCKET_IS_BWTP_FRAME(b) SERF_BUCKET_CHECK((b), bwtp_frame)
extern const serf_bucket_type_t serf_bucket_type_bwtp_incoming_frame;
#define SERF_BUCKET_IS_BWTP_INCOMING_FRAME(b) SERF_BUCKET_CHECK((b), bwtp_incoming_frame)
int serf_bucket_bwtp_frame_get_channel(
serf_bucket_t *hdr);
int serf_bucket_bwtp_frame_get_type(
serf_bucket_t *hdr);
const char *serf_bucket_bwtp_frame_get_phrase(
serf_bucket_t *hdr);
serf_bucket_t *serf_bucket_bwtp_frame_get_headers(
serf_bucket_t *hdr);
serf_bucket_t *serf_bucket_bwtp_channel_open(
int channel,
const char *URI,
serf_bucket_alloc_t *allocator);
serf_bucket_t *serf_bucket_bwtp_channel_close(
int channel,
serf_bucket_alloc_t *allocator);
serf_bucket_t *serf_bucket_bwtp_header_create(
int channel,
const char *phrase,
serf_bucket_alloc_t *allocator);
serf_bucket_t *serf_bucket_bwtp_message_create(
int channel,
serf_bucket_t *body,
serf_bucket_alloc_t *allocator);
serf_bucket_t *serf_bucket_bwtp_incoming_frame_create(
serf_bucket_t *bkt,
serf_bucket_alloc_t *allocator);
apr_status_t serf_bucket_bwtp_incoming_frame_wait_for_headers(
serf_bucket_t *bkt);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_aggregate;
#define SERF_BUCKET_IS_AGGREGATE(b) SERF_BUCKET_CHECK((b), aggregate)
typedef apr_status_t (*serf_bucket_aggregate_eof_t)(
void *baton,
serf_bucket_t *aggregate_bucket);
/** serf_bucket_aggregate_cleanup will instantly destroy all buckets in
the aggregate bucket that have been read completely. Whereas normally,
these buckets are destroyed on every read operation. */
void serf_bucket_aggregate_cleanup(
serf_bucket_t *bucket,
serf_bucket_alloc_t *allocator);
serf_bucket_t *serf_bucket_aggregate_create(
serf_bucket_alloc_t *allocator);
/* Creates a stream bucket.
A stream bucket is like an aggregate bucket, but:
- it doesn't destroy its child buckets on cleanup
- one can always keep adding child buckets, the handler FN should return
APR_EOF when no more buckets will be added.
Note: keep this factory function internal for now. If it turns out this
bucket type is useful outside serf, we should make it an actual separate
type.
*/
serf_bucket_t *serf__bucket_stream_create(
serf_bucket_alloc_t *allocator,
serf_bucket_aggregate_eof_t fn,
void *baton);
/** Transform @a bucket in-place into an aggregate bucket. */
void serf_bucket_aggregate_become(
serf_bucket_t *bucket);
void serf_bucket_aggregate_prepend(
serf_bucket_t *aggregate_bucket,
serf_bucket_t *prepend_bucket);
void serf_bucket_aggregate_append(
serf_bucket_t *aggregate_bucket,
serf_bucket_t *append_bucket);
void serf_bucket_aggregate_hold_open(
serf_bucket_t *aggregate_bucket,
serf_bucket_aggregate_eof_t fn,
void *baton);
void serf_bucket_aggregate_prepend_iovec(
serf_bucket_t *aggregate_bucket,
struct iovec *vecs,
int vecs_count);
void serf_bucket_aggregate_append_iovec(
serf_bucket_t *aggregate_bucket,
struct iovec *vecs,
int vecs_count);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_file;
#define SERF_BUCKET_IS_FILE(b) SERF_BUCKET_CHECK((b), file)
serf_bucket_t *serf_bucket_file_create(
apr_file_t *file,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_socket;
#define SERF_BUCKET_IS_SOCKET(b) SERF_BUCKET_CHECK((b), socket)
serf_bucket_t *serf_bucket_socket_create(
apr_socket_t *skt,
serf_bucket_alloc_t *allocator);
/**
* Call @a progress_func every time bytes are read from the socket, pass
* the number of bytes read.
*
* When using serf's bytes read & written progress indicator, pass
* @a serf_context_progress_delta for progress_func and the serf_context for
* progress_baton.
*/
void serf_bucket_socket_set_read_progress_cb(
serf_bucket_t *bucket,
const serf_progress_t progress_func,
void *progress_baton);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_simple;
#define SERF_BUCKET_IS_SIMPLE(b) SERF_BUCKET_CHECK((b), simple)
typedef void (*serf_simple_freefunc_t)(
void *baton,
const char *data);
serf_bucket_t *serf_bucket_simple_create(
const char *data,
apr_size_t len,
serf_simple_freefunc_t freefunc,
void *freefunc_baton,
serf_bucket_alloc_t *allocator);
/**
* Equivalent to serf_bucket_simple_create, except that the bucket takes
* ownership of a private copy of the data.
*/
serf_bucket_t *serf_bucket_simple_copy_create(
const char *data,
apr_size_t len,
serf_bucket_alloc_t *allocator);
/**
* Equivalent to serf_bucket_simple_create, except that the bucket assumes
* responsibility for freeing the data on this allocator without making
* a copy. It is assumed that data was created by a call from allocator.
*/
serf_bucket_t *serf_bucket_simple_own_create(
const char *data,
apr_size_t len,
serf_bucket_alloc_t *allocator);
#define SERF_BUCKET_SIMPLE_STRING(s,a) \
serf_bucket_simple_create(s, strlen(s), NULL, NULL, a);
#define SERF_BUCKET_SIMPLE_STRING_LEN(s,l,a) \
serf_bucket_simple_create(s, l, NULL, NULL, a);
/* ==================================================================== */
/* Note: apr_mmap_t is always defined, but if APR doesn't have mmaps, then
the caller can never create an apr_mmap_t to pass to this function. */
extern const serf_bucket_type_t serf_bucket_type_mmap;
#define SERF_BUCKET_IS_MMAP(b) SERF_BUCKET_CHECK((b), mmap)
serf_bucket_t *serf_bucket_mmap_create(
apr_mmap_t *mmap,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_headers;
#define SERF_BUCKET_IS_HEADERS(b) SERF_BUCKET_CHECK((b), headers)
serf_bucket_t *serf_bucket_headers_create(
serf_bucket_alloc_t *allocator);
/**
* Set, default: value copied.
*
* Set the specified @a header within the bucket, copying the @a value
* into space from this bucket's allocator. The header is NOT copied,
* so it should remain in scope at least as long as the bucket.
*/
void serf_bucket_headers_set(
serf_bucket_t *headers_bucket,
const char *header,
const char *value);
/**
* Set, copies: header and value copied.
*
* Copy the specified @a header and @a value into the bucket, using space
* from this bucket's allocator.
*/
void serf_bucket_headers_setc(
serf_bucket_t *headers_bucket,
const char *header,
const char *value);
/**
* Set, no copies.
*
* Set the specified @a header and @a value into the bucket, without
* copying either attribute. Both attributes should remain in scope at
* least as long as the bucket.
*
* @note In the case where a header already exists this will result
* in a reallocation and copy, @see serf_bucket_headers_setn.
*/
void serf_bucket_headers_setn(
serf_bucket_t *headers_bucket,
const char *header,
const char *value);
/**
* Set, extended: fine grained copy control of header and value.
*
* Set the specified @a header, with length @a header_size with the
* @a value, and length @a value_size, into the bucket. The header will
* be copied if @a header_copy is set, and the value is copied if
* @a value_copy is set. If the values are not copied, then they should
* remain in scope at least as long as the bucket.
*
* If @a headers_bucket already contains a header with the same name
* as @a header, then append @a value to the existing value,
* separating with a comma (as per RFC 2616, section 4.2). In this
* case, the new value must be allocated and the header re-used, so
* behave as if @a value_copy were true and @a header_copy false.
*/
void serf_bucket_headers_setx(
serf_bucket_t *headers_bucket,
const char *header,
apr_size_t header_size,
int header_copy,
const char *value,
apr_size_t value_size,
int value_copy);
const char *serf_bucket_headers_get(
serf_bucket_t *headers_bucket,
const char *header);
/**
* @param baton opaque baton as passed to @see serf_bucket_headers_do
* @param key The header key from this iteration through the table
* @param value The header value from this iteration through the table
*/
typedef int (serf_bucket_headers_do_callback_fn_t)(
void *baton,
const char *key,
const char *value);
/**
* Iterates over all headers of the message and invokes the callback
* function with header key and value. Stop iterating when no more
* headers are available or when the callback function returned a
* non-0 value.
*
* @param headers_bucket headers to iterate over
* @param func callback routine to invoke for every header in the bucket
* @param baton baton to pass on each invocation to func
*/
void serf_bucket_headers_do(
serf_bucket_t *headers_bucket,
serf_bucket_headers_do_callback_fn_t func,
void *baton);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_chunk;
#define SERF_BUCKET_IS_CHUNK(b) SERF_BUCKET_CHECK((b), chunk)
serf_bucket_t *serf_bucket_chunk_create(
serf_bucket_t *stream,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_dechunk;
#define SERF_BUCKET_IS_DECHUNK(b) SERF_BUCKET_CHECK((b), dechunk)
serf_bucket_t *serf_bucket_dechunk_create(
serf_bucket_t *stream,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_deflate;
#define SERF_BUCKET_IS_DEFLATE(b) SERF_BUCKET_CHECK((b), deflate)
#define SERF_DEFLATE_GZIP 0
#define SERF_DEFLATE_DEFLATE 1
serf_bucket_t *serf_bucket_deflate_create(
serf_bucket_t *stream,
serf_bucket_alloc_t *allocator,
int format);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_limit;
#define SERF_BUCKET_IS_LIMIT(b) SERF_BUCKET_CHECK((b), limit)
serf_bucket_t *serf_bucket_limit_create(
serf_bucket_t *stream,
apr_uint64_t limit,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
#define SERF_SSL_CERT_NOTYETVALID 1
#define SERF_SSL_CERT_EXPIRED 2
#define SERF_SSL_CERT_UNKNOWNCA 4
#define SERF_SSL_CERT_SELF_SIGNED 8
#define SERF_SSL_CERT_UNKNOWN_FAILURE 16
#define SERF_SSL_CERT_REVOKED 32
extern const serf_bucket_type_t serf_bucket_type_ssl_encrypt;
#define SERF_BUCKET_IS_SSL_ENCRYPT(b) SERF_BUCKET_CHECK((b), ssl_encrypt)
typedef struct serf_ssl_context_t serf_ssl_context_t;
typedef struct serf_ssl_certificate_t serf_ssl_certificate_t;
typedef apr_status_t (*serf_ssl_need_client_cert_t)(
void *data,
const char **cert_path);
typedef apr_status_t (*serf_ssl_need_cert_password_t)(
void *data,
const char *cert_path,
const char **password);
typedef apr_status_t (*serf_ssl_need_server_cert_t)(
void *data,
int failures,
const serf_ssl_certificate_t *cert);
typedef apr_status_t (*serf_ssl_server_cert_chain_cb_t)(
void *data,
int failures,
int error_depth,
const serf_ssl_certificate_t * const * certs,
apr_size_t certs_len);
void serf_ssl_client_cert_provider_set(
serf_ssl_context_t *context,
serf_ssl_need_client_cert_t callback,
void *data,
void *cache_pool);
void serf_ssl_client_cert_password_set(
serf_ssl_context_t *context,
serf_ssl_need_cert_password_t callback,
void *data,
void *cache_pool);
/**
* Set a callback to override the default SSL server certificate validation
* algorithm.
*/
void serf_ssl_server_cert_callback_set(
serf_ssl_context_t *context,
serf_ssl_need_server_cert_t callback,
void *data);
/**
* Set callbacks to override the default SSL server certificate validation
* algorithm for the current certificate or the entire certificate chain.
*/
void serf_ssl_server_cert_chain_callback_set(
serf_ssl_context_t *context,
serf_ssl_need_server_cert_t cert_callback,
serf_ssl_server_cert_chain_cb_t cert_chain_callback,
void *data);
/**
* Use the default root CA certificates as included with the OpenSSL library.
*/
apr_status_t serf_ssl_use_default_certificates(
serf_ssl_context_t *context);
/**
* Allow SNI indicators to be sent to the server.
*/
apr_status_t serf_ssl_set_hostname(
serf_ssl_context_t *context, const char *hostname);
/**
* Return the depth of the certificate.
*/
int serf_ssl_cert_depth(
const serf_ssl_certificate_t *cert);
/**
* Extract the fields of the issuer in a table with keys (E, CN, OU, O, L,
* ST and C). The returned table will be allocated in @a pool.
*/
apr_hash_t *serf_ssl_cert_issuer(
const serf_ssl_certificate_t *cert,
apr_pool_t *pool);
/**
* Extract the fields of the subject in a table with keys (E, CN, OU, O, L,
* ST and C). The returned table will be allocated in @a pool.
*/
apr_hash_t *serf_ssl_cert_subject(
const serf_ssl_certificate_t *cert,
apr_pool_t *pool);
/**
* Extract the fields of the certificate in a table with keys (sha1, notBefore,
* notAfter, subjectAltName). The returned table will be allocated in @a pool.
*/
apr_hash_t *serf_ssl_cert_certificate(
const serf_ssl_certificate_t *cert,
apr_pool_t *pool);
/**
* Export a certificate to base64-encoded, zero-terminated string.
* The returned string is allocated in @a pool. Returns NULL on failure.
*/
const char *serf_ssl_cert_export(
const serf_ssl_certificate_t *cert,
apr_pool_t *pool);
/**
* Load a CA certificate file from a path @a file_path. If the file was loaded
* and parsed correctly, a certificate @a cert will be created and returned.
* This certificate object will be alloced in @a pool.
*/
apr_status_t serf_ssl_load_cert_file(
serf_ssl_certificate_t **cert,
const char *file_path,
apr_pool_t *pool);
/**
* Adds the certificate @a cert to the list of trusted certificates in
* @a ssl_ctx that will be used for verification.
* See also @a serf_ssl_load_cert_file.
*/
apr_status_t serf_ssl_trust_cert(
serf_ssl_context_t *ssl_ctx,
serf_ssl_certificate_t *cert);
/**
* Enable or disable SSL compression on a SSL session.
* @a enabled = 1 to enable compression, 0 to disable compression.
* Default = disabled.
*/
apr_status_t serf_ssl_use_compression(
serf_ssl_context_t *ssl_ctx,
int enabled);
serf_bucket_t *serf_bucket_ssl_encrypt_create(
serf_bucket_t *stream,
serf_ssl_context_t *ssl_context,
serf_bucket_alloc_t *allocator);
serf_ssl_context_t *serf_bucket_ssl_encrypt_context_get(
serf_bucket_t *bucket);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_ssl_decrypt;
#define SERF_BUCKET_IS_SSL_DECRYPT(b) SERF_BUCKET_CHECK((b), ssl_decrypt)
serf_bucket_t *serf_bucket_ssl_decrypt_create(
serf_bucket_t *stream,
serf_ssl_context_t *ssl_context,
serf_bucket_alloc_t *allocator);
serf_ssl_context_t *serf_bucket_ssl_decrypt_context_get(
serf_bucket_t *bucket);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_barrier;
#define SERF_BUCKET_IS_BARRIER(b) SERF_BUCKET_CHECK((b), barrier)
serf_bucket_t *serf_bucket_barrier_create(
serf_bucket_t *stream,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
extern const serf_bucket_type_t serf_bucket_type_iovec;
#define SERF_BUCKET_IS_IOVEC(b) SERF_BUCKET_CHECK((b), iovec)
serf_bucket_t *serf_bucket_iovec_create(
struct iovec vecs[],
int len,
serf_bucket_alloc_t *allocator);
/* ==================================================================== */
/* ### do we need a PIPE bucket type? they are simple apr_file_t objects */
#ifdef __cplusplus
}
#endif
#endif /* !SERF_BUCKET_TYPES_H */
| 30.583573 | 89 | 0.705913 | [
"object",
"transform"
] |
1910f3c936924b3d3e6db9d32f2b0b1cb148274a | 57,127 | c | C | src/cpu/ccpu/ccpu.c | rsn8887/mame2003-plus-libretro | 2d0759df85a6e647a7301fed9eec37b4f4270812 | [
"RSA-MD"
] | 145 | 2018-04-10T17:24:39.000Z | 2022-03-27T17:39:03.000Z | src/cpu/ccpu/ccpu.c | rsn8887/mame2003-plus-libretro | 2d0759df85a6e647a7301fed9eec37b4f4270812 | [
"RSA-MD"
] | 779 | 2018-04-09T21:30:15.000Z | 2022-03-31T06:38:07.000Z | src/cpu/ccpu/ccpu.c | rsn8887/mame2003-plus-libretro | 2d0759df85a6e647a7301fed9eec37b4f4270812 | [
"RSA-MD"
] | 152 | 2018-04-10T10:52:18.000Z | 2022-03-09T08:24:16.000Z | /*** Glue Code (******************************************
Glue code to hook up Retrocade's CCPU emulator to MAME's
architecture. Really, it's not so bad!
**********************************************************/
#include "driver.h"
#include "mamedbg.h"
#include "ccpu.h"
static UINT8 ccpu_reg_layout[] = {
CCPU_PC, CCPU_CFLAG, CCPU_CSTATE, CCPU_A, CCPU_B, CCPU_I, -1,
CCPU_P, CCPU_J, CCPU_ACC, CCPU_CMP, CCPU_PA0, 0,
};
/* Layout of the debugger windows x,y,w,h */
static UINT8 ccpu_win_layout[] = {
25, 0,55, 2, /* register window (top rows) */
0, 0,24,22, /* disassembler window (left colums) */
25, 3,55, 9, /* memory #1 window (right, upper middle) */
25,13,55, 9, /* memory #2 window (right, lower middle) */
0,23,80, 1, /* command line window (bottom rows) */
};
/* the MAME version of the CCPU registers */
typedef struct ccpuRegs
{
UINT16 accVal;
UINT16 cmpVal;
UINT8 pa0;
UINT8 cFlag;
UINT16 eRegPC;
UINT16 eRegA;
UINT16 eRegB;
UINT16 eRegI;
UINT16 eRegJ;
UINT8 eRegP;
UINT8 eCState;
} ccpuRegs;
#define CCPU_FETCH(a) (cpu_readop(BYTE_XOR_BE(a)+CCPU_PGM_OFFSET))
#define CCPU_READPORT(a) (cpu_readport16bew_word(a))
#define CCPU_WRITEPORT(a,v) (cpu_writeport16bew_word(a,v))
/*
* Read a word from given RAM memory location
*/
#define CCPU_RAM_RDMEM(A) (cpu_readmem16bew_word((A<<1)+CCPU_DATA_OFFSET))
/*
* Write a word to given RAM memory location
*/
#define CCPU_RAM_WRMEM(A,V) (cpu_writemem16bew_word((A<<1)+CCPU_DATA_OFFSET,V))
#define RAW_VECTORS 1
/* this #define works around the naming conflict with the opcode_table
in cinedbg.c */
#define opcode_table _opcode_table
/* This prototype was missing */
extern void CinemaVectorData (int fromx, int fromy, int tox, int toy, int color);
int ccpu_icount = 1000;
extern UINT16 ioSwitches;
extern UINT16 ioInputs;
void ccpu_init(void)
{
}
void ccpu_reset(void *param)
{
cineReset();
}
void ccpu_exit(void)
{
/* nothing to do ? */
}
int ccpu_execute(int cycles)
{
int newCycles;
newCycles = cineExec(cycles);
return newCycles;
}
unsigned ccpu_get_context(void *dst)
{
if( dst )
{
CONTEXTCCPU context;
ccpuRegs *Regs = dst;
cGetContext (&context);
Regs->accVal = context.accVal;
Regs->cmpVal = context.cmpVal;
Regs->pa0 = context.pa0;
Regs->cFlag = context.cFlag;
Regs->eRegPC = context.eRegPC;
Regs->eRegA = context.eRegA;
Regs->eRegB = context.eRegB;
Regs->eRegI = context.eRegI;
Regs->eRegJ = context.eRegJ;
Regs->eRegP = context.eRegP;
Regs->eCState = context.eCState;
}
return sizeof(ccpuRegs);
}
void ccpu_set_context(void *src)
{
if( src )
{
CONTEXTCCPU context;
ccpuRegs *Regs = src;
context.accVal = Regs->accVal;
context.cmpVal = Regs->cmpVal;
context.pa0 = Regs->pa0;
context.cFlag = Regs->cFlag;
context.eRegPC = Regs->eRegPC;
context.eRegA = Regs->eRegA;
context.eRegB = Regs->eRegB;
context.eRegI = Regs->eRegI;
context.eRegJ = Regs->eRegJ;
context.eRegP = Regs->eRegP;
context.eCState = (CINESTATE)Regs->eCState;
cSetContext (&context);
}
}
unsigned ccpu_get_reg(int regnum)
{
CONTEXTCCPU context;
cGetContext (&context);
switch( regnum )
{
case CCPU_ACC: return context.accVal;
case CCPU_CMP: return context.cmpVal;
case CCPU_PA0: return context.pa0;
case CCPU_CFLAG: return context.cFlag;
case REG_PC:
case CCPU_PC: return context.eRegPC;
case CCPU_A: return context.eRegA;
case CCPU_B: return context.eRegB;
case CCPU_I: return context.eRegI;
case CCPU_J: return context.eRegJ;
case REG_SP:
case CCPU_P: return context.eRegP;
case CCPU_CSTATE: return context.eCState;
/* TODO: return contents of [SP + wordsize * (REG_SP_CONTENTS-regnum)] */
default:
if( regnum <= REG_SP_CONTENTS )
return 0;
}
return 0;
}
void ccpu_set_reg(int regnum, unsigned val)
{
CONTEXTCCPU context;
cGetContext (&context);
switch( regnum )
{
case CCPU_ACC: context.accVal = val; break;
case CCPU_CMP: context.cmpVal = val; break;
case CCPU_PA0: context.pa0 = val; break;
case CCPU_CFLAG: context.cFlag = val; break;
case REG_PC:
case CCPU_PC: context.eRegPC = val; break;
case CCPU_A: context.eRegA = val; break;
case CCPU_B: context.eRegB = val; break;
case CCPU_I: context.eRegI = val; break;
case CCPU_J: context.eRegJ = val; break;
case REG_SP:
case CCPU_P: context.eRegP = val; break;
case CCPU_CSTATE: context.eCState = (CINESTATE) val; break;
/* TODO: set contents of [SP + wordsize * (REG_SP_CONTENTS-regnum)] */
default:
if( regnum <= REG_SP_CONTENTS )
{
unsigned offset = /* SP? + */ (REG_SP_CONTENTS-regnum);
(void)offset;
}
}
cSetContext (&context);
}
void ccpu_set_irq_line(int irqline, int state)
{
/* nothing to do */
}
void ccpu_set_irq_callback(int (*callback)(int irqline))
{
/* nothing to do */
}
const char *ccpu_info(void *context, int regnum)
{
static char buffer[16][47+1];
static int which = 0;
CONTEXTCCPU *r = context;
which = (which+1) % 16;
buffer[which][0] = '\0';
if( !context )
{
static CONTEXTCCPU tmp;
cGetContext(&tmp);
r = &tmp;
}
switch( regnum )
{
case CPU_INFO_REG+CCPU_PC: sprintf(buffer[which], "PC:%04X", r->eRegPC); break;
case CPU_INFO_REG+CCPU_CFLAG: sprintf(buffer[which], "C:%02X", r->cFlag); break;
case CPU_INFO_REG+CCPU_CSTATE: sprintf(buffer[which], "S:%X", r->eCState); break;
case CPU_INFO_REG+CCPU_A: sprintf(buffer[which], "A:%03X", r->eRegA); break;
case CPU_INFO_REG+CCPU_B: sprintf(buffer[which], "B:%03X", r->eRegB); break;
case CPU_INFO_REG+CCPU_I: sprintf(buffer[which], "I:%03X", r->eRegI); break;
case CPU_INFO_REG+CCPU_P: sprintf(buffer[which], "P:%X", r->eRegP); break;
case CPU_INFO_REG+CCPU_J: sprintf(buffer[which], "J:%03X", r->eRegJ); break;
case CPU_INFO_REG+CCPU_ACC: sprintf(buffer[which], "ACC:%03X", r->accVal); break;
case CPU_INFO_REG+CCPU_CMP: sprintf(buffer[which], "CMP:%03X", r->cmpVal); break;
case CPU_INFO_REG+CCPU_PA0: sprintf(buffer[which], "PA0:%02X", r->pa0); break;
break;
case CPU_INFO_FLAGS:
/* TODO: no idea how the flags should look like */
sprintf(buffer[which], "%c-%c%c%c%c",
(r->cFlag) ? 'C' : 'c',
(r->eCState == state_A || r->eCState == state_AA) ? 'A':' ',
(r->eCState == state_A) ? 'A':' ',
(r->eCState == state_B || r->eCState == state_BB) ? 'B':' ',
(r->eCState == state_B) ? 'B':' ');
break;
case CPU_INFO_NAME: return "CCPU";
case CPU_INFO_FAMILY: return "Cinematronics CPU";
case CPU_INFO_VERSION: return "1.0";
case CPU_INFO_FILE: return __FILE__;
case CPU_INFO_CREDITS: return "Copyright 1997/1998 Jeff Mitchell and the Retrocade Alliance\nCopyright 1997 Zonn Moore";
case CPU_INFO_REG_LAYOUT: return (const char *)ccpu_reg_layout;
case CPU_INFO_WIN_LAYOUT: return (const char *)ccpu_win_layout;
}
return buffer[which];
}
/* TODO: hook up the disassembler */
unsigned ccpu_dasm(char *buffer, unsigned pc)
{
#ifdef MAME_DEBUG
return DasmCCPU(buffer,pc);
#else
sprintf( buffer, "$%02X", cpu_readop(pc) );
return 1;
#endif
}
void ccpu_Config (int jmi, int msize, int monitor)
{
cineSetJMI (jmi);
cineSetMSize (msize);
cineSetMonitor (monitor);
}
void ccpu_SetInputs(int inputs, int switches)
{
/* ioInputs = inputs;
ioSwitches = switches;*/
}
/* To do:
- make RAM external */
/*============================================================================================*
BELOW LIES THE CORE OF THE CCPU. THE CODE WAS KINDLY GIVEN TO MAME BY ZONN MOORE,
JEFF MITCHELL, AND NEIL BRADLEY. I HAVE PRETTY HEAVILY CLEANED IT UP.
*============================================================================================*/
/*
* cinecore.c, cinedbg.c, cineops.c -- Cinematronics game emulator
* copyright 1997/1998 Jeff Mitchell and the Retrocade Alliance
* copyright 1997 Zonn Moore
*
* This Cinematronics emulator may be freely used in any non-commercial
* venture, and is to be considered as under the Gnu Public Licence
* (GPL, copyleft). To avoid a huge deluge of email, I also allow the
* MAME team usage under the so-called MAME licence for non-commercial
* use.
*
* There are some restrictions, however, mostly to help further development
* of the emulator and continue the enjoyment these fine games have
* provided.
*
* 1) Jeff Mitchell (skeezix@skeleton.org) is the authoritative maintainer for
* the C implementation of the "CCPU" written by Zonn Moore. Modifications
* or changes to this code may not be distributed in source form, in whole
* or in part, without the written permission of the maintainer. (ie: At
* some point after changes have been made, submit them to the maintainer
* for inclusion into the authoritative source tree, for all to use.)
* 2) Credit must be given where appropriate: Jeff Mitchell, author of the
* C version. Zonn Moore for the ASM version and all original research,
* original documentation, etc. (The C version is a rewrite of Zonn's
* brilliant work.) Neil Bradley, for the 32bit conversion of the ASM
* core, and technical assistance. Without him, the C version wouldn't
* have been written. Where possible, please include references to the
* official website for the software (see below), so that others may
* easily find the sources.
* 3) Users of this software are encouraged to periodically check the
* official website for new revisions, bugfixes, etc. This is an
* ongoing project, with many optimizations yet to be done.
*
* Games known to work 100% or nearly so, at some point or another of
* the emulators development (but not necessarily right now :):
* RipOff, Solar Quest, Spacewar, Speed Freak, Star Castle, Star Hawk,
* Tail Gunner, War of the Worlds, Warrior
*
* For reference, all of the cinematronics games are:
* Armor Attack, Barrier, Boxing Bugs, Demon, Ripoff, Solar Quest,
* Spacewar, Speed Freak, Star Castle, Star Hawk, Sundance, Tail Gunner
* War of the worlds, Warrior
* (There is another, but it has not been made available yet)
*
* USAGE:
* 1) The emulator works like any other "processor" emulator
* 2) It does expect a few variables to be set, however, indicating
* which switches were connected on the original boards. (Most
* important is the variable to chose whethor or not to use the MI
* or EI flag...). See below.
* 3) The emulator expects the memory to ALREADY be interleaved into
* "normalacy". The cinem ROMs are slow to read otherwise...
* 4) Endianness doesn't matter; its code nice and slowly :)
* 5) Compile time options may be set to obtain debugging tool, runtime
* traces, etc etc.
* 6) The emulator does the vector handling; you need provide a routine
* to receive the vector draw requests, so that it may queue them up
* 7) Zonn will be documenting the method by which the game palettes
* may be derived, where applicable.
*
* INITIALIZATION:
* Take, for example, the game RipOff (the reaosn I got into this mess :).
* The following variables need to be set, and the functions called, in
* order to have the "cpu" run properly (courtesy Neil Bradley, Zonn Moore):
* bFlipX = 0; bFlipY = 1; bSwapXY = 0; (for vector generation)
* ioInputs = 0xffff; ioSwitches = 0xfff0; (cleared values)
* bOverlay = 0xff; (No overlay)
* cineSetJMI(1); (JMI Allowed)
* cineSetMSize(0); (8K)
* cineSetMonitor(0); (Bi-level display)
*
* If masking values are needed by anyone for the various game
* controllers and whatnot, let me know, and I'll put up a document.
*
* SUPPORT:
* FTP and WEB:
* Official support archive is at ftp.retrocade.com and www.retrocade.com.
* Various mirrors will be kept (ie: skeleton.org, the Emulation Repository,
* erc.), and are yet to be announced.
* EMAIL:
* The C version: Jeff Mitchell is skeezix@skeleton.org
* The ASM version: Neil Bradley (neil@synthcom.com) and
* Zonn Moore (zonn@zonn.com)
*
* An emulator for the Cinematronics vector game hardware, originally
* for use in the Retrocade emulator project. All work is based on
* documentation and sources and testbeds created by Zonn. He's a freak.
*
* Last modified: 02/17/98
*
* 12/04/97: Created a "SETFC" macro for storing the flag_C var
* (shift and mask it at inspection time)
* 12/??/97: Fixed subtraction bugs (using register_B for A0 instead
* of register_A). Fixed input mask value in opINP.
* 12/24/97: Added #define for CCPUSSTEP for single stepping
* 12/25/97: Added ioSwitches &= (!SW_ABORT) into the top
* of the cineExec call. This fixed Star Castle, but
* broke others :/
* Made opLSLe_A_.. handle multiple consecutive occurances
* so things would be a little faster, and so DOS versus
* Unix traces would be easier.
* Changed above ioSwitches fix to ~SW_ABORT instead. This
* rebroke StarCastle and Sundance, but fixed Barrier. *sigh*
*/
/* Optional #defines for debugging:
* CCPUBREAK -- causes stopage on unknown upcodes
* For these to operate, the debugging variables must be set as well.
* This allows runtime selection of traces, etc.
* CCPUSSTEP -- force single stepping
*
* Debug Variables:
* ccpubreak -- set to non-zero to enable "break"ing
*/
/* 1) Need to macro-ize everything, so that I can have this whole
* source file written by a perl script generator easier.
* 4) Any of the jumps weird? JNC?
* 5) JEI's all fucked? Are the tredirector's set right in the first place?
* What about all those damned JPP8, 16 and 32s? They work right?
* 6) Store ccpu_jmi_dip and other new state vars in struct?
* 7) Various OUT functions correct?
*/
#include <stdio.h>
#include <string.h>
/*
* Use 0xF000 so as to keep the current page, since it may well
* have been changed with JPP.
*/
#define JMP() register_PC = ((register_PC - 1) & 0xF000) + register_J; ccpu_icount -= 2
/* Declare needed macros */
#ifdef macintosh
#define UNFINISHED(x) { SysBeep (0); }
#else
#define UNFINISHED(x) { log_cb(RETRO_LOG_DEBUG, LOGPRE "UNFINISHED: %s\n", x); }
#endif
/* Handy new operators ... */
/* for Zonn translation :) */
#define SAR(var,arg) (((signed short int) var) >> arg)
/* for setting/checking the A0 flag */
#define SETA0(var) (acc_a0 = var)
#define GETA0() (acc_a0)
/* for setting/checking the Carry flag */
#define SETFC(val) (flag_C = val)
#define GETFC() ((flag_C >> 8) & 0xFF)
static int bailOut = FALSE;
/* C-CPU context information begins -- */
static CINEWORD register_PC = 0; /* C-CPU registers; program counter */
static CINEWORD register_A = 0; /* A-Register (accumulator) */
static CINEWORD register_B = 0; /* B-Register (accumulator) */
static CINEBYTE register_I = 0; /* I-Register (last access RAM location) */
static CINEWORD register_J = 0; /* J-Register (target address for JMP opcodes) */
static CINEBYTE register_P = 0; /* Page-Register (4 bits) */
static CINEWORD FromX = 0; /* X-Register (start of a vector) */
static CINEWORD FromY = 0; /* Y-Register (start of a vector) */
static CINEWORD register_T = 0; /* T-Register (vector draw length timer) */
static CINEWORD flag_C = 0; /* C-CPU flags; carry. Is word sized, instead
* of CINEBYTE, so we can do direct assignment
* and then change to BYTE during inspection.
*/
static CINEWORD cmp_old = 0; /* last accumulator value */
static CINEWORD cmp_new = 0; /* new accumulator value */
static CINEBYTE acc_a0 = 0; /* bit0 of A-reg at last accumulator access */
static CINESTATE state = state_A;/* C-CPU state machine current state */
/*static CINEWORD ram[256]; // C-CPU ram (for all pages) */
/*#define CCPU_RAM_RDMEM(a) (ram[a])*/
/*#define CCPU_RAM_WRMEM(a,v) (ram[a]=v)*/
static int ccpu_jmi_dip = 0; /* as set by cineSetJMI */
static int ccpu_msize = 0; /* as set by cineSetMSize */
static int ccpu_monitor = 0; /* as set by cineSetMonitor */
static CINEBYTE vgShiftLength = 0; /* number of shifts loaded into length reg */
static CINEWORD vgColour = 0;
/* -- Context information ends. */
int bNewFrame;
/* Note: I have removed all of this assuming that the vector drawing function can handle things */
#if !RAW_VECTORS
int bFlipX;
int bFlipY;
int bSwapXY;
int bOverlay;
extern int sdwGameXSize;
extern int sdwGameYSize;
extern int sdwXOffset;
extern int sdwYOffset;
#endif
/* functions */
#include "ccputabl.c"
/*
* cineExec() is what performs all the "processors" work; it will
* continue to execute until something horrible happens, a watchpoint
* is hit, cycle count exceeded, or other happy things.
*/
CINELONG cineExec (CINELONG cycles)
{
ccpu_icount = cycles;
bailOut = FALSE;
do
{
int opcode;
CALL_MAME_DEBUG;
/*
* goto the correct piece of code
* for the current opcode. That piece of code will set the state
* for the next run, as well.
*/
opcode = CCPU_FETCH (register_PC++);
state = (*cineops[state][opcode]) (opcode);
ccpu_icount -= ccpu_cycles[opcode];
/*
* the opcode code has set a state and done mischief with flags and
* the program counter; now jump back to the top and run through another
* opcode.
*/
if (bailOut)
/* ccpu_ICount = 0; */
ccpu_icount -= 100;
}
while (ccpu_icount > 0);
return cycles - ccpu_icount;
}
/*
* the actual opcode code; each piece should be careful to
* (1) set the correct state
* (2) increment the program counter as necessary
* (3) piss with the flags as needed
* otherwise the next opcode will be completely buggered.
*/
CINESTATE opINP_A_AA (int opcode)
{
/*
* bottom 4 bits of opcode are the position of the bit we want;
* obtain input value, shift over that no, and truncate to last bit.
* NOTE: Masking 0x07 does interesting things on Sundance and
* others, but masking 0x0F makes RipOff and others actually work :)
*/
cmp_new = (CCPU_READPORT (CCPU_PORT_IOINPUTS) >> (opcode & 0x0F)) & 0x01;
SETA0 (register_A); /* save old accA bit0 */
SETFC (register_A);
cmp_old = register_A; /* save old accB */
register_A = cmp_new; /* load new accB; zero other bits */
return state_AA;
}
CINESTATE opINP_B_AA (int opcode)
{
/*
* bottom 3 bits of opcode are the position of the bit we want;
* obtain Switches value, shift over that no, and truncate to last bit.
*/
cmp_new = (CCPU_READPORT (CCPU_PORT_IOSWITCHES) >> (opcode & 0x07)) & 0x01;
SETA0 (register_A); /* save old accA bit0 */
SETFC (register_A);
cmp_old = register_B; /* save old accB */
register_B = cmp_new; /* load new accB; zero other bits */
return state_AA;
}
CINESTATE opOUTsnd_A (int opcode)
{
if (!(register_A & 0x01))
CCPU_WRITEPORT (CCPU_PORT_IOOUTPUTS, CCPU_READPORT (CCPU_PORT_IOOUTPUTS) | (0x01 << (opcode & 0x07)));
else
CCPU_WRITEPORT (CCPU_PORT_IOOUTPUTS, CCPU_READPORT (CCPU_PORT_IOOUTPUTS) & ~(0x01 << (opcode & 0x07)));
if ((opcode & 0x07) == 0x05)
{
/* reset coin counter */
}
return state_A;
}
CINESTATE opOUTbi_A_A (int opcode)
{
if ((opcode & 0x07) != 6)
return opOUTsnd_A (opcode);
vgColour = register_A & 0x01 ? 0x0f: 0x07;
return state_A;
}
CINESTATE opOUT16_A_A (int opcode)
{
if ((opcode & 0x07) != 6)
return opOUTsnd_A (opcode);
if ((register_A & 0x1) != 1)
{
vgColour = FromX & 0x0F;
if (!vgColour)
vgColour = 1;
}
return state_A;
}
CINESTATE opOUT64_A_A (int opcode)
{
return state_A;
}
CINESTATE opOUTWW_A_A (int opcode)
{
if ((opcode & 0x07) != 6)
return opOUTsnd_A (opcode);
if ((register_A & 0x1) == 1)
{
CINEWORD temp_word = ~FromX & 0x0FFF;
if (!temp_word) /* black */
vgColour = 0;
else
{ /* non-black */
if (temp_word & 0x0888)
/* bright */
vgColour = ((temp_word >> 1) & 0x04) | ((temp_word >> 6) & 0x02) | ((temp_word >> 11) & 0x01) | 0x08;
else if (temp_word & 0x0444)
/* dim bits */
vgColour = (temp_word & 0x04) | ((temp_word >> 5) & 0x02) | ((temp_word >> 10) & 0x01);
}
} /* colour change? == 1 */
return state_A;
}
CINESTATE opOUTsnd_B (int opcode)
{
return state_BB;
}
CINESTATE opOUTbi_B_BB (int opcode)
{
CINEBYTE temp_byte = opcode & 0x07;
if (temp_byte - 0x06)
return opOUTsnd_B (opcode);
vgColour = ((register_B & 0x01) << 3) | 0x07;
return state_BB;
}
CINESTATE opOUT16_B_BB (int opcode)
{
CINEBYTE temp_byte = opcode & 0x07;
if (temp_byte - 0x06)
return opOUTsnd_B (opcode);
if ((register_B & 0xFF) != 1)
{
vgColour = FromX & 0x0F;
if (!vgColour)
vgColour = 1;
}
return state_BB;
}
CINESTATE opOUT64_B_BB (int opcode)
{
return state_BB;
}
CINESTATE opOUTWW_B_BB (int opcode)
{
return state_BB;
}
/* LDA imm (0x) */
CINESTATE opLDAimm_A_AA (int opcode)
{
CINEWORD temp_word = opcode & 0x0F; /* pick up immediate value */
temp_word <<= 8; /* LDAimm is the HIGH nibble!*/
cmp_new = temp_word; /* set new comparison flag */
SETA0 (register_A); /* save old accA bit0 */
SETFC (register_A); /* ??? clear carry? */
cmp_old = register_A; /* step back cmp flag */
register_A = temp_word; /* set the register */
return state_AA; /* swap state and end opcode */
}
CINESTATE opLDAimm_B_AA (int opcode)
{
CINEWORD temp_word = opcode & 0x0F; /* pick up immediate value */
temp_word <<= 8; /* LDAimm is the HIGH nibble!*/
cmp_new = temp_word; /* set new comparison flag */
SETA0 (register_A); /* save old accA bit0 */
SETFC (register_A);
cmp_old = register_B; /* step back cmp flag */
register_B = temp_word; /* set the register */
return state_AA;
}
CINESTATE opLDAdir_A_AA (int opcode)
{
CINEBYTE temp_byte = opcode & 0x0F; /* snag imm value */
register_I = (register_P << 4) + temp_byte; /* set I register */
cmp_new = CCPU_RAM_RDMEM(register_I); /* new acc value */
SETA0 (register_A); /* back up bit0 */
SETFC (register_A);
cmp_old = register_A; /* store old acc */
register_A = cmp_new; /* store new acc */
return state_AA;
}
CINESTATE opLDAdir_B_AA (int opcode)
{
CINEBYTE temp_byte = opcode & 0x0F; /* snag imm value */
register_I = (register_P << 4) + temp_byte; /* set I register */
cmp_new = CCPU_RAM_RDMEM(register_I); /* new acc value */
SETA0 (register_A); /* back up bit0 */
SETFC (register_A);
cmp_old = register_B; /* store old acc */
register_B = cmp_new; /* store new acc */
return state_AA;
}
CINESTATE opLDAirg_A_AA (int opcode)
{
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
SETFC (register_A);
cmp_old = register_A;
register_A = cmp_new;
return state_AA;
}
CINESTATE opLDAirg_B_AA (int opcode)
{
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
SETFC (register_A);
cmp_old = register_B;
register_B = cmp_new;
return state_AA;
}
/* ADD imm */
CINESTATE opADDimm_A_AA (int opcode)
{
CINEWORD temp_word = opcode & 0x0F; /* get imm value */
cmp_new = temp_word; /* new acc value */
SETA0 (register_A); /* save old accA bit0 */
cmp_old = register_A; /* store old acc for later */
register_A += temp_word; /* add values */
SETFC (register_A); /* store carry and extra */
register_A &= 0xFFF; /* toss out >12bit carry */
return state_AA;
}
CINESTATE opADDimm_B_AA (int opcode)
{
CINEWORD temp_word = opcode & 0x0F; /* get imm value */
cmp_new = temp_word; /* new acc value */
SETA0 (register_A); /* save old accA bit0 */
cmp_old = register_B; /* store old acc for later */
register_B += temp_word; /* add values */
SETFC (register_B); /* store carry and extra */
register_B &= 0xFFF; /* toss out >12bit carry */
return state_AA;
}
/* ADD imm extended */
CINESTATE opADDimmX_A_AA (int opcode)
{
cmp_new = CCPU_FETCH (register_PC++); /* get extended value */
SETA0 (register_A); /* save old accA bit0 */
cmp_old = register_A; /* store old acc for later */
register_A += cmp_new; /* add values */
SETFC (register_A); /* store carry and extra */
register_A &= 0xFFF; /* toss out >12bit carry */
return state_AA;
}
CINESTATE opADDimmX_B_AA (int opcode)
{
cmp_new = CCPU_FETCH (register_PC++); /* get extended value */
SETA0 (register_A); /* save old accA bit0 */
cmp_old = register_B; /* store old acc for later */
register_B += cmp_new; /* add values */
SETFC (register_B); /* store carry and extra */
register_B &= 0xFFF; /* toss out >12bit carry */
return state_AA;
}
CINESTATE opADDdir_A_AA (int opcode)
{
CINEBYTE temp_byte = opcode & 0x0F; /* fetch imm value */
register_I = (register_P << 4) + temp_byte; /* set regI addr */
cmp_new = CCPU_RAM_RDMEM(register_I); /* fetch imm real value */
SETA0 (register_A); /* store bit0 */
cmp_old = register_A; /* store old acc value */
register_A += cmp_new; /* do acc operation */
SETFC (register_A); /* store carry and extra */
register_A &= 0x0FFF;
return state_AA;
}
CINESTATE opADDdir_B_AA (int opcode)
{
CINEBYTE temp_byte = opcode & 0x0F; /* fetch imm value */
register_I = (register_P << 4) + temp_byte; /* set regI addr */
cmp_new = CCPU_RAM_RDMEM(register_I); /* fetch imm real value */
SETA0 (register_A); /* store bit0 */
cmp_old = register_B; /* store old acc value */
register_B += cmp_new; /* do acc operation */
SETFC (register_B); /* store carry and extra */
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opAWDirg_A_AA (int opcode)
{
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
cmp_old = register_A;
register_A += cmp_new;
SETFC (register_A);
register_A &= 0x0FFF;
return state_AA;
}
CINESTATE opAWDirg_B_AA (int opcode)
{
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
cmp_old = register_B;
register_B += cmp_new;
SETFC (register_B);
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opSUBimm_A_AA (int opcode)
{
/*
* SUBtractions are negate-and-add instructions of the CCPU; what
* a pain in the ass.
*/
CINEWORD temp_word = opcode & 0x0F;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_A;
temp_word = (temp_word ^ 0xFFF) + 1; /* ones compliment */
register_A += temp_word; /* add */
SETFC (register_A); /* pick up top bits */
register_A &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBimm_B_AA (int opcode)
{
/*
* SUBtractions are negate-and-add instructions of the CCPU; what
* a pain in the ass.
*/
CINEWORD temp_word = opcode & 0x0F;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_B;
temp_word = (temp_word ^ 0xFFF) + 1; /* ones compliment */
register_B += temp_word; /* add */
SETFC (register_B); /* pick up top bits */
register_B &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBimmX_A_AA (int opcode)
{
CINEWORD temp_word = CCPU_FETCH (register_PC++); /* snag imm value */
cmp_new = temp_word; /* save cmp value */
SETA0 (register_A); /* store bit0 */
cmp_old = register_A; /* back up regA */
temp_word = (temp_word ^ 0xFFF) + 1; /* ones compliment */
register_A += temp_word; /* add */
SETFC (register_A); /* pick up top bits */
register_A &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBimmX_B_AA (int opcode)
{
CINEWORD temp_word = CCPU_FETCH (register_PC++); /* snag imm value */
cmp_new = temp_word; /* save cmp value */
SETA0 (register_A); /* store bit0 */
cmp_old = register_B; /* back up regA */
temp_word = (temp_word ^ 0xFFF) + 1; /* ones compliment */
register_B += temp_word; /* add */
SETFC (register_B); /* pick up top bits */
register_B &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBdir_A_AA (int opcode)
{
CINEWORD temp_word = opcode & 0x0F; /* fetch imm value */
register_I = (register_P << 4) + temp_word; /* set regI addr */
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
cmp_old = register_A;
temp_word = (cmp_new ^ 0xFFF) + 1; /* ones compliment */
register_A += temp_word; /* add */
SETFC (register_A); /* pick up top bits */
register_A &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBdir_B_AA (int opcode)
{
CINEWORD temp_word;
CINEBYTE temp_byte = opcode & 0x0F; /* fetch imm value */
register_I = (register_P << 4) + temp_byte; /* set regI addr */
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
cmp_old = register_B;
temp_word = (cmp_new ^ 0xFFF) + 1; /* ones compliment */
register_B += temp_word; /* add */
SETFC (register_B); /* pick up top bits */
register_B &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBirg_A_AA (int opcode)
{
CINEWORD temp_word;
/* sub [i] */
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
cmp_old = register_A;
temp_word = (cmp_new ^ 0xFFF) + 1; /* ones compliment */
register_A += temp_word; /* add */
SETFC (register_A); /* pick up top bits */
register_A &= 0x0FFF; /* mask final regA value */
return state_AA;
}
CINESTATE opSUBirg_B_AA (int opcode)
{
CINEWORD temp_word;
/* sub [i] */
cmp_new = CCPU_RAM_RDMEM(register_I);
SETA0 (register_A);
cmp_old = register_B;
temp_word = (cmp_new ^ 0xFFF) + 1; /* ones compliment */
register_B += temp_word; /* add */
SETFC (register_B); /* pick up top bits */
register_B &= 0x0FFF; /* mask final regA value */
return state_AA;
}
/* CMP dir */
CINESTATE opCMPdir_A_AA (int opcode)
{
/*
* compare direct mode; don't modify regs, just set carry flag or not.
*/
CINEWORD temp_word;
CINEBYTE temp_byte = opcode & 0x0F; /* obtain relative addr */
register_I = (register_P << 4) + temp_byte; /* build real addr */
temp_word = CCPU_RAM_RDMEM(register_I);
cmp_new = temp_word; /* new acc value */
SETA0 (register_A); /* backup bit0 */
cmp_old = register_A; /* backup old acc */
temp_word = (temp_word ^ 0xFFF) + 1; /* ones compliment */
temp_word += register_A;
SETFC (temp_word); /* pick up top bits */
return state_AA;
}
CINESTATE opCMPdir_B_AA (int opcode)
{
CINEWORD temp_word;
CINEBYTE temp_byte = opcode & 0x0F; /* obtain relative addr */
register_I = (register_P << 4) + temp_byte; /* build real addr */
temp_word = CCPU_RAM_RDMEM(register_I);
cmp_new = temp_word; /* new acc value */
SETA0 (register_A); /* backup bit0 */
cmp_old = register_B; /* backup old acc */
temp_word = (temp_word ^ 0xFFF) + 1; /* ones compliment */
temp_word += register_B;
SETFC (temp_word); /* pick up top bits */
return state_AA;
}
/* AND [i] */
CINESTATE opANDirg_A_AA (int opcode)
{
cmp_new = CCPU_RAM_RDMEM(register_I); /* new acc value */
SETA0 (register_A);
SETFC (register_A);
cmp_old = register_A;
register_A &= cmp_new;
return state_AA;
}
CINESTATE opANDirg_B_AA (int opcode)
{
cmp_new = CCPU_RAM_RDMEM(register_I); /* new acc value */
SETA0 (register_A);
SETFC (register_A);
cmp_old = register_B;
register_B &= cmp_new;
return state_AA;
}
/* LDJ imm */
CINESTATE opLDJimm_A_A (int opcode)
{
CINEBYTE temp_byte = CCPU_FETCH (register_PC++); /* upper part of address */
temp_byte = (temp_byte << 4) | /* Silly CCPU; Swap */
(temp_byte >> 4); /* nibbles */
/* put the upper 8 bits above the existing 4 bits */
register_J = (opcode & 0x0F) | (temp_byte << 4);
return state_A;
}
CINESTATE opLDJimm_B_BB (int opcode)
{
CINEBYTE temp_byte = CCPU_FETCH (register_PC++); /* upper part of address */
temp_byte = (temp_byte << 4) | /* Silly CCPU; Swap */
(temp_byte >> 4); /* nibbles */
/* put the upper 8 bits above the existing 4 bits */
register_J = (opcode & 0x0F) | (temp_byte << 4);
return state_BB;
}
/* LDJ irg */
CINESTATE opLDJirg_A_A (int opcode)
{
/* load J reg from value at last dir addr */
register_J = CCPU_RAM_RDMEM(register_I);
return state_A;
}
CINESTATE opLDJirg_B_BB (int opcode)
{
register_J = CCPU_RAM_RDMEM(register_I);
return state_BB;
}
/* LDP imm */
CINESTATE opLDPimm_A_A (int opcode)
{
/* load page register from immediate */
register_P = opcode & 0x0F; /* set page register */
return state_A;
}
CINESTATE opLDPimm_B_BB (int opcode)
{
/* load page register from immediate */
register_P = opcode & 0x0F; /* set page register */
return state_BB;
}
/* LDI dir */
CINESTATE opLDIdir_A_A (int opcode)
{
/* load regI directly .. */
CINEBYTE temp_byte = (register_P << 4) + /* get ram page ... */
(opcode & 0x0F); /* and imm half of ram addr.. */
register_I = CCPU_RAM_RDMEM(temp_byte) & 0xFF; /* set/mask new register_I */
return state_A;
}
CINESTATE opLDIdir_B_BB (int opcode)
{
CINEBYTE temp_byte = (register_P << 4) + /* get ram page ... */
(opcode & 0x0F); /* and imm half of ram addr.. */
register_I = CCPU_RAM_RDMEM(temp_byte) & 0xFF; /* set/mask new register_I */
return state_BB;
}
/* STA dir */
CINESTATE opSTAdir_A_A (int opcode)
{
CINEBYTE temp_byte = opcode & 0x0F; /* snag imm value */
register_I = (register_P << 4) + temp_byte; /* set I register */
CCPU_RAM_WRMEM(register_I, register_A); /* store acc to RAM */
return state_A;
}
CINESTATE opSTAdir_B_BB (int opcode)
{
CINEBYTE temp_byte = opcode & 0x0F; /* snag imm value */
register_I = (register_P << 4) + temp_byte; /* set I register */
CCPU_RAM_WRMEM(register_I, register_B); /* store acc to RAM */
return state_BB;
}
/* STA irg */
CINESTATE opSTAirg_A_A (int opcode)
{
/*
* STA into address specified in regI. Nice and easy :)
*/
CCPU_RAM_WRMEM(register_I, register_A); /* store acc */
return state_A;
}
CINESTATE opSTAirg_B_BB (int opcode)
{
CCPU_RAM_WRMEM(register_I, register_B); /* store acc */
return state_BB;
}
/* XLT */
CINESTATE opXLT_A_AA (int opcode)
{
/*
* XLT is weird; it loads the current accumulator with the bytevalue
* at ROM location pointed to by the accumulator; this allows the
* program to read the program itself..
* NOTE! Next opcode is *IGNORED!* because of a twisted side-effect
*/
cmp_new = CCPU_FETCH (((register_PC - 1) & 0xF000) + register_A); /* store new acc value */
SETA0 (register_A); /* store bit0 */
SETFC (register_A);
cmp_old = register_A; /* back up acc */
register_A = cmp_new; /* new acc value */
register_PC++; /* bump PC twice because XLT is fucked up */
return state_AA;
}
CINESTATE opXLT_B_AA (int opcode)
{
cmp_new = CCPU_FETCH (((register_PC - 1) & 0xF000) + register_B); /* store new acc value */
SETA0 (register_A); /* store bit0 */
SETFC (register_A);
cmp_old = register_B; /* back up acc */
register_B = cmp_new; /* new acc value */
register_PC++; /* bump PC twice because XLT is fucked up */
return state_AA;
}
/* MUL [i] */
CINESTATE opMULirg_A_AA (int opcode)
{
CINEBYTE temp_byte = opcode & 0xFF; /* (for ease and speed) */
CINEWORD temp_word = CCPU_RAM_RDMEM(register_I); /* pick up ram value */
cmp_new = temp_word;
temp_word <<= 4; /* shift into ADD position */
register_B <<= 4; /* get sign bit 15 */
register_B |= (register_A >> 8); /* bring in A high nibble */
register_A = ((register_A & 0xFF) << 8) | /* shift over 8 bits */
temp_byte; /* pick up opcode */
if (register_A & 0x100)
{ /* 1bit shifted out? */
register_A = (register_A >> 8) |
((register_B & 0xFF) << 8);
SETA0 (register_A & 0xFF); /* store bit0 */
register_A >>= 1;
register_A &= 0xFFF;
register_B = SAR(register_B,4);
cmp_old = register_B & 0x0F;
register_B = SAR(register_B,1);
register_B &= 0xFFF;
register_B += cmp_new;
SETFC (register_B);
register_B &= 0xFFF;
}
else
{
register_A = (register_A >> 8) | /* Bhigh | Alow */
((register_B & 0xFF) << 8);
temp_word = register_A & 0xFFF;
SETA0 (temp_word & 0xFF); /* store bit0 */
cmp_old = temp_word;
temp_word += cmp_new;
SETFC (temp_word);
register_A >>= 1;
register_A &= 0xFFF;
register_B = SAR(register_B,5);
register_B &= 0xFFF;
}
return state_AA;
}
CINESTATE opMULirg_B_AA (int opcode)
{
CINEWORD temp_word = CCPU_RAM_RDMEM(register_I);
cmp_new = temp_word;
cmp_old = register_B;
SETA0 (register_A & 0xFF);
register_B <<= 4;
register_B = SAR(register_B,5);
if (register_A & 0x01)
{
register_B += temp_word;
SETFC (register_B);
register_B &= 0x0FFF;
}
else
{
temp_word += register_B;
SETFC (temp_word);
}
return state_AA;
}
/* LSRe */
CINESTATE opLSRe_A_AA (int opcode)
{
/*
* EB; right shift pure; fill new bit with zero.
*/
CINEWORD temp_word = 0x0BEB;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_A;
temp_word += register_A;
SETFC (temp_word);
register_A >>= 1;
return state_AA;
}
CINESTATE opLSRe_B_AA (int opcode)
{
CINEWORD temp_word = 0x0BEB;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_B;
temp_word += register_B;
SETFC (temp_word);
register_B >>= 1;
return state_AA;
}
CINESTATE opLSRf_A_AA (int opcode)
{
UNFINISHED ("opLSRf 1\n");
return state_AA;
}
CINESTATE opLSRf_B_AA (int opcode)
{
UNFINISHED ("opLSRf 2\n");
return state_AA;
}
CINESTATE opLSLe_A_AA (int opcode)
{
/*
* EC; left shift pure; fill new bit with zero *
*/
CINEWORD temp_word = 0x0CEC;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_A;
temp_word += register_A;
SETFC (temp_word);
register_A <<= 1;
register_A &= 0x0FFF;
return state_AA;
}
CINESTATE opLSLe_B_AA (int opcode)
{
CINEWORD temp_word = 0x0CEC; /* data register */
cmp_new = temp_word; /* magic value */
SETA0 (register_A); /* back up bit0 */
cmp_old = register_B; /* store old acc */
temp_word += register_B; /* add to acc */
SETFC (temp_word); /* store carry flag */
register_B <<= 1; /* add regA to itself */
register_B &= 0xFFF; /* toss excess bits */
return state_AA;
}
CINESTATE opLSLf_A_AA (int opcode)
{
UNFINISHED ("opLSLf 1\n");
return state_AA;
}
CINESTATE opLSLf_B_AA (int opcode)
{
UNFINISHED ("opLSLf 2\n");
return state_AA;
}
CINESTATE opASRe_A_AA (int opcode)
{
/* agh! I dislike these silly 12bit processors :P */
cmp_new = 0x0DED;
SETA0 (register_A); /* store bit0 */
SETFC (register_A);
cmp_old = register_A;
register_A <<= 4; /* get sign bit */
register_A = SAR(register_A,5);
register_A &= 0xFFF;
return state_AA;
}
CINESTATE opASRe_B_AA (int opcode)
{
cmp_new = 0x0DED;
SETA0 (register_A);
SETFC (register_A);
cmp_old = register_B;
register_B <<= 4;
register_B = SAR(register_B,5);
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opASRf_A_AA (int opcode)
{
UNFINISHED ("opASRf 1\n");
return state_AA;
}
CINESTATE opASRf_B_AA (int opcode)
{
UNFINISHED ("opASRf 2\n");
return state_AA;
}
CINESTATE opASRDe_A_AA (int opcode)
{
/*
* Arithmetic shift right of D (A+B) .. B is high (sign bits).
* divide by 2, but leave the sign bit the same. (ie: 1010 -> 1001)
*/
CINEWORD temp_word = 0x0EEE;
CINEWORD temp_word_2;
cmp_new = temp_word; /* save new acc value */
SETA0 (register_A & 0xFF); /* save old accA bit0 */
cmp_old = register_A; /* save old acc */
temp_word += register_A;
SETFC (temp_word);
register_A <<= 4;
register_B <<= 4;
temp_word_2 = (register_B >> 4) << 15;
register_B = SAR(register_B,5);
register_A = (register_A >> 1) | temp_word_2;
register_A >>= 4;
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opASRDe_B_AA (int opcode)
{
CINEWORD temp_word = 0x0EEE;
cmp_new = temp_word;
SETA0 (register_A & 0xFF);
cmp_old = register_B;
temp_word += register_B;
SETFC (temp_word);
register_B <<= 4;
register_B = SAR(register_B,5);
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opASRDf_A_AA (int opcode)
{
UNFINISHED ("opASRDf 1\n");
return state_AA;
}
CINESTATE opASRDf_B_AA (int opcode)
{
UNFINISHED ("opASRDf 2\n");
return state_AA;
}
CINESTATE opLSLDe_A_AA (int opcode)
{
/* LSLDe -- Left shift through both accumulators; lossy in middle. */
CINEWORD temp_word = 0x0FEF;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_A;
temp_word += register_A;
SETFC (temp_word);
register_A <<= 1; /* logical shift left */
register_A &= 0xFFF;
register_B <<= 1;
register_B &= 0xFFF;
return state_AA;
}
CINESTATE opLSLDe_B_AA (int opcode)
{
UNFINISHED ("opLSLD 1\n");
return state_AA;
}
CINESTATE opLSLDf_A_AA (int opcode)
{
/* LSLDf */
CINEWORD temp_word = 0x0FFF;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_A;
temp_word += register_A;
SETFC (temp_word);
register_A <<= 1;
register_A &= 0x0FFF;
register_B <<= 1;
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opLSLDf_B_AA (int opcode)
{
/* not 'the same' as the A->AA version above */
CINEWORD temp_word = 0x0FFF;
cmp_new = temp_word;
SETA0 (register_A);
cmp_old = register_B;
temp_word += register_B;
SETFC (temp_word);
register_B <<= 1;
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opJMP_A_A (int opcode)
{
/*
* simple jump; change PC and continue..
*/
JMP();
return state_A;
}
CINESTATE opJMP_B_BB (int opcode)
{
JMP();
return state_BB;
}
CINESTATE opJEI_A_A (int opcode)
{
if (FromX & 0x800)
FromX |= 0xF000;
if (!(CCPU_READPORT (CCPU_PORT_IOOUTPUTS) & 0x80))
{
if ((CCPU_READPORT (CCPU_PORT_IN_JOYSTICKY) - (CINESWORD)FromX) < 0x800)
JMP();
}
else
{
if ((CCPU_READPORT (CCPU_PORT_IN_JOYSTICKX) - (CINESWORD)FromX) < 0x800)
JMP();
}
return state_A;
}
CINESTATE opJEI_B_BB (int opcode)
{
if (FromX & 0x800)
FromX |= 0xF000;
if (!(CCPU_READPORT (CCPU_PORT_IOOUTPUTS) & 0x80))
{
if ((CCPU_READPORT (CCPU_PORT_IN_JOYSTICKY) - (CINESWORD)FromX) < 0x800)
JMP();
}
else
{
if ((CCPU_READPORT (CCPU_PORT_IN_JOYSTICKX) - (CINESWORD)FromX) < 0x800)
JMP();
}
return state_BB;
}
CINESTATE opJEI_A_B (int opcode)
{
if (FromX & 0x800)
FromX |= 0xF000;
if (!(CCPU_READPORT (CCPU_PORT_IOOUTPUTS) & 0x80))
{
if ((CCPU_READPORT (CCPU_PORT_IN_JOYSTICKY) - (CINESWORD)FromX) < 0x800)
JMP();
}
else
{
if ((CCPU_READPORT (CCPU_PORT_IN_JOYSTICKX) - (CINESWORD)FromX) < 0x800)
JMP();
}
return state_B;
}
CINESTATE opJMI_A_A (int opcode)
{
/*
* previous instruction was not an ACC instruction, nor was the
* instruction twice back a USB, therefore minus flag test the
* current A-reg
*/
/* negative acc? */
if (register_A & 0x800)
JMP(); /* yes -- do jump */
return state_A;
}
CINESTATE opJMI_AA_A (int opcode)
{
/* previous acc negative? Jump if so... */
if (cmp_old & 0x800)
JMP();
return state_A;
}
CINESTATE opJMI_BB_A (int opcode)
{
if (register_B & 0x800)
JMP();
return state_A;
}
CINESTATE opJMI_B_BB (int opcode)
{
if (register_A & 0x800)
JMP();
return state_BB;
}
CINESTATE opJLT_A_A (int opcode)
{
/* jump if old acc equals new acc */
if (cmp_new < cmp_old)
JMP();
return state_A;
}
CINESTATE opJLT_B_BB (int opcode)
{
if (cmp_new < cmp_old)
JMP();
return state_BB;
}
CINESTATE opJEQ_A_A (int opcode)
{
/* jump if equal */
if (cmp_new == cmp_old)
JMP();
return state_A;
}
CINESTATE opJEQ_B_BB (int opcode)
{
if (cmp_new == cmp_old)
JMP();
return state_BB;
}
CINESTATE opJA0_A_A (int opcode)
{
if (acc_a0 & 0x01)
JMP();
return state_A;
}
CINESTATE opJA0_B_BB (int opcode)
{
if (acc_a0 & 0x01)
JMP();
return state_BB;
}
CINESTATE opJNC_A_A (int opcode)
{
if (!(GETFC() & 0xF0))
JMP(); /* no carry, so jump */
return state_A;
}
CINESTATE opJNC_B_BB (int opcode)
{
if (!(GETFC() & 0xF0))
JMP(); /* no carry, so jump */
return state_BB;
}
CINESTATE opJDR_A_A (int opcode)
{
/*
* Calculate number of cycles executed since
* last 'VDR' instruction, add two and use as
* cycle count, never branch
*/
return state_A;
}
CINESTATE opJDR_B_BB (int opcode)
{
/*
* Calculate number of cycles executed since
* last 'VDR' instruction, add two and use as
* cycle count, never branch
*/
return state_BB;
}
CINESTATE opNOP_A_A (int opcode)
{
return state_A;
}
CINESTATE opNOP_B_BB (int opcode)
{
return state_BB;
}
CINESTATE opJPP32_A_B (int opcode)
{
/*
* 00 = Offset 0000h
* 01 = Offset 1000h
* 02 = Offset 2000h
* 03 = Offset 3000h
* 04 = Offset 4000h
* 05 = Offset 5000h
* 06 = Offset 6000h
* 07 = Offset 7000h
*/
CINEWORD temp_word = (register_P & 0x07) << 12; /* rom offset */
register_PC = register_J + temp_word;
return state_B;
}
CINESTATE opJPP32_B_BB (int opcode)
{
CINEWORD temp_word = (register_P & 0x07) << 12; /* rom offset */
register_PC = register_J + temp_word;
return state_BB;
}
CINESTATE opJPP16_A_B (int opcode)
{
/*
* 00 = Offset 0000h
* 01 = Offset 1000h
* 02 = Offset 2000h
* 03 = Offset 3000h
*/
CINEWORD temp_word = (register_P & 0x03) << 12; /* rom offset */
register_PC = register_J + temp_word;
return state_B;
}
CINESTATE opJPP16_B_BB (int opcode)
{
CINEWORD temp_word = (register_P & 0x03) << 12; /* rom offset */
register_PC = register_J + temp_word;
return state_BB;
}
CINESTATE opJMP_A_B (int opcode)
{
JMP();
return state_B;
}
CINESTATE opJPP8_A_B (int opcode)
{
/*
* "long jump"; combine P and J to jump to a new far location (that can
* be more than 12 bits in address). After this jump, further jumps
* are local to this new page.
*/
CINEWORD temp_word = ((register_P & 0x03) - 1) << 12; /* rom offset */
register_PC = register_J + temp_word;
return state_B;
}
CINESTATE opJPP8_B_BB (int opcode)
{
CINEWORD temp_word = ((register_P & 0x03) - 1) << 12; /* rom offset */
register_PC = register_J + temp_word;
return state_BB;
}
CINESTATE opJMI_A_B (int opcode)
{
if (register_A & 0x800)
JMP();
return state_B;
}
CINESTATE opJMI_AA_B (int opcode)
{
UNFINISHED ("opJMI 3\n");
return state_B;
}
CINESTATE opJMI_BB_B (int opcode)
{
UNFINISHED ("opJMI 4\n");
return state_B;
}
CINESTATE opJLT_A_B (int opcode)
{
if (cmp_new < cmp_old)
JMP();
return state_B;
}
CINESTATE opJEQ_A_B (int opcode)
{
if (cmp_new == cmp_old)
JMP();
return state_B;
}
CINESTATE opJA0_A_B (int opcode)
{
if (GETA0() & 0x01)
JMP();
return state_B;
}
CINESTATE opJNC_A_B (int opcode)
{
if (!(GETFC() & 0x0F0))
JMP(); /* if no carry, jump */
return state_B;
}
CINESTATE opJDR_A_B (int opcode)
{
/* register_PC++; */
log_cb(RETRO_LOG_DEBUG, LOGPRE "The hell? No PC incrementing?\n");
return state_B;
}
/* NOP */
CINESTATE opNOP_A_B (int opcode)
{
return state_B;
}
CINESTATE opLLT_A_AA (int opcode)
{
CINEBYTE temp_byte = 0;
while (1)
{
CINEWORD temp_word = register_A >> 8; /* register_A's high bits */
temp_word &= 0x0A; /* only want PA11 and PA9 */
if (temp_word)
{
temp_word ^= 0x0A; /* flip the bits */
if (temp_word)
break; /* if not zero, mismatch found */
}
temp_word = register_B >> 8; /* regB's top bits */
temp_word &= 0x0A; /* only want SA11 and SA9 */
if (temp_word)
{
temp_word ^= 0x0A; /* flip bits */
if (temp_word)
break; /* if not zero, mismatch found */
}
register_A <<= 1; /* shift regA */
register_B <<= 1; /* shift regB */
temp_byte ++;
if (!temp_byte)
return state_AA;
/* try again */
}
vgShiftLength = temp_byte;
register_A &= 0x0FFF;
register_B &= 0x0FFF;
return state_AA;
}
CINESTATE opLLT_B_AA (int opcode)
{
UNFINISHED ("opLLT 1\n");
return state_AA;
}
CINESTATE opVIN_A_A (int opcode)
{
/* set the starting address of a vector */
FromX = register_A & 0xFFF; /* regA goes to x-coord */
FromY = register_B & 0xFFF; /* regB goes to y-coord */
return state_A;
}
CINESTATE opVIN_B_BB (int opcode)
{
FromX = register_A & 0xFFF; /* regA goes to x-coord */
FromY = register_B & 0xFFF; /* regB goes to y-coord */
return state_BB;
}
CINESTATE opWAI_A_A (int opcode)
{
/* wait for a tick on the watchdog */
bNewFrame = 1;
bailOut = TRUE;
return state;
}
CINESTATE opWAI_B_BB (int opcode)
{
bNewFrame = 1;
bailOut = TRUE;
return state;
}
CINESTATE opVDR_A_A (int opcode)
{
/* set ending points and draw the vector, or buffer for a later draw. */
int ToX = register_A & 0xFFF;
int ToY = register_B & 0xFFF;
/*
* shl 20, sar 20; this means that if the CCPU reg should be -ve,
* we should be negative as well.. sign extended.
*/
if (FromX & 0x800)
FromX |= 0xFFFFF000;
if (ToX & 0x800)
ToX |= 0xFFFFF000;
if (FromY & 0x800)
FromY |= 0xFFFFF000;
if (ToY & 0x800)
ToY |= 0xFFFFF000;
/* figure out the vector */
ToX -= FromX;
ToX = SAR(ToX,vgShiftLength);
ToX += FromX;
ToY -= FromY;
ToY = SAR(ToY,vgShiftLength);
ToY += FromY;
/* do orientation flipping, etc. */
/* NOTE: this has been removed on the assumption that the vector draw routine can do it all */
#if !RAW_VECTORS
if (bFlipX)
{
ToX = sdwGameXSize - ToX;
FromX = sdwGameXSize - FromX;
}
if (bFlipY)
{
ToY = sdwGameYSize - ToY;
FromY = sdwGameYSize - FromY;
}
FromX += sdwXOffset;
ToX += sdwXOffset;
FromY += sdwYOffset;
ToY += sdwYOffset;
/* check real coords */
if (bSwapXY)
{
CINEWORD temp_word;
temp_word = ToY;
ToY = ToX;
ToX = temp_word;
temp_word = FromY;
FromY = FromX;
FromX = temp_word;
}
#endif
/* render the line */
CinemaVectorData (FromX, FromY, ToX, ToY, vgColour);
return state_A;
}
CINESTATE opVDR_B_BB (int opcode)
{
UNFINISHED ("opVDR B 1\n");
return state_BB;
}
/*
* some code needs to be changed based on the machine or switches set.
* Instead of getting disorganized, I'll put the extra dispatchers
* here. The main dispatch loop jumps here, checks options, and
* redispatches to the actual opcode handlers.
*/
/* JPP series of opcodes */
CINESTATE tJPP_A_B (int opcode)
{
/* MSIZE -- 0 = 4k, 1 = 8k, 2 = 16k, 3 = 32k */
switch (ccpu_msize)
{
case CCPU_MEMSIZE_4K:
case CCPU_MEMSIZE_8K:
return opJPP8_A_B (opcode);
case CCPU_MEMSIZE_16K:
return opJPP16_A_B (opcode);
case CCPU_MEMSIZE_32K:
return opJPP32_A_B (opcode);
}
log_cb(RETRO_LOG_DEBUG, LOGPRE "Out of range JPP!\n");
return opJPP32_A_B (opcode);
}
CINESTATE tJPP_B_BB (int opcode)
{
/* MSIZE -- 0 = 4k, 1 = 8k, 2 = 16k, 3 = 32k */
switch (ccpu_msize)
{
case CCPU_MEMSIZE_4K:
case CCPU_MEMSIZE_8K:
return opJPP8_B_BB (opcode);
case CCPU_MEMSIZE_16K:
return opJPP16_B_BB (opcode);
case CCPU_MEMSIZE_32K:
return opJPP32_B_BB (opcode);
}
log_cb(RETRO_LOG_DEBUG, LOGPRE "Out of range JPP!\n");
return state;
}
/* JMI series of opcodes */
CINESTATE tJMI_A_B (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_A_B (opcode) : opJEI_A_B (opcode);
}
CINESTATE tJMI_A_A (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_A_A (opcode) : opJEI_A_A (opcode);
}
CINESTATE tJMI_AA_B (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_AA_B (opcode) : opJEI_AA_B (opcode);
}
CINESTATE tJMI_AA_A (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_AA_A (opcode) : opJEI_A_A (opcode);
}
CINESTATE tJMI_B_BB1 (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_B_BB (opcode) : opJEI_B_BB (opcode);
}
CINESTATE tJMI_BB_B (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_BB_B (opcode) : opJEI_A_B (opcode);
}
CINESTATE tJMI_BB_A (int opcode)
{
return (ccpu_jmi_dip) ? opJMI_BB_A (opcode) : opJEI_A_A (opcode);
}
/*
* OUT series of opcodes:
* ccpu_monitor can be one of:
* 1 -- 16-level colour
* 2 -- 64-level colour
* 3 -- War of the Worlds colour
* other -- bi-level
*/
CINESTATE tOUT_A_A (int opcode)
{
switch (ccpu_monitor)
{
case CCPU_MONITOR_16LEV:
return opOUT16_A_A (opcode);
case CCPU_MONITOR_64LEV:
return opOUT64_A_A (opcode);
case CCPU_MONITOR_WOWCOL:
return opOUTWW_A_A (opcode);
default:
return opOUTbi_A_A (opcode);
}
}
CINESTATE tOUT_B_BB (int opcode)
{
switch (ccpu_monitor)
{
case CCPU_MONITOR_16LEV:
return opOUT16_B_BB (opcode);
case CCPU_MONITOR_64LEV:
return opOUT64_B_BB (opcode);
case CCPU_MONITOR_WOWCOL:
return opOUTWW_B_BB (opcode);
default:
return opOUTbi_B_BB (opcode);
}
}
/* Reset C-CPU registers, flags, etc to default starting values
*/
void cineReset(void)
{
/* zero registers */
register_PC = 0;
register_A = 0;
register_B = 0;
register_I = 0;
register_J = 0;
register_P = 0;
FromX = 0;
FromY = 0;
register_T = 0;
/* zero flags */
flag_C = 0;
/* reset state */
state = state_A;
/* reset internal state */
cmp_old = 0;
cmp_new = 0;
SETA0 (0);
}
void cineSetJMI(int j)
{
ccpu_jmi_dip = j;
/*
if (ccpu_jmi_dip)
fprintf (stderr, "CCPU JMI Set: Yes.\n");
else
fprintf (stderr, "CCPU JMI Set: No.\n");
*/
}
void cineSetMSize(int m)
{
ccpu_msize = m;
/*
switch (m)
{
case 0:
fprintf (stderr, "CCPU Address Space: 4k\n");
break;
case 1:
fprintf (stderr, "CCPU Address Space: 8k\n");
break;
case 2:
fprintf (stderr, "CCPU Address Space: 16k\n");
break;
case 3:
fprintf (stderr, "CCPU Address Space: 32k\n");
break;
default:
fprintf (stderr, "CCPU Address Space: Error\n");
break;
}
*/
}
void cineSetMonitor(int m)
{
ccpu_monitor = m;
/*
switch (m)
{
case 1:
fprintf (stderr, "CCPU Monitor: 16-colour\n");
break;
case 2:
fprintf (stderr, "CCPU Monitor: 64-colour\n");
break;
case 3:
fprintf (stderr, "CCPU Monitor: War-of-the-Worlds-colour\n");
break;
default:
fprintf (stderr, "CCPU Monitor: bi-level-display\n");
break;
}
*/
}
void cSetContext(CONTEXTCCPU *c)
{
cmp_old = c -> accVal;
cmp_new = c -> cmpVal;
SETA0 (c -> pa0);
flag_C = c -> cFlag;
register_PC = c -> eRegPC;
register_A = c -> eRegA;
register_B = c -> eRegB;
register_I = c -> eRegI;
register_J = c -> eRegJ;
register_P = c -> eRegP;
state = (CINESTATE)c -> eCState;
}
void cGetContext(CONTEXTCCPU *c)
{
c -> accVal = cmp_old;
c -> cmpVal = cmp_new;
c -> pa0 = GETA0();
c -> cFlag = GETFC();
c -> eRegPC = register_PC;
c -> eRegA = register_A;
c -> eRegB = register_B;
c -> eRegI = register_I;
c -> eRegJ = register_J;
c -> eRegP = register_P;
c -> eCState = state;
}
| 24.083895 | 122 | 0.626884 | [
"render",
"vector"
] |
19129263d7c90a8868f0eed4bd3d9f373c67ae79 | 4,246 | h | C | ricochet/cl_dll/health.h | HLSources/HalfPayne | cc42f6ee19c23b36c4e9fd14e89181e222f1d27c | [
"Unlicense"
] | 27 | 2016-08-07T10:41:15.000Z | 2022-03-08T14:42:46.000Z | ricochet/cl_dll/health.h | HLSources/HalfPayne | cc42f6ee19c23b36c4e9fd14e89181e222f1d27c | [
"Unlicense"
] | null | null | null | ricochet/cl_dll/health.h | HLSources/HalfPayne | cc42f6ee19c23b36c4e9fd14e89181e222f1d27c | [
"Unlicense"
] | 5 | 2020-09-07T06:29:28.000Z | 2021-12-13T03:15:46.000Z | /***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#define DMG_IMAGE_LIFE 2 // seconds that image is up
#define DMG_IMAGE_POISON 0
#define DMG_IMAGE_ACID 1
#define DMG_IMAGE_COLD 2
#define DMG_IMAGE_DROWN 3
#define DMG_IMAGE_BURN 4
#define DMG_IMAGE_NERVE 5
#define DMG_IMAGE_RAD 6
#define DMG_IMAGE_SHOCK 7
//tf defines
#define DMG_IMAGE_CALTROP 8
#define DMG_IMAGE_TRANQ 9
#define DMG_IMAGE_CONCUSS 10
#define DMG_IMAGE_HALLUC 11
#define NUM_DMG_TYPES 12
// instant damage
#define DMG_GENERIC 0 // generic damage was done
#define DMG_CRUSH (1 << 0) // crushed by falling or moving object
#define DMG_BULLET (1 << 1) // shot
#define DMG_SLASH (1 << 2) // cut, clawed, stabbed
#define DMG_BURN (1 << 3) // heat burned
#define DMG_FREEZE (1 << 4) // frozen
#define DMG_FALL (1 << 5) // fell too far
#define DMG_BLAST (1 << 6) // explosive blast damage
#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt
#define DMG_SHOCK (1 << 8) // electric shock
#define DMG_SONIC (1 << 9) // sound pulse shockwave
#define DMG_ENERGYBEAM (1 << 10) // laser or other high energy beam
#define DMG_NEVERGIB (1 << 12) // with this bit OR'd in, no damage type will be able to gib victims upon death
#define DMG_ALWAYSGIB (1 << 13) // with this bit OR'd in, any damage type can be made to gib victims upon death.
// time-based damage
//mask off TF-specific stuff too
#define DMG_TIMEBASED (~(0xff003fff)) // mask for time-based damage
#define DMG_DROWN (1 << 14) // Drowning
#define DMG_FIRSTTIMEBASED DMG_DROWN
#define DMG_PARALYZE (1 << 15) // slows affected creature down
#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad
#define DMG_POISON (1 << 17) // blood poisioning
#define DMG_RADIATION (1 << 18) // radiation exposure
#define DMG_DROWNRECOVER (1 << 19) // drowning recovery
#define DMG_ACID (1 << 20) // toxic chemicals or acid burns
#define DMG_SLOWBURN (1 << 21) // in an oven
#define DMG_SLOWFREEZE (1 << 22) // in a subzero freezer
#define DMG_MORTAR (1 << 23) // Hit by air raid (done to distinguish grenade from mortar)
//TF ADDITIONS
#define DMG_IGNITE (1 << 24) // Players hit by this begin to burn
#define DMG_RADIUS_MAX (1 << 25) // Radius damage with this flag doesn't decrease over distance
#define DMG_RADIUS_QUAKE (1 << 26) // Radius damage is done like Quake. 1/2 damage at 1/2 radius.
#define DMG_IGNOREARMOR (1 << 27) // Damage ignores target's armor
#define DMG_AIMED (1 << 28) // Does Hit location damage
#define DMG_WALLPIERCING (1 << 29) // Blast Damages ents through walls
#define DMG_CALTROP (1<<30)
#define DMG_HALLUC (1<<31)
// TF Healing Additions for TakeHealth
#define DMG_IGNORE_MAXHEALTH DMG_IGNITE
// TF Redefines since we never use the originals
#define DMG_NAIL DMG_SLASH
#define DMG_NOT_SELF DMG_FREEZE
#define DMG_TRANQ DMG_MORTAR
#define DMG_CONCUSS DMG_SONIC
typedef struct
{
float fExpire;
float fBaseline;
int x, y;
} DAMAGE_IMAGE;
//
//-----------------------------------------------------
//
class CHudHealth: public CHudBase
{
public:
virtual int Init( void );
virtual int VidInit( void );
virtual int Draw(float fTime);
virtual void Reset( void );
int MsgFunc_Health(const char *pszName, int iSize, void *pbuf);
int MsgFunc_Damage(const char *pszName, int iSize, void *pbuf);
int m_iHealth;
int m_HUD_dmg_bio;
int m_HUD_cross;
float m_fAttackFront, m_fAttackRear, m_fAttackLeft, m_fAttackRight;
void GetPainColor( int &r, int &g, int &b );
float m_fFade;
int m_bitsDamage;
private:
SPRITE_HANDLE m_hSprite;
SPRITE_HANDLE m_hDamage;
DAMAGE_IMAGE m_dmg[NUM_DMG_TYPES];
int DrawPain(float fTime);
int DrawDamage(float fTime);
void CalcDamageDirection(vec3_t vecFrom);
void UpdateTiles(float fTime, long bits);
};
| 32.914729 | 113 | 0.713613 | [
"object"
] |
19158cb59101e0cddbc38acf4f68f77621948e55 | 55,979 | h | C | drivers/scsi/mpt3sas/mpt3sas_base.h | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/scsi/mpt3sas/mpt3sas_base.h | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/scsi/mpt3sas/mpt3sas_base.h | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | /*
* This is the Fusion MPT base driver providing common API layer interface
* for access to MPT (Message Passing Technology) firmware.
*
* This code is based on drivers/scsi/mpt3sas/mpt3sas_base.h
* Copyright (C) 2012-2014 LSI Corporation
* Copyright (C) 2013-2014 Avago Technologies
* (mailto: MPT-FusionLinux.pdl@avagotech.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* NO WARRANTY
* THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
* LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
* solely responsible for determining the appropriateness of using and
* distributing the Program and assumes all risks associated with its
* exercise of rights under this Agreement, including but not limited to
* the risks and costs of program errors, damage to or loss of data,
* programs or equipment, and unavailability or interruption of operations.
* DISCLAIMER OF LIABILITY
* NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
* HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#ifndef MPT3SAS_BASE_H_INCLUDED
#define MPT3SAS_BASE_H_INCLUDED
#include "mpi/mpi2_type.h"
#include "mpi/mpi2.h"
#include "mpi/mpi2_ioc.h"
#include "mpi/mpi2_cnfg.h"
#include "mpi/mpi2_init.h"
#include "mpi/mpi2_raid.h"
#include "mpi/mpi2_tool.h"
#include "mpi/mpi2_sas.h"
#include "mpi/mpi2_pci.h"
#include "mpi/mpi2_image.h"
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_transport_sas.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_eh.h>
#include <linux/pci.h>
#include <linux/poll.h>
#include "mpt3sas_debug.h"
#include "mpt3sas_trigger_diag.h"
/* driver versioning info */
#define MPT3SAS_DRIVER_NAME "mpt3sas"
#define MPT3SAS_AUTHOR "Avago Technologies <MPT-FusionLinux.pdl@avagotech.com>"
#define MPT3SAS_DESCRIPTION "LSI MPT Fusion SAS 3.0 Device Driver"
#define MPT3SAS_DRIVER_VERSION "27.102.00.00"
#define MPT3SAS_MAJOR_VERSION 27
#define MPT3SAS_MINOR_VERSION 102
#define MPT3SAS_BUILD_VERSION 0
#define MPT3SAS_RELEASE_VERSION 00
#define MPT2SAS_DRIVER_NAME "mpt2sas"
#define MPT2SAS_DESCRIPTION "LSI MPT Fusion SAS 2.0 Device Driver"
#define MPT2SAS_DRIVER_VERSION "20.102.00.00"
#define MPT2SAS_MAJOR_VERSION 20
#define MPT2SAS_MINOR_VERSION 102
#define MPT2SAS_BUILD_VERSION 0
#define MPT2SAS_RELEASE_VERSION 00
/*
* Set MPT3SAS_SG_DEPTH value based on user input.
*/
#define MPT_MAX_PHYS_SEGMENTS SG_CHUNK_SIZE
#define MPT_MIN_PHYS_SEGMENTS 16
#define MPT_KDUMP_MIN_PHYS_SEGMENTS 32
#define MCPU_MAX_CHAINS_PER_IO 3
#ifdef CONFIG_SCSI_MPT3SAS_MAX_SGE
#define MPT3SAS_SG_DEPTH CONFIG_SCSI_MPT3SAS_MAX_SGE
#else
#define MPT3SAS_SG_DEPTH MPT_MAX_PHYS_SEGMENTS
#endif
#ifdef CONFIG_SCSI_MPT2SAS_MAX_SGE
#define MPT2SAS_SG_DEPTH CONFIG_SCSI_MPT2SAS_MAX_SGE
#else
#define MPT2SAS_SG_DEPTH MPT_MAX_PHYS_SEGMENTS
#endif
/*
* Generic Defines
*/
#define MPT3SAS_SATA_QUEUE_DEPTH 32
#define MPT3SAS_SAS_QUEUE_DEPTH 254
#define MPT3SAS_RAID_QUEUE_DEPTH 128
#define MPT3SAS_KDUMP_SCSI_IO_DEPTH 200
#define MPT3SAS_RAID_MAX_SECTORS 8192
#define MPT3SAS_HOST_PAGE_SIZE_4K 12
#define MPT3SAS_NVME_QUEUE_DEPTH 128
#define MPT_NAME_LENGTH 32 /* generic length of strings */
#define MPT_STRING_LENGTH 64
#define MPI_FRAME_START_OFFSET 256
#define REPLY_FREE_POOL_SIZE 512 /*(32 maxcredix *4)*(4 times)*/
#define MPT_MAX_CALLBACKS 32
#define INTERNAL_CMDS_COUNT 10 /* reserved cmds */
/* reserved for issuing internally framed scsi io cmds */
#define INTERNAL_SCSIIO_CMDS_COUNT 3
#define MPI3_HIM_MASK 0xFFFFFFFF /* mask every bit*/
#define MPT3SAS_INVALID_DEVICE_HANDLE 0xFFFF
#define MAX_CHAIN_ELEMT_SZ 16
#define DEFAULT_NUM_FWCHAIN_ELEMTS 8
#define FW_IMG_HDR_READ_TIMEOUT 15
#define IOC_OPERATIONAL_WAIT_COUNT 10
/*
* NVMe defines
*/
#define NVME_PRP_SIZE 8 /* PRP size */
#define NVME_ERROR_RESPONSE_SIZE 16 /* Max NVME Error Response */
#define NVME_TASK_ABORT_MIN_TIMEOUT 6
#define NVME_TASK_ABORT_MAX_TIMEOUT 60
#define NVME_TASK_MNGT_CUSTOM_MASK (0x0010)
#define NVME_PRP_PAGE_SIZE 4096 /* Page size */
struct mpt3sas_nvme_cmd {
u8 rsvd[24];
__le64 prp1;
__le64 prp2;
};
/*
* logging format
*/
#define ioc_err(ioc, fmt, ...) \
pr_err("%s: " fmt, (ioc)->name, ##__VA_ARGS__)
#define ioc_notice(ioc, fmt, ...) \
pr_notice("%s: " fmt, (ioc)->name, ##__VA_ARGS__)
#define ioc_warn(ioc, fmt, ...) \
pr_warn("%s: " fmt, (ioc)->name, ##__VA_ARGS__)
#define ioc_info(ioc, fmt, ...) \
pr_info("%s: " fmt, (ioc)->name, ##__VA_ARGS__)
/*
* WarpDrive Specific Log codes
*/
#define MPT2_WARPDRIVE_LOGENTRY (0x8002)
#define MPT2_WARPDRIVE_LC_SSDT (0x41)
#define MPT2_WARPDRIVE_LC_SSDLW (0x43)
#define MPT2_WARPDRIVE_LC_SSDLF (0x44)
#define MPT2_WARPDRIVE_LC_BRMF (0x4D)
/*
* per target private data
*/
#define MPT_TARGET_FLAGS_RAID_COMPONENT 0x01
#define MPT_TARGET_FLAGS_VOLUME 0x02
#define MPT_TARGET_FLAGS_DELETED 0x04
#define MPT_TARGET_FASTPATH_IO 0x08
#define MPT_TARGET_FLAGS_PCIE_DEVICE 0x10
#define SAS2_PCI_DEVICE_B0_REVISION (0x01)
#define SAS3_PCI_DEVICE_C0_REVISION (0x02)
/* Atlas PCIe Switch Management Port */
#define MPI26_ATLAS_PCIe_SWITCH_DEVID (0x00B2)
/*
* Intel HBA branding
*/
#define MPT2SAS_INTEL_RMS25JB080_BRANDING \
"Intel(R) Integrated RAID Module RMS25JB080"
#define MPT2SAS_INTEL_RMS25JB040_BRANDING \
"Intel(R) Integrated RAID Module RMS25JB040"
#define MPT2SAS_INTEL_RMS25KB080_BRANDING \
"Intel(R) Integrated RAID Module RMS25KB080"
#define MPT2SAS_INTEL_RMS25KB040_BRANDING \
"Intel(R) Integrated RAID Module RMS25KB040"
#define MPT2SAS_INTEL_RMS25LB040_BRANDING \
"Intel(R) Integrated RAID Module RMS25LB040"
#define MPT2SAS_INTEL_RMS25LB080_BRANDING \
"Intel(R) Integrated RAID Module RMS25LB080"
#define MPT2SAS_INTEL_RMS2LL080_BRANDING \
"Intel Integrated RAID Module RMS2LL080"
#define MPT2SAS_INTEL_RMS2LL040_BRANDING \
"Intel Integrated RAID Module RMS2LL040"
#define MPT2SAS_INTEL_RS25GB008_BRANDING \
"Intel(R) RAID Controller RS25GB008"
#define MPT2SAS_INTEL_SSD910_BRANDING \
"Intel(R) SSD 910 Series"
#define MPT3SAS_INTEL_RMS3JC080_BRANDING \
"Intel(R) Integrated RAID Module RMS3JC080"
#define MPT3SAS_INTEL_RS3GC008_BRANDING \
"Intel(R) RAID Controller RS3GC008"
#define MPT3SAS_INTEL_RS3FC044_BRANDING \
"Intel(R) RAID Controller RS3FC044"
#define MPT3SAS_INTEL_RS3UC080_BRANDING \
"Intel(R) RAID Controller RS3UC080"
/*
* Intel HBA SSDIDs
*/
#define MPT2SAS_INTEL_RMS25JB080_SSDID 0x3516
#define MPT2SAS_INTEL_RMS25JB040_SSDID 0x3517
#define MPT2SAS_INTEL_RMS25KB080_SSDID 0x3518
#define MPT2SAS_INTEL_RMS25KB040_SSDID 0x3519
#define MPT2SAS_INTEL_RMS25LB040_SSDID 0x351A
#define MPT2SAS_INTEL_RMS25LB080_SSDID 0x351B
#define MPT2SAS_INTEL_RMS2LL080_SSDID 0x350E
#define MPT2SAS_INTEL_RMS2LL040_SSDID 0x350F
#define MPT2SAS_INTEL_RS25GB008_SSDID 0x3000
#define MPT2SAS_INTEL_SSD910_SSDID 0x3700
#define MPT3SAS_INTEL_RMS3JC080_SSDID 0x3521
#define MPT3SAS_INTEL_RS3GC008_SSDID 0x3522
#define MPT3SAS_INTEL_RS3FC044_SSDID 0x3523
#define MPT3SAS_INTEL_RS3UC080_SSDID 0x3524
/*
* Dell HBA branding
*/
#define MPT2SAS_DELL_BRANDING_SIZE 32
#define MPT2SAS_DELL_6GBPS_SAS_HBA_BRANDING "Dell 6Gbps SAS HBA"
#define MPT2SAS_DELL_PERC_H200_ADAPTER_BRANDING "Dell PERC H200 Adapter"
#define MPT2SAS_DELL_PERC_H200_INTEGRATED_BRANDING "Dell PERC H200 Integrated"
#define MPT2SAS_DELL_PERC_H200_MODULAR_BRANDING "Dell PERC H200 Modular"
#define MPT2SAS_DELL_PERC_H200_EMBEDDED_BRANDING "Dell PERC H200 Embedded"
#define MPT2SAS_DELL_PERC_H200_BRANDING "Dell PERC H200"
#define MPT2SAS_DELL_6GBPS_SAS_BRANDING "Dell 6Gbps SAS"
#define MPT3SAS_DELL_12G_HBA_BRANDING \
"Dell 12Gbps HBA"
/*
* Dell HBA SSDIDs
*/
#define MPT2SAS_DELL_6GBPS_SAS_HBA_SSDID 0x1F1C
#define MPT2SAS_DELL_PERC_H200_ADAPTER_SSDID 0x1F1D
#define MPT2SAS_DELL_PERC_H200_INTEGRATED_SSDID 0x1F1E
#define MPT2SAS_DELL_PERC_H200_MODULAR_SSDID 0x1F1F
#define MPT2SAS_DELL_PERC_H200_EMBEDDED_SSDID 0x1F20
#define MPT2SAS_DELL_PERC_H200_SSDID 0x1F21
#define MPT2SAS_DELL_6GBPS_SAS_SSDID 0x1F22
#define MPT3SAS_DELL_12G_HBA_SSDID 0x1F46
/*
* Cisco HBA branding
*/
#define MPT3SAS_CISCO_12G_8E_HBA_BRANDING \
"Cisco 9300-8E 12G SAS HBA"
#define MPT3SAS_CISCO_12G_8I_HBA_BRANDING \
"Cisco 9300-8i 12G SAS HBA"
#define MPT3SAS_CISCO_12G_AVILA_HBA_BRANDING \
"Cisco 12G Modular SAS Pass through Controller"
#define MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_BRANDING \
"UCS C3X60 12G SAS Pass through Controller"
/*
* Cisco HBA SSSDIDs
*/
#define MPT3SAS_CISCO_12G_8E_HBA_SSDID 0x14C
#define MPT3SAS_CISCO_12G_8I_HBA_SSDID 0x154
#define MPT3SAS_CISCO_12G_AVILA_HBA_SSDID 0x155
#define MPT3SAS_CISCO_12G_COLUSA_MEZZANINE_HBA_SSDID 0x156
/*
* status bits for ioc->diag_buffer_status
*/
#define MPT3_DIAG_BUFFER_IS_REGISTERED (0x01)
#define MPT3_DIAG_BUFFER_IS_RELEASED (0x02)
#define MPT3_DIAG_BUFFER_IS_DIAG_RESET (0x04)
/*
* HP HBA branding
*/
#define MPT2SAS_HP_3PAR_SSVID 0x1590
#define MPT2SAS_HP_2_4_INTERNAL_BRANDING \
"HP H220 Host Bus Adapter"
#define MPT2SAS_HP_2_4_EXTERNAL_BRANDING \
"HP H221 Host Bus Adapter"
#define MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_BRANDING \
"HP H222 Host Bus Adapter"
#define MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_BRANDING \
"HP H220i Host Bus Adapter"
#define MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_BRANDING \
"HP H210i Host Bus Adapter"
/*
* HO HBA SSDIDs
*/
#define MPT2SAS_HP_2_4_INTERNAL_SSDID 0x0041
#define MPT2SAS_HP_2_4_EXTERNAL_SSDID 0x0042
#define MPT2SAS_HP_1_4_INTERNAL_1_4_EXTERNAL_SSDID 0x0043
#define MPT2SAS_HP_EMBEDDED_2_4_INTERNAL_SSDID 0x0044
#define MPT2SAS_HP_DAUGHTER_2_4_INTERNAL_SSDID 0x0046
/*
* Combined Reply Queue constants,
* There are twelve Supplemental Reply Post Host Index Registers
* and each register is at offset 0x10 bytes from the previous one.
*/
#define MAX_COMBINED_MSIX_VECTORS(gen35) ((gen35 == 1) ? 16 : 8)
#define MPT3_SUP_REPLY_POST_HOST_INDEX_REG_COUNT_G3 12
#define MPT3_SUP_REPLY_POST_HOST_INDEX_REG_COUNT_G35 16
#define MPT3_SUP_REPLY_POST_HOST_INDEX_REG_OFFSET (0x10)
/* OEM Identifiers */
#define MFG10_OEM_ID_INVALID (0x00000000)
#define MFG10_OEM_ID_DELL (0x00000001)
#define MFG10_OEM_ID_FSC (0x00000002)
#define MFG10_OEM_ID_SUN (0x00000003)
#define MFG10_OEM_ID_IBM (0x00000004)
/* GENERIC Flags 0*/
#define MFG10_GF0_OCE_DISABLED (0x00000001)
#define MFG10_GF0_R1E_DRIVE_COUNT (0x00000002)
#define MFG10_GF0_R10_DISPLAY (0x00000004)
#define MFG10_GF0_SSD_DATA_SCRUB_DISABLE (0x00000008)
#define MFG10_GF0_SINGLE_DRIVE_R0 (0x00000010)
#define VIRTUAL_IO_FAILED_RETRY (0x32010081)
/* OEM Specific Flags will come from OEM specific header files */
struct Mpi2ManufacturingPage10_t {
MPI2_CONFIG_PAGE_HEADER Header; /* 00h */
U8 OEMIdentifier; /* 04h */
U8 Reserved1; /* 05h */
U16 Reserved2; /* 08h */
U32 Reserved3; /* 0Ch */
U32 GenericFlags0; /* 10h */
U32 GenericFlags1; /* 14h */
U32 Reserved4; /* 18h */
U32 OEMSpecificFlags0; /* 1Ch */
U32 OEMSpecificFlags1; /* 20h */
U32 Reserved5[18]; /* 24h - 60h*/
};
/* Miscellaneous options */
struct Mpi2ManufacturingPage11_t {
MPI2_CONFIG_PAGE_HEADER Header; /* 00h */
__le32 Reserved1; /* 04h */
u8 Reserved2; /* 08h */
u8 EEDPTagMode; /* 09h */
u8 Reserved3; /* 0Ah */
u8 Reserved4; /* 0Bh */
__le32 Reserved5[8]; /* 0Ch-2Ch */
u16 AddlFlags2; /* 2Ch */
u8 AddlFlags3; /* 2Eh */
u8 Reserved6; /* 2Fh */
__le32 Reserved7[7]; /* 30h - 4Bh */
u8 NVMeAbortTO; /* 4Ch */
u8 Reserved8; /* 4Dh */
u16 Reserved9; /* 4Eh */
__le32 Reserved10[4]; /* 50h - 60h */
};
/**
* struct MPT3SAS_TARGET - starget private hostdata
* @starget: starget object
* @sas_address: target sas address
* @raid_device: raid_device pointer to access volume data
* @handle: device handle
* @num_luns: number luns
* @flags: MPT_TARGET_FLAGS_XXX flags
* @deleted: target flaged for deletion
* @tm_busy: target is busy with TM request.
* @sas_dev: The sas_device associated with this target
* @pcie_dev: The pcie device associated with this target
*/
struct MPT3SAS_TARGET {
struct scsi_target *starget;
u64 sas_address;
struct _raid_device *raid_device;
u16 handle;
int num_luns;
u32 flags;
u8 deleted;
u8 tm_busy;
struct _sas_device *sas_dev;
struct _pcie_device *pcie_dev;
};
/*
* per device private data
*/
#define MPT_DEVICE_FLAGS_INIT 0x01
#define MFG_PAGE10_HIDE_SSDS_MASK (0x00000003)
#define MFG_PAGE10_HIDE_ALL_DISKS (0x00)
#define MFG_PAGE10_EXPOSE_ALL_DISKS (0x01)
#define MFG_PAGE10_HIDE_IF_VOL_PRESENT (0x02)
/**
* struct MPT3SAS_DEVICE - sdev private hostdata
* @sas_target: starget private hostdata
* @lun: lun number
* @flags: MPT_DEVICE_XXX flags
* @configured_lun: lun is configured
* @block: device is in SDEV_BLOCK state
* @tlr_snoop_check: flag used in determining whether to disable TLR
* @eedp_enable: eedp support enable bit
* @eedp_type: 0(type_1), 1(type_2), 2(type_3)
* @eedp_block_length: block size
* @ata_command_pending: SATL passthrough outstanding for device
*/
struct MPT3SAS_DEVICE {
struct MPT3SAS_TARGET *sas_target;
unsigned int lun;
u32 flags;
u8 configured_lun;
u8 block;
u8 tlr_snoop_check;
u8 ignore_delay_remove;
/* Iopriority Command Handling */
u8 ncq_prio_enable;
/*
* Bug workaround for SATL handling: the mpt2/3sas firmware
* doesn't return BUSY or TASK_SET_FULL for subsequent
* commands while a SATL pass through is in operation as the
* spec requires, it simply does nothing with them until the
* pass through completes, causing them possibly to timeout if
* the passthrough is a long executing command (like format or
* secure erase). This variable allows us to do the right
* thing while a SATL command is pending.
*/
unsigned long ata_command_pending;
};
#define MPT3_CMD_NOT_USED 0x8000 /* free */
#define MPT3_CMD_COMPLETE 0x0001 /* completed */
#define MPT3_CMD_PENDING 0x0002 /* pending */
#define MPT3_CMD_REPLY_VALID 0x0004 /* reply is valid */
#define MPT3_CMD_RESET 0x0008 /* host reset dropped the command */
/**
* struct _internal_cmd - internal commands struct
* @mutex: mutex
* @done: completion
* @reply: reply message pointer
* @sense: sense data
* @status: MPT3_CMD_XXX status
* @smid: system message id
*/
struct _internal_cmd {
struct mutex mutex;
struct completion done;
void *reply;
void *sense;
u16 status;
u16 smid;
};
/**
* struct _sas_device - attached device information
* @list: sas device list
* @starget: starget object
* @sas_address: device sas address
* @device_name: retrieved from the SAS IDENTIFY frame.
* @handle: device handle
* @sas_address_parent: sas address of parent expander or sas host
* @enclosure_handle: enclosure handle
* @enclosure_logical_id: enclosure logical identifier
* @volume_handle: volume handle (valid when hidden raid member)
* @volume_wwid: volume unique identifier
* @device_info: bitfield provides detailed info about the device
* @id: target id
* @channel: target channel
* @slot: number number
* @phy: phy identifier provided in sas device page 0
* @responding: used in _scsih_sas_device_mark_responding
* @fast_path: fast path feature enable bit
* @pfa_led_on: flag for PFA LED status
* @pend_sas_rphy_add: flag to check if device is in sas_rphy_add()
* addition routine.
* @chassis_slot: chassis slot
* @is_chassis_slot_valid: chassis slot valid or not
*/
struct _sas_device {
struct list_head list;
struct scsi_target *starget;
u64 sas_address;
u64 device_name;
u16 handle;
u64 sas_address_parent;
u16 enclosure_handle;
u64 enclosure_logical_id;
u16 volume_handle;
u64 volume_wwid;
u32 device_info;
int id;
int channel;
u16 slot;
u8 phy;
u8 responding;
u8 fast_path;
u8 pfa_led_on;
u8 pend_sas_rphy_add;
u8 enclosure_level;
u8 chassis_slot;
u8 is_chassis_slot_valid;
u8 connector_name[5];
struct kref refcount;
};
static inline void sas_device_get(struct _sas_device *s)
{
kref_get(&s->refcount);
}
static inline void sas_device_free(struct kref *r)
{
kfree(container_of(r, struct _sas_device, refcount));
}
static inline void sas_device_put(struct _sas_device *s)
{
kref_put(&s->refcount, sas_device_free);
}
/*
* struct _pcie_device - attached PCIe device information
* @list: pcie device list
* @starget: starget object
* @wwid: device WWID
* @handle: device handle
* @device_info: bitfield provides detailed info about the device
* @id: target id
* @channel: target channel
* @slot: slot number
* @port_num: port number
* @responding: used in _scsih_pcie_device_mark_responding
* @fast_path: fast path feature enable bit
* @nvme_mdts: MaximumDataTransferSize from PCIe Device Page 2 for
* NVMe device only
* @enclosure_handle: enclosure handle
* @enclosure_logical_id: enclosure logical identifier
* @enclosure_level: The level of device's enclosure from the controller
* @connector_name: ASCII value of the Connector's name
* @serial_number: pointer of serial number string allocated runtime
* @refcount: reference count for deletion
*/
struct _pcie_device {
struct list_head list;
struct scsi_target *starget;
u64 wwid;
u16 handle;
u32 device_info;
int id;
int channel;
u16 slot;
u8 port_num;
u8 responding;
u8 fast_path;
u32 nvme_mdts;
u16 enclosure_handle;
u64 enclosure_logical_id;
u8 enclosure_level;
u8 connector_name[4];
u8 *serial_number;
u8 reset_timeout;
struct kref refcount;
};
/**
* pcie_device_get - Increment the pcie device reference count
*
* @p: pcie_device object
*
* When ever this function called it will increment the
* reference count of the pcie device for which this function called.
*
*/
static inline void pcie_device_get(struct _pcie_device *p)
{
kref_get(&p->refcount);
}
/**
* pcie_device_free - Release the pcie device object
* @r - kref object
*
* Free's the pcie device object. It will be called when reference count
* reaches to zero.
*/
static inline void pcie_device_free(struct kref *r)
{
kfree(container_of(r, struct _pcie_device, refcount));
}
/**
* pcie_device_put - Decrement the pcie device reference count
*
* @p: pcie_device object
*
* When ever this function called it will decrement the
* reference count of the pcie device for which this function called.
*
* When refernce count reaches to Zero, this will call pcie_device_free to the
* pcie_device object.
*/
static inline void pcie_device_put(struct _pcie_device *p)
{
kref_put(&p->refcount, pcie_device_free);
}
/**
* struct _raid_device - raid volume link list
* @list: sas device list
* @starget: starget object
* @sdev: scsi device struct (volumes are single lun)
* @wwid: unique identifier for the volume
* @handle: device handle
* @block_size: Block size of the volume
* @id: target id
* @channel: target channel
* @volume_type: the raid level
* @device_info: bitfield provides detailed info about the hidden components
* @num_pds: number of hidden raid components
* @responding: used in _scsih_raid_device_mark_responding
* @percent_complete: resync percent complete
* @direct_io_enabled: Whether direct io to PDs are allowed or not
* @stripe_exponent: X where 2powX is the stripe sz in blocks
* @block_exponent: X where 2powX is the block sz in bytes
* @max_lba: Maximum number of LBA in the volume
* @stripe_sz: Stripe Size of the volume
* @device_info: Device info of the volume member disk
* @pd_handle: Array of handles of the physical drives for direct I/O in le16
*/
#define MPT_MAX_WARPDRIVE_PDS 8
struct _raid_device {
struct list_head list;
struct scsi_target *starget;
struct scsi_device *sdev;
u64 wwid;
u16 handle;
u16 block_sz;
int id;
int channel;
u8 volume_type;
u8 num_pds;
u8 responding;
u8 percent_complete;
u8 direct_io_enabled;
u8 stripe_exponent;
u8 block_exponent;
u64 max_lba;
u32 stripe_sz;
u32 device_info;
u16 pd_handle[MPT_MAX_WARPDRIVE_PDS];
};
/**
* struct _boot_device - boot device info
*
* @channel: sas, raid, or pcie channel
* @device: holds pointer for struct _sas_device, struct _raid_device or
* struct _pcie_device
*/
struct _boot_device {
int channel;
void *device;
};
/**
* struct _sas_port - wide/narrow sas port information
* @port_list: list of ports belonging to expander
* @num_phys: number of phys belonging to this port
* @remote_identify: attached device identification
* @rphy: sas transport rphy object
* @port: sas transport wide/narrow port object
* @phy_list: _sas_phy list objects belonging to this port
*/
struct _sas_port {
struct list_head port_list;
u8 num_phys;
struct sas_identify remote_identify;
struct sas_rphy *rphy;
struct sas_port *port;
struct list_head phy_list;
};
/**
* struct _sas_phy - phy information
* @port_siblings: list of phys belonging to a port
* @identify: phy identification
* @remote_identify: attached device identification
* @phy: sas transport phy object
* @phy_id: unique phy id
* @handle: device handle for this phy
* @attached_handle: device handle for attached device
* @phy_belongs_to_port: port has been created for this phy
*/
struct _sas_phy {
struct list_head port_siblings;
struct sas_identify identify;
struct sas_identify remote_identify;
struct sas_phy *phy;
u8 phy_id;
u16 handle;
u16 attached_handle;
u8 phy_belongs_to_port;
};
/**
* struct _sas_node - sas_host/expander information
* @list: list of expanders
* @parent_dev: parent device class
* @num_phys: number phys belonging to this sas_host/expander
* @sas_address: sas address of this sas_host/expander
* @handle: handle for this sas_host/expander
* @sas_address_parent: sas address of parent expander or sas host
* @enclosure_handle: handle for this a member of an enclosure
* @device_info: bitwise defining capabilities of this sas_host/expander
* @responding: used in _scsih_expander_device_mark_responding
* @phy: a list of phys that make up this sas_host/expander
* @sas_port_list: list of ports attached to this sas_host/expander
*/
struct _sas_node {
struct list_head list;
struct device *parent_dev;
u8 num_phys;
u64 sas_address;
u16 handle;
u64 sas_address_parent;
u16 enclosure_handle;
u64 enclosure_logical_id;
u8 responding;
struct _sas_phy *phy;
struct list_head sas_port_list;
};
/**
* struct _enclosure_node - enclosure information
* @list: list of enclosures
* @pg0: enclosure pg0;
*/
struct _enclosure_node {
struct list_head list;
Mpi2SasEnclosurePage0_t pg0;
};
/**
* enum reset_type - reset state
* @FORCE_BIG_HAMMER: issue diagnostic reset
* @SOFT_RESET: issue message_unit_reset, if fails to to big hammer
*/
enum reset_type {
FORCE_BIG_HAMMER,
SOFT_RESET,
};
/**
* struct pcie_sg_list - PCIe SGL buffer (contiguous per I/O)
* @pcie_sgl: PCIe native SGL for NVMe devices
* @pcie_sgl_dma: physical address
*/
struct pcie_sg_list {
void *pcie_sgl;
dma_addr_t pcie_sgl_dma;
};
/**
* struct chain_tracker - firmware chain tracker
* @chain_buffer: chain buffer
* @chain_buffer_dma: physical address
* @tracker_list: list of free request (ioc->free_chain_list)
*/
struct chain_tracker {
void *chain_buffer;
dma_addr_t chain_buffer_dma;
};
struct chain_lookup {
struct chain_tracker *chains_per_smid;
atomic_t chain_offset;
};
/**
* struct scsiio_tracker - scsi mf request tracker
* @smid: system message id
* @cb_idx: callback index
* @direct_io: To indicate whether I/O is direct (WARPDRIVE)
* @chain_list: list of associated firmware chain tracker
* @msix_io: IO's msix
*/
struct scsiio_tracker {
u16 smid;
u8 cb_idx;
u8 direct_io;
struct pcie_sg_list pcie_sg_list;
struct list_head chain_list;
u16 msix_io;
};
/**
* struct request_tracker - firmware request tracker
* @smid: system message id
* @cb_idx: callback index
* @tracker_list: list of free request (ioc->free_list)
*/
struct request_tracker {
u16 smid;
u8 cb_idx;
struct list_head tracker_list;
};
/**
* struct _tr_list - target reset list
* @handle: device handle
* @state: state machine
*/
struct _tr_list {
struct list_head list;
u16 handle;
u16 state;
};
/**
* struct _sc_list - delayed SAS_IO_UNIT_CONTROL message list
* @handle: device handle
*/
struct _sc_list {
struct list_head list;
u16 handle;
};
/**
* struct _event_ack_list - delayed event acknowledgment list
* @Event: Event ID
* @EventContext: used to track the event uniquely
*/
struct _event_ack_list {
struct list_head list;
U16 Event;
U32 EventContext;
};
/**
* struct adapter_reply_queue - the reply queue struct
* @ioc: per adapter object
* @msix_index: msix index into vector table
* @vector: irq vector
* @reply_post_host_index: head index in the pool where FW completes IO
* @reply_post_free: reply post base virt address
* @name: the name registered to request_irq()
* @busy: isr is actively processing replies on another cpu
* @list: this list
*/
struct adapter_reply_queue {
struct MPT3SAS_ADAPTER *ioc;
u8 msix_index;
u32 reply_post_host_index;
Mpi2ReplyDescriptorsUnion_t *reply_post_free;
char name[MPT_NAME_LENGTH];
atomic_t busy;
struct list_head list;
};
typedef void (*MPT_ADD_SGE)(void *paddr, u32 flags_length, dma_addr_t dma_addr);
/* SAS3.0 support */
typedef int (*MPT_BUILD_SG_SCMD)(struct MPT3SAS_ADAPTER *ioc,
struct scsi_cmnd *scmd, u16 smid, struct _pcie_device *pcie_device);
typedef void (*MPT_BUILD_SG)(struct MPT3SAS_ADAPTER *ioc, void *psge,
dma_addr_t data_out_dma, size_t data_out_sz,
dma_addr_t data_in_dma, size_t data_in_sz);
typedef void (*MPT_BUILD_ZERO_LEN_SGE)(struct MPT3SAS_ADAPTER *ioc,
void *paddr);
/* SAS3.5 support */
typedef void (*NVME_BUILD_PRP)(struct MPT3SAS_ADAPTER *ioc, u16 smid,
Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request,
dma_addr_t data_out_dma, size_t data_out_sz, dma_addr_t data_in_dma,
size_t data_in_sz);
/* To support atomic and non atomic descriptors*/
typedef void (*PUT_SMID_IO_FP_HIP) (struct MPT3SAS_ADAPTER *ioc, u16 smid,
u16 funcdep);
typedef void (*PUT_SMID_DEFAULT) (struct MPT3SAS_ADAPTER *ioc, u16 smid);
typedef u32 (*BASE_READ_REG) (const volatile void __iomem *addr);
/* IOC Facts and Port Facts converted from little endian to cpu */
union mpi3_version_union {
MPI2_VERSION_STRUCT Struct;
u32 Word;
};
struct mpt3sas_facts {
u16 MsgVersion;
u16 HeaderVersion;
u8 IOCNumber;
u8 VP_ID;
u8 VF_ID;
u16 IOCExceptions;
u16 IOCStatus;
u32 IOCLogInfo;
u8 MaxChainDepth;
u8 WhoInit;
u8 NumberOfPorts;
u8 MaxMSIxVectors;
u16 RequestCredit;
u16 ProductID;
u32 IOCCapabilities;
union mpi3_version_union FWVersion;
u16 IOCRequestFrameSize;
u16 IOCMaxChainSegmentSize;
u16 MaxInitiators;
u16 MaxTargets;
u16 MaxSasExpanders;
u16 MaxEnclosures;
u16 ProtocolFlags;
u16 HighPriorityCredit;
u16 MaxReplyDescriptorPostQueueDepth;
u8 ReplyFrameSize;
u8 MaxVolumes;
u16 MaxDevHandle;
u16 MaxPersistentEntries;
u16 MinDevHandle;
u8 CurrentHostPageSize;
};
struct mpt3sas_port_facts {
u8 PortNumber;
u8 VP_ID;
u8 VF_ID;
u8 PortType;
u16 MaxPostedCmdBuffers;
};
struct reply_post_struct {
Mpi2ReplyDescriptorsUnion_t *reply_post_free;
dma_addr_t reply_post_free_dma;
};
typedef void (*MPT3SAS_FLUSH_RUNNING_CMDS)(struct MPT3SAS_ADAPTER *ioc);
/**
* struct MPT3SAS_ADAPTER - per adapter struct
* @list: ioc_list
* @shost: shost object
* @id: unique adapter id
* @cpu_count: number online cpus
* @name: generic ioc string
* @tmp_string: tmp string used for logging
* @pdev: pci pdev object
* @pio_chip: physical io register space
* @chip: memory mapped register space
* @chip_phys: physical addrss prior to mapping
* @logging_level: see mpt3sas_debug.h
* @fwfault_debug: debuging FW timeouts
* @ir_firmware: IR firmware present
* @bars: bitmask of BAR's that must be configured
* @mask_interrupts: ignore interrupt
* @dma_mask: used to set the consistent dma mask
* @pci_access_mutex: Mutex to synchronize ioctl, sysfs show path and
* pci resource handling
* @fault_reset_work_q_name: fw fault work queue
* @fault_reset_work_q: ""
* @fault_reset_work: ""
* @firmware_event_name: fw event work queue
* @firmware_event_thread: ""
* @fw_event_lock:
* @fw_event_list: list of fw events
* @aen_event_read_flag: event log was read
* @broadcast_aen_busy: broadcast aen waiting to be serviced
* @shost_recovery: host reset in progress
* @ioc_reset_in_progress_lock:
* @ioc_link_reset_in_progress: phy/hard reset in progress
* @ignore_loginfos: ignore loginfos during task management
* @remove_host: flag for when driver unloads, to avoid sending dev resets
* @pci_error_recovery: flag to prevent ioc access until slot reset completes
* @wait_for_discovery_to_complete: flag set at driver load time when
* waiting on reporting devices
* @is_driver_loading: flag set at driver load time
* @port_enable_failed: flag set when port enable has failed
* @start_scan: flag set from scan_start callback, cleared from _mpt3sas_fw_work
* @start_scan_failed: means port enable failed, return's the ioc_status
* @msix_enable: flag indicating msix is enabled
* @msix_vector_count: number msix vectors
* @cpu_msix_table: table for mapping cpus to msix index
* @cpu_msix_table_sz: table size
* @schedule_dead_ioc_flush_running_cmds: callback to flush pending commands
* @scsi_io_cb_idx: shost generated commands
* @tm_cb_idx: task management commands
* @scsih_cb_idx: scsih internal commands
* @transport_cb_idx: transport internal commands
* @ctl_cb_idx: clt internal commands
* @base_cb_idx: base internal commands
* @config_cb_idx: base internal commands
* @tm_tr_cb_idx : device removal target reset handshake
* @tm_tr_volume_cb_idx : volume removal target reset
* @base_cmds:
* @transport_cmds:
* @scsih_cmds:
* @tm_cmds:
* @ctl_cmds:
* @config_cmds:
* @base_add_sg_single: handler for either 32/64 bit sgl's
* @event_type: bits indicating which events to log
* @event_context: unique id for each logged event
* @event_log: event log pointer
* @event_masks: events that are masked
* @facts: static facts data
* @pfacts: static port facts data
* @manu_pg0: static manufacturing page 0
* @manu_pg10: static manufacturing page 10
* @manu_pg11: static manufacturing page 11
* @bios_pg2: static bios page 2
* @bios_pg3: static bios page 3
* @ioc_pg8: static ioc page 8
* @iounit_pg0: static iounit page 0
* @iounit_pg1: static iounit page 1
* @iounit_pg8: static iounit page 8
* @sas_hba: sas host object
* @sas_expander_list: expander object list
* @enclosure_list: enclosure object list
* @sas_node_lock:
* @sas_device_list: sas device object list
* @sas_device_init_list: sas device object list (used only at init time)
* @sas_device_lock:
* @pcie_device_list: pcie device object list
* @pcie_device_init_list: pcie device object list (used only at init time)
* @pcie_device_lock:
* @io_missing_delay: time for IO completed by fw when PDR enabled
* @device_missing_delay: time for device missing by fw when PDR enabled
* @sas_id : used for setting volume target IDs
* @pcie_target_id: used for setting pcie target IDs
* @blocking_handles: bitmask used to identify which devices need blocking
* @pd_handles : bitmask for PD handles
* @pd_handles_sz : size of pd_handle bitmask
* @config_page_sz: config page size
* @config_page: reserve memory for config page payload
* @config_page_dma:
* @hba_queue_depth: hba request queue depth
* @sge_size: sg element size for either 32/64 bit
* @scsiio_depth: SCSI_IO queue depth
* @request_sz: per request frame size
* @request: pool of request frames
* @request_dma:
* @request_dma_sz:
* @scsi_lookup: firmware request tracker list
* @scsi_lookup_lock:
* @free_list: free list of request
* @pending_io_count:
* @reset_wq:
* @chain: pool of chains
* @chain_dma:
* @max_sges_in_main_message: number sg elements in main message
* @max_sges_in_chain_message: number sg elements per chain
* @chains_needed_per_io: max chains per io
* @chain_depth: total chains allocated
* @chain_segment_sz: gives the max number of
* SGEs accommodate on single chain buffer
* @hi_priority_smid:
* @hi_priority:
* @hi_priority_dma:
* @hi_priority_depth:
* @hpr_lookup:
* @hpr_free_list:
* @internal_smid:
* @internal:
* @internal_dma:
* @internal_depth:
* @internal_lookup:
* @internal_free_list:
* @sense: pool of sense
* @sense_dma:
* @sense_dma_pool:
* @reply_depth: hba reply queue depth:
* @reply_sz: per reply frame size:
* @reply: pool of replys:
* @reply_dma:
* @reply_dma_pool:
* @reply_free_queue_depth: reply free depth
* @reply_free: pool for reply free queue (32 bit addr)
* @reply_free_dma:
* @reply_free_dma_pool:
* @reply_free_host_index: tail index in pool to insert free replys
* @reply_post_queue_depth: reply post queue depth
* @reply_post_struct: struct for reply_post_free physical & virt address
* @rdpq_array_capable: FW supports multiple reply queue addresses in ioc_init
* @rdpq_array_enable: rdpq_array support is enabled in the driver
* @rdpq_array_enable_assigned: this ensures that rdpq_array_enable flag
* is assigned only ones
* @reply_queue_count: number of reply queue's
* @reply_queue_list: link list contaning the reply queue info
* @msix96_vector: 96 MSI-X vector support
* @replyPostRegisterIndex: index of next position in Reply Desc Post Queue
* @delayed_tr_list: target reset link list
* @delayed_tr_volume_list: volume target reset link list
* @delayed_sc_list:
* @delayed_event_ack_list:
* @temp_sensors_count: flag to carry the number of temperature sensors
* @pci_access_mutex: Mutex to synchronize ioctl,sysfs show path and
* pci resource handling. PCI resource freeing will lead to free
* vital hardware/memory resource, which might be in use by cli/sysfs
* path functions resulting in Null pointer reference followed by kernel
* crash. To avoid the above race condition we use mutex syncrhonization
* which ensures the syncrhonization between cli/sysfs_show path.
*/
struct MPT3SAS_ADAPTER {
struct list_head list;
struct Scsi_Host *shost;
u8 id;
int cpu_count;
char name[MPT_NAME_LENGTH];
char driver_name[MPT_NAME_LENGTH - 8];
char tmp_string[MPT_STRING_LENGTH];
struct pci_dev *pdev;
Mpi2SystemInterfaceRegs_t __iomem *chip;
phys_addr_t chip_phys;
int logging_level;
int fwfault_debug;
u8 ir_firmware;
int bars;
u8 mask_interrupts;
int dma_mask;
/* fw fault handler */
char fault_reset_work_q_name[20];
struct workqueue_struct *fault_reset_work_q;
struct delayed_work fault_reset_work;
/* fw event handler */
char firmware_event_name[20];
struct workqueue_struct *firmware_event_thread;
spinlock_t fw_event_lock;
struct list_head fw_event_list;
/* misc flags */
int aen_event_read_flag;
u8 broadcast_aen_busy;
u16 broadcast_aen_pending;
u8 shost_recovery;
u8 got_task_abort_from_ioctl;
struct mutex reset_in_progress_mutex;
spinlock_t ioc_reset_in_progress_lock;
u8 ioc_link_reset_in_progress;
u8 ignore_loginfos;
u8 remove_host;
u8 pci_error_recovery;
u8 wait_for_discovery_to_complete;
u8 is_driver_loading;
u8 port_enable_failed;
u8 start_scan;
u16 start_scan_failed;
u8 msix_enable;
u16 msix_vector_count;
u8 *cpu_msix_table;
u16 cpu_msix_table_sz;
resource_size_t __iomem **reply_post_host_index;
u32 ioc_reset_count;
MPT3SAS_FLUSH_RUNNING_CMDS schedule_dead_ioc_flush_running_cmds;
u32 non_operational_loop;
/* internal commands, callback index */
u8 scsi_io_cb_idx;
u8 tm_cb_idx;
u8 transport_cb_idx;
u8 scsih_cb_idx;
u8 ctl_cb_idx;
u8 base_cb_idx;
u8 port_enable_cb_idx;
u8 config_cb_idx;
u8 tm_tr_cb_idx;
u8 tm_tr_volume_cb_idx;
u8 tm_sas_control_cb_idx;
struct _internal_cmd base_cmds;
struct _internal_cmd port_enable_cmds;
struct _internal_cmd transport_cmds;
struct _internal_cmd scsih_cmds;
struct _internal_cmd tm_cmds;
struct _internal_cmd ctl_cmds;
struct _internal_cmd config_cmds;
MPT_ADD_SGE base_add_sg_single;
/* function ptr for either IEEE or MPI sg elements */
MPT_BUILD_SG_SCMD build_sg_scmd;
MPT_BUILD_SG build_sg;
MPT_BUILD_ZERO_LEN_SGE build_zero_len_sge;
u16 sge_size_ieee;
u16 hba_mpi_version_belonged;
/* function ptr for MPI sg elements only */
MPT_BUILD_SG build_sg_mpi;
MPT_BUILD_ZERO_LEN_SGE build_zero_len_sge_mpi;
/* function ptr for NVMe PRP elements only */
NVME_BUILD_PRP build_nvme_prp;
/* event log */
u32 event_type[MPI2_EVENT_NOTIFY_EVENTMASK_WORDS];
u32 event_context;
void *event_log;
u32 event_masks[MPI2_EVENT_NOTIFY_EVENTMASK_WORDS];
u8 tm_custom_handling;
u8 nvme_abort_timeout;
/* static config pages */
struct mpt3sas_facts facts;
struct mpt3sas_port_facts *pfacts;
Mpi2ManufacturingPage0_t manu_pg0;
struct Mpi2ManufacturingPage10_t manu_pg10;
struct Mpi2ManufacturingPage11_t manu_pg11;
Mpi2BiosPage2_t bios_pg2;
Mpi2BiosPage3_t bios_pg3;
Mpi2IOCPage8_t ioc_pg8;
Mpi2IOUnitPage0_t iounit_pg0;
Mpi2IOUnitPage1_t iounit_pg1;
Mpi2IOUnitPage8_t iounit_pg8;
struct _boot_device req_boot_device;
struct _boot_device req_alt_boot_device;
struct _boot_device current_boot_device;
/* sas hba, expander, and device list */
struct _sas_node sas_hba;
struct list_head sas_expander_list;
struct list_head enclosure_list;
spinlock_t sas_node_lock;
struct list_head sas_device_list;
struct list_head sas_device_init_list;
spinlock_t sas_device_lock;
struct list_head pcie_device_list;
struct list_head pcie_device_init_list;
spinlock_t pcie_device_lock;
struct list_head raid_device_list;
spinlock_t raid_device_lock;
u8 io_missing_delay;
u16 device_missing_delay;
int sas_id;
int pcie_target_id;
void *blocking_handles;
void *pd_handles;
u16 pd_handles_sz;
void *pend_os_device_add;
u16 pend_os_device_add_sz;
/* config page */
u16 config_page_sz;
void *config_page;
dma_addr_t config_page_dma;
void *config_vaddr;
/* scsiio request */
u16 hba_queue_depth;
u16 sge_size;
u16 scsiio_depth;
u16 request_sz;
u8 *request;
dma_addr_t request_dma;
u32 request_dma_sz;
struct pcie_sg_list *pcie_sg_lookup;
spinlock_t scsi_lookup_lock;
int pending_io_count;
wait_queue_head_t reset_wq;
/* PCIe SGL */
struct dma_pool *pcie_sgl_dma_pool;
/* Host Page Size */
u32 page_size;
/* chain */
struct chain_lookup *chain_lookup;
struct list_head free_chain_list;
struct dma_pool *chain_dma_pool;
ulong chain_pages;
u16 max_sges_in_main_message;
u16 max_sges_in_chain_message;
u16 chains_needed_per_io;
u32 chain_depth;
u16 chain_segment_sz;
u16 chains_per_prp_buffer;
/* hi-priority queue */
u16 hi_priority_smid;
u8 *hi_priority;
dma_addr_t hi_priority_dma;
u16 hi_priority_depth;
struct request_tracker *hpr_lookup;
struct list_head hpr_free_list;
/* internal queue */
u16 internal_smid;
u8 *internal;
dma_addr_t internal_dma;
u16 internal_depth;
struct request_tracker *internal_lookup;
struct list_head internal_free_list;
/* sense */
u8 *sense;
dma_addr_t sense_dma;
struct dma_pool *sense_dma_pool;
/* reply */
u16 reply_sz;
u8 *reply;
dma_addr_t reply_dma;
u32 reply_dma_max_address;
u32 reply_dma_min_address;
struct dma_pool *reply_dma_pool;
/* reply free queue */
u16 reply_free_queue_depth;
__le32 *reply_free;
dma_addr_t reply_free_dma;
struct dma_pool *reply_free_dma_pool;
u32 reply_free_host_index;
/* reply post queue */
u16 reply_post_queue_depth;
struct reply_post_struct *reply_post;
u8 rdpq_array_capable;
u8 rdpq_array_enable;
u8 rdpq_array_enable_assigned;
struct dma_pool *reply_post_free_dma_pool;
struct dma_pool *reply_post_free_array_dma_pool;
Mpi2IOCInitRDPQArrayEntry *reply_post_free_array;
dma_addr_t reply_post_free_array_dma;
u8 reply_queue_count;
struct list_head reply_queue_list;
u8 combined_reply_queue;
u8 combined_reply_index_count;
/* reply post register index */
resource_size_t **replyPostRegisterIndex;
struct list_head delayed_tr_list;
struct list_head delayed_tr_volume_list;
struct list_head delayed_sc_list;
struct list_head delayed_event_ack_list;
u8 temp_sensors_count;
struct mutex pci_access_mutex;
/* diag buffer support */
u8 *diag_buffer[MPI2_DIAG_BUF_TYPE_COUNT];
u32 diag_buffer_sz[MPI2_DIAG_BUF_TYPE_COUNT];
dma_addr_t diag_buffer_dma[MPI2_DIAG_BUF_TYPE_COUNT];
u8 diag_buffer_status[MPI2_DIAG_BUF_TYPE_COUNT];
u32 unique_id[MPI2_DIAG_BUF_TYPE_COUNT];
u32 product_specific[MPI2_DIAG_BUF_TYPE_COUNT][23];
u32 diagnostic_flags[MPI2_DIAG_BUF_TYPE_COUNT];
u32 ring_buffer_offset;
u32 ring_buffer_sz;
u8 is_warpdrive;
u8 is_mcpu_endpoint;
u8 hide_ir_msg;
u8 mfg_pg10_hide_flag;
u8 hide_drives;
spinlock_t diag_trigger_lock;
u8 diag_trigger_active;
BASE_READ_REG base_readl;
struct SL_WH_MASTER_TRIGGER_T diag_trigger_master;
struct SL_WH_EVENT_TRIGGERS_T diag_trigger_event;
struct SL_WH_SCSI_TRIGGERS_T diag_trigger_scsi;
struct SL_WH_MPI_TRIGGERS_T diag_trigger_mpi;
void *device_remove_in_progress;
u16 device_remove_in_progress_sz;
u8 is_gen35_ioc;
u8 is_aero_ioc;
PUT_SMID_IO_FP_HIP put_smid_scsi_io;
};
typedef u8 (*MPT_CALLBACK)(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
u32 reply);
/* base shared API */
extern struct list_head mpt3sas_ioc_list;
extern char driver_name[MPT_NAME_LENGTH];
/* spinlock on list operations over IOCs
* Case: when multiple warpdrive cards(IOCs) are in use
* Each IOC will added to the ioc list structure on initialization.
* Watchdog threads run at regular intervals to check IOC for any
* fault conditions which will trigger the dead_ioc thread to
* deallocate pci resource, resulting deleting the IOC netry from list,
* this deletion need to protected by spinlock to enusre that
* ioc removal is syncrhonized, if not synchronized it might lead to
* list_del corruption as the ioc list is traversed in cli path.
*/
extern spinlock_t gioc_lock;
void mpt3sas_base_start_watchdog(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_base_stop_watchdog(struct MPT3SAS_ADAPTER *ioc);
int mpt3sas_base_attach(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_base_detach(struct MPT3SAS_ADAPTER *ioc);
int mpt3sas_base_map_resources(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_base_free_resources(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_free_enclosure_list(struct MPT3SAS_ADAPTER *ioc);
int mpt3sas_base_hard_reset_handler(struct MPT3SAS_ADAPTER *ioc,
enum reset_type type);
void *mpt3sas_base_get_msg_frame(struct MPT3SAS_ADAPTER *ioc, u16 smid);
void *mpt3sas_base_get_sense_buffer(struct MPT3SAS_ADAPTER *ioc, u16 smid);
__le32 mpt3sas_base_get_sense_buffer_dma(struct MPT3SAS_ADAPTER *ioc,
u16 smid);
void *mpt3sas_base_get_pcie_sgl(struct MPT3SAS_ADAPTER *ioc, u16 smid);
dma_addr_t mpt3sas_base_get_pcie_sgl_dma(struct MPT3SAS_ADAPTER *ioc, u16 smid);
void mpt3sas_base_sync_reply_irqs(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_base_put_smid_fast_path(struct MPT3SAS_ADAPTER *ioc, u16 smid,
u16 handle);
void mpt3sas_base_put_smid_hi_priority(struct MPT3SAS_ADAPTER *ioc, u16 smid,
u16 msix_task);
void mpt3sas_base_put_smid_nvme_encap(struct MPT3SAS_ADAPTER *ioc, u16 smid);
void mpt3sas_base_put_smid_default(struct MPT3SAS_ADAPTER *ioc, u16 smid);
/* hi-priority queue */
u16 mpt3sas_base_get_smid_hpr(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx);
u16 mpt3sas_base_get_smid_scsiio(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx,
struct scsi_cmnd *scmd);
void mpt3sas_base_clear_st(struct MPT3SAS_ADAPTER *ioc,
struct scsiio_tracker *st);
u16 mpt3sas_base_get_smid(struct MPT3SAS_ADAPTER *ioc, u8 cb_idx);
void mpt3sas_base_free_smid(struct MPT3SAS_ADAPTER *ioc, u16 smid);
void mpt3sas_base_initialize_callback_handler(void);
u8 mpt3sas_base_register_callback_handler(MPT_CALLBACK cb_func);
void mpt3sas_base_release_callback_handler(u8 cb_idx);
u8 mpt3sas_base_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
u32 reply);
u8 mpt3sas_port_enable_done(struct MPT3SAS_ADAPTER *ioc, u16 smid,
u8 msix_index, u32 reply);
void *mpt3sas_base_get_reply_virt_addr(struct MPT3SAS_ADAPTER *ioc,
u32 phys_addr);
u32 mpt3sas_base_get_iocstate(struct MPT3SAS_ADAPTER *ioc, int cooked);
void mpt3sas_base_fault_info(struct MPT3SAS_ADAPTER *ioc , u16 fault_code);
int mpt3sas_base_sas_iounit_control(struct MPT3SAS_ADAPTER *ioc,
Mpi2SasIoUnitControlReply_t *mpi_reply,
Mpi2SasIoUnitControlRequest_t *mpi_request);
int mpt3sas_base_scsi_enclosure_processor(struct MPT3SAS_ADAPTER *ioc,
Mpi2SepReply_t *mpi_reply, Mpi2SepRequest_t *mpi_request);
void mpt3sas_base_validate_event_type(struct MPT3SAS_ADAPTER *ioc,
u32 *event_type);
void mpt3sas_halt_firmware(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_base_update_missing_delay(struct MPT3SAS_ADAPTER *ioc,
u16 device_missing_delay, u8 io_missing_delay);
int mpt3sas_port_enable(struct MPT3SAS_ADAPTER *ioc);
void
mpt3sas_wait_for_commands_to_complete(struct MPT3SAS_ADAPTER *ioc);
u8 mpt3sas_base_check_cmd_timeout(struct MPT3SAS_ADAPTER *ioc,
u8 status, void *mpi_request, int sz);
int mpt3sas_wait_for_ioc(struct MPT3SAS_ADAPTER *ioc, int wait_count);
/* scsih shared API */
struct scsi_cmnd *mpt3sas_scsih_scsi_lookup_get(struct MPT3SAS_ADAPTER *ioc,
u16 smid);
u8 mpt3sas_scsih_event_callback(struct MPT3SAS_ADAPTER *ioc, u8 msix_index,
u32 reply);
void mpt3sas_scsih_pre_reset_handler(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_scsih_after_reset_handler(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_scsih_reset_done_handler(struct MPT3SAS_ADAPTER *ioc);
int mpt3sas_scsih_issue_tm(struct MPT3SAS_ADAPTER *ioc, u16 handle, u64 lun,
u8 type, u16 smid_task, u16 msix_task, u8 timeout, u8 tr_method);
int mpt3sas_scsih_issue_locked_tm(struct MPT3SAS_ADAPTER *ioc, u16 handle,
u64 lun, u8 type, u16 smid_task, u16 msix_task,
u8 timeout, u8 tr_method);
void mpt3sas_scsih_set_tm_flag(struct MPT3SAS_ADAPTER *ioc, u16 handle);
void mpt3sas_scsih_clear_tm_flag(struct MPT3SAS_ADAPTER *ioc, u16 handle);
void mpt3sas_expander_remove(struct MPT3SAS_ADAPTER *ioc, u64 sas_address);
void mpt3sas_device_remove_by_sas_address(struct MPT3SAS_ADAPTER *ioc,
u64 sas_address);
u8 mpt3sas_check_for_pending_internal_cmds(struct MPT3SAS_ADAPTER *ioc,
u16 smid);
struct _sas_node *mpt3sas_scsih_expander_find_by_handle(
struct MPT3SAS_ADAPTER *ioc, u16 handle);
struct _sas_node *mpt3sas_scsih_expander_find_by_sas_address(
struct MPT3SAS_ADAPTER *ioc, u64 sas_address);
struct _sas_device *mpt3sas_get_sdev_by_addr(
struct MPT3SAS_ADAPTER *ioc, u64 sas_address);
struct _sas_device *__mpt3sas_get_sdev_by_addr(
struct MPT3SAS_ADAPTER *ioc, u64 sas_address);
struct _sas_device *mpt3sas_get_sdev_by_handle(struct MPT3SAS_ADAPTER *ioc,
u16 handle);
struct _pcie_device *mpt3sas_get_pdev_by_handle(struct MPT3SAS_ADAPTER *ioc,
u16 handle);
void mpt3sas_port_enable_complete(struct MPT3SAS_ADAPTER *ioc);
struct _raid_device *
mpt3sas_raid_device_find_by_handle(struct MPT3SAS_ADAPTER *ioc, u16 handle);
/* config shared API */
u8 mpt3sas_config_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
u32 reply);
int mpt3sas_config_get_number_hba_phys(struct MPT3SAS_ADAPTER *ioc,
u8 *num_phys);
int mpt3sas_config_get_manufacturing_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2ManufacturingPage0_t *config_page);
int mpt3sas_config_get_manufacturing_pg7(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2ManufacturingPage7_t *config_page,
u16 sz);
int mpt3sas_config_get_manufacturing_pg10(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply,
struct Mpi2ManufacturingPage10_t *config_page);
int mpt3sas_config_get_manufacturing_pg11(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply,
struct Mpi2ManufacturingPage11_t *config_page);
int mpt3sas_config_set_manufacturing_pg11(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply,
struct Mpi2ManufacturingPage11_t *config_page);
int mpt3sas_config_get_bios_pg2(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2BiosPage2_t *config_page);
int mpt3sas_config_get_bios_pg3(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2BiosPage3_t *config_page);
int mpt3sas_config_get_iounit_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2IOUnitPage0_t *config_page);
int mpt3sas_config_get_sas_device_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2SasDevicePage0_t *config_page,
u32 form, u32 handle);
int mpt3sas_config_get_sas_device_pg1(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2SasDevicePage1_t *config_page,
u32 form, u32 handle);
int mpt3sas_config_get_pcie_device_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi26PCIeDevicePage0_t *config_page,
u32 form, u32 handle);
int mpt3sas_config_get_pcie_device_pg2(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi26PCIeDevicePage2_t *config_page,
u32 form, u32 handle);
int mpt3sas_config_get_sas_iounit_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2SasIOUnitPage0_t *config_page,
u16 sz);
int mpt3sas_config_get_iounit_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2IOUnitPage1_t *config_page);
int mpt3sas_config_get_iounit_pg3(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2IOUnitPage3_t *config_page, u16 sz);
int mpt3sas_config_set_iounit_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2IOUnitPage1_t *config_page);
int mpt3sas_config_get_iounit_pg8(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2IOUnitPage8_t *config_page);
int mpt3sas_config_get_sas_iounit_pg1(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2SasIOUnitPage1_t *config_page,
u16 sz);
int mpt3sas_config_set_sas_iounit_pg1(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2SasIOUnitPage1_t *config_page,
u16 sz);
int mpt3sas_config_get_ioc_pg8(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2IOCPage8_t *config_page);
int mpt3sas_config_get_expander_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2ExpanderPage0_t *config_page,
u32 form, u32 handle);
int mpt3sas_config_get_expander_pg1(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2ExpanderPage1_t *config_page,
u32 phy_number, u16 handle);
int mpt3sas_config_get_enclosure_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2SasEnclosurePage0_t *config_page,
u32 form, u32 handle);
int mpt3sas_config_get_phy_pg0(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2SasPhyPage0_t *config_page, u32 phy_number);
int mpt3sas_config_get_phy_pg1(struct MPT3SAS_ADAPTER *ioc, Mpi2ConfigReply_t
*mpi_reply, Mpi2SasPhyPage1_t *config_page, u32 phy_number);
int mpt3sas_config_get_raid_volume_pg1(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2RaidVolPage1_t *config_page, u32 form,
u32 handle);
int mpt3sas_config_get_number_pds(struct MPT3SAS_ADAPTER *ioc, u16 handle,
u8 *num_pds);
int mpt3sas_config_get_raid_volume_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2RaidVolPage0_t *config_page, u32 form,
u32 handle, u16 sz);
int mpt3sas_config_get_phys_disk_pg0(struct MPT3SAS_ADAPTER *ioc,
Mpi2ConfigReply_t *mpi_reply, Mpi2RaidPhysDiskPage0_t *config_page,
u32 form, u32 form_specific);
int mpt3sas_config_get_volume_handle(struct MPT3SAS_ADAPTER *ioc, u16 pd_handle,
u16 *volume_handle);
int mpt3sas_config_get_volume_wwid(struct MPT3SAS_ADAPTER *ioc,
u16 volume_handle, u64 *wwid);
/* ctl shared API */
extern struct device_attribute *mpt3sas_host_attrs[];
extern struct device_attribute *mpt3sas_dev_attrs[];
void mpt3sas_ctl_init(ushort hbas_to_enumerate);
void mpt3sas_ctl_exit(ushort hbas_to_enumerate);
u8 mpt3sas_ctl_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
u32 reply);
void mpt3sas_ctl_pre_reset_handler(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_ctl_after_reset_handler(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_ctl_reset_done_handler(struct MPT3SAS_ADAPTER *ioc);
u8 mpt3sas_ctl_event_callback(struct MPT3SAS_ADAPTER *ioc,
u8 msix_index, u32 reply);
void mpt3sas_ctl_add_to_event_log(struct MPT3SAS_ADAPTER *ioc,
Mpi2EventNotificationReply_t *mpi_reply);
void mpt3sas_enable_diag_buffer(struct MPT3SAS_ADAPTER *ioc,
u8 bits_to_register);
int mpt3sas_send_diag_release(struct MPT3SAS_ADAPTER *ioc, u8 buffer_type,
u8 *issue_reset);
/* transport shared API */
extern struct scsi_transport_template *mpt3sas_transport_template;
u8 mpt3sas_transport_done(struct MPT3SAS_ADAPTER *ioc, u16 smid, u8 msix_index,
u32 reply);
struct _sas_port *mpt3sas_transport_port_add(struct MPT3SAS_ADAPTER *ioc,
u16 handle, u64 sas_address);
void mpt3sas_transport_port_remove(struct MPT3SAS_ADAPTER *ioc, u64 sas_address,
u64 sas_address_parent);
int mpt3sas_transport_add_host_phy(struct MPT3SAS_ADAPTER *ioc, struct _sas_phy
*mpt3sas_phy, Mpi2SasPhyPage0_t phy_pg0, struct device *parent_dev);
int mpt3sas_transport_add_expander_phy(struct MPT3SAS_ADAPTER *ioc,
struct _sas_phy *mpt3sas_phy, Mpi2ExpanderPage1_t expander_pg1,
struct device *parent_dev);
void mpt3sas_transport_update_links(struct MPT3SAS_ADAPTER *ioc,
u64 sas_address, u16 handle, u8 phy_number, u8 link_rate);
extern struct sas_function_template mpt3sas_transport_functions;
extern struct scsi_transport_template *mpt3sas_transport_template;
/* trigger data externs */
void mpt3sas_send_trigger_data_event(struct MPT3SAS_ADAPTER *ioc,
struct SL_WH_TRIGGERS_EVENT_DATA_T *event_data);
void mpt3sas_process_trigger_data(struct MPT3SAS_ADAPTER *ioc,
struct SL_WH_TRIGGERS_EVENT_DATA_T *event_data);
void mpt3sas_trigger_master(struct MPT3SAS_ADAPTER *ioc,
u32 tigger_bitmask);
void mpt3sas_trigger_event(struct MPT3SAS_ADAPTER *ioc, u16 event,
u16 log_entry_qualifier);
void mpt3sas_trigger_scsi(struct MPT3SAS_ADAPTER *ioc, u8 sense_key,
u8 asc, u8 ascq);
void mpt3sas_trigger_mpi(struct MPT3SAS_ADAPTER *ioc, u16 ioc_status,
u32 loginfo);
/* warpdrive APIs */
u8 mpt3sas_get_num_volumes(struct MPT3SAS_ADAPTER *ioc);
void mpt3sas_init_warpdrive_properties(struct MPT3SAS_ADAPTER *ioc,
struct _raid_device *raid_device);
void
mpt3sas_setup_direct_io(struct MPT3SAS_ADAPTER *ioc, struct scsi_cmnd *scmd,
struct _raid_device *raid_device, Mpi25SCSIIORequest_t *mpi_request);
/* NCQ Prio Handling Check */
bool scsih_ncq_prio_supp(struct scsi_device *sdev);
#endif /* MPT3SAS_BASE_H_INCLUDED */
| 33.084515 | 80 | 0.785027 | [
"object",
"vector"
] |
1915a4b57947989e5340bbd0ee8c664d1190607a | 95,108 | h | C | inspire_itk/source/common/itkImageProcessingTools.h | MIDA-group/inspire | 6786372bdd282afe5c47951e6893ce58e8ebfb7f | [
"MIT"
] | 4 | 2020-12-15T13:17:45.000Z | 2021-11-04T01:10:09.000Z | inspire_itk/source/common/itkImageProcessingTools.h | MIDA-group/inspire | 6786372bdd282afe5c47951e6893ce58e8ebfb7f | [
"MIT"
] | 1 | 2022-03-17T02:57:56.000Z | 2022-03-17T02:57:57.000Z | inspire_itk/source/common/itkImageProcessingTools.h | MIDA-group/inspire | 6786372bdd282afe5c47951e6893ce58e8ebfb7f | [
"MIT"
] | null | null | null |
#ifndef ITK_IMAGE_PROCESSING_TOOLS_H
#define ITK_IMAGE_PROCESSING_TOOLS_H
#include "itkVersion.h"
#include "itkPoint.h"
#include "itkImage.h"
#include "itkSmartPointer.h"
#include "itkImageRegionIterator.h"
#include "itkNumericTraits.h"
#include "itkCovariantVector.h"
#include "itkImageDuplicator.h"
#include "itkCastImageFilter.h"
#include "itkClampImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkShiftScaleImageFilter.h"
#include "itkResampleImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkStatisticsImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkHistogramMatchingImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkAbsoluteValueDifferenceImageFilter.h"
#include "itkChangeInformationImageFilter.h"
#include <itkLabelOverlapMeasuresImageFilter.h>
#include "itkAdditiveGaussianNoiseImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkMedianImageFilter.h"
#include "itkCSVArray2DFileReader.h"
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include <itkChangeInformationImageFilter.h>
#include "itkMultiplyImageFilter.h"
#include <algorithm>
#include "minicsv.h"
// Transforms
#include "itkAffineTransform.h"
#include "itkIdentityTransform.h"
#include "itkCompositeTransform.h"
#include "itkTranslationTransform.h"
#include "itkTransformFactory.h"
// Interpolation headers
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkBSplineInterpolateImageFunction.h"
#include "itkChangeInformationImageFilter.h"
template <typename ImageType>
typename ImageType::Pointer RemoveDirectionInformation(typename ImageType::Pointer image)
{
using FilterType = itk::ChangeInformationImageFilter<ImageType>;
using FilterPointer = typename FilterType::Pointer;
FilterPointer filter = FilterType::New();
filter->SetInput(image);
/*
typename ImageType::PointType origin;
for (unsigned int i = 0; i < ImageType::ImageDimension; ++i)
{
origin[i] = 0;
}
filter->SetOutputOrigin(origin);
filter->ChangeOriginOn();
*/
auto rot = image->GetDirection();
rot.SetIdentity();
filter->SetOutputDirection(rot);
filter->ChangeDirectionOn();
filter->Update();
auto result = filter->GetOutput();
result->SetRequestedRegion(result->GetLargestPossibleRegion());
result->SetBufferedRegion(result->GetLargestPossibleRegion());
return result;
}
namespace itk
{
template <typename Src, typename Dest>
inline itk::SmartPointer<Dest> CastSmartPointer(itk::SmartPointer<Src> ptr)
{
itk::SmartPointer<Dest> result = itk::SmartPointer<Dest>((Dest *)ptr.GetPointer());
return result;
}
template <typename TInputImage, typename TOutputImage>
inline typename TOutputImage::Pointer CastImage(
typename TInputImage::Pointer inputImage)
{
typedef itk::ClampImageFilter<TInputImage, TOutputImage> CastFilter;
typedef typename CastFilter::Pointer CastFilterPointer;
CastFilterPointer castFilter = CastFilter::New();
castFilter->SetInput(inputImage);
castFilter->Update();
return castFilter->GetOutput();
}
template <typename ImagePixelType, unsigned int Dim>
typename itk::Image<ImagePixelType, Dim>::Pointer ConvertImageToIntegerFormat(typename itk::Image<double, Dim>::Pointer image)
{
typedef double ValueType;
typedef itk::Image<double, Dim> ImageType;
typedef itk::Image<ImagePixelType, Dim> ImageUType;
typedef itk::ShiftScaleImageFilter<ImageType, ImageType> RescaleFilter;
typedef typename RescaleFilter::Pointer RescaleFilterPointer;
typedef itk::ClampImageFilter<ImageType, ImageUType> CastFilter;
typedef typename CastFilter::Pointer CastFilterPointer;
ValueType minVal = (ValueType)itk::NumericTraits<ImagePixelType>::min();
ValueType maxVal = (ValueType)itk::NumericTraits<ImagePixelType>::max();//+0.9999999999;
ValueType span = (maxVal - minVal);
ValueType halfInt = (itk::NumericTraits<ValueType>::One / 2);
RescaleFilterPointer rescaleFilter = RescaleFilter::New();
rescaleFilter->SetInput(image);
rescaleFilter->SetShift(0);
//rescaleFilter->SetShift((halfInt / span) + minVal);
rescaleFilter->SetScale(span);
rescaleFilter->Update();
CastFilterPointer castFilter = CastFilter::New();
castFilter->SetInput(rescaleFilter->GetOutput());
castFilter->Update();
return castFilter->GetOutput();
}
template <typename ImagePixelType, unsigned int Dim>
typename itk::Image<ImagePixelType, Dim>::Pointer ConvertImageF32ToIntegerFormat(typename itk::Image<float, Dim>::Pointer image)
{
typename itk::Image<double, Dim>::Pointer casted = CastImage<itk::Image<float, Dim>, itk::Image<double, Dim> >(image);
return ConvertImageToIntegerFormat<ImagePixelType, Dim>(casted);
/*
typedef itk::CastImageFilter<itk::Image<double, Dim>, itk::Image<float, Dim> > CastFilter;
typedef typename CastFilter::Pointer CastFilterPointer;
CastFilterPointer castFilter = CastFilter::New();
castFilter->SetInput(image);
castFilter->Update();
return ConvertImageToIntegerFormat(castFilter->GetOutput());*/
}
template <typename ImagePixelType, unsigned int Dim>
typename itk::Image<double, Dim>::Pointer ConvertImageFromIntegerFormat(
typename itk::Image<ImagePixelType, Dim>::Pointer image)
{
typedef double ValueType;
typedef itk::Image<double, Dim> ImageType;
typedef itk::Image<ImagePixelType, Dim> ImageUType;
typedef itk::CastImageFilter<ImageUType, ImageType> CastFilter;
typedef typename CastFilter::Pointer CastFilterPointer;
typedef itk::ShiftScaleImageFilter<ImageType, ImageType> RescaleFilter;
typedef typename RescaleFilter::Pointer RescaleFilterPointer;
CastFilterPointer castFilter = CastFilter::New();
castFilter->SetInput(image);
castFilter->Update();
ValueType minVal = (ValueType)itk::NumericTraits<ImagePixelType>::min();
ValueType maxVal = (ValueType)itk::NumericTraits<ImagePixelType>::max();
ValueType span = (maxVal - minVal);
RescaleFilterPointer rescaleFilter = RescaleFilter::New();
rescaleFilter->SetInput(castFilter->GetOutput());
rescaleFilter->SetShift(-minVal);
rescaleFilter->SetScale(itk::NumericTraits<ValueType>::One / span);
rescaleFilter->Update();
return rescaleFilter->GetOutput();
}
template <typename ImageType>
inline void PrintStatistics(
typename ImageType::Pointer image,
std::string name)
{
typedef itk::StatisticsImageFilter<ImageType> StatisticsImageFilterType;
typename StatisticsImageFilterType::Pointer statisticsImageFilter = StatisticsImageFilterType::New();
statisticsImageFilter->SetInput(image);
statisticsImageFilter->Update();
std::cout << "--- Image " << name << " statistics ---";
std::cout << "Origin: " << image->GetLargestPossibleRegion().GetIndex() << std::endl;
std::cout << "Size: " << image->GetLargestPossibleRegion().GetSize() << std::endl;
std::cout << "Spacing: " << image->GetSpacing() << std::endl;
std::cout << "Direction:" << image->GetDirection() << std::endl;
std::cout << "Mean: " << statisticsImageFilter->GetMean() << std::endl;
std::cout << "Std. Dev: " << statisticsImageFilter->GetSigma() << std::endl;
std::cout << "Min: " << statisticsImageFilter->GetMinimum() << std::endl;
std::cout << "Max: " << statisticsImageFilter->GetMaximum() << std::endl;
}
template <typename PixelType, unsigned int Dim>
inline typename itk::Image<PixelType, Dim - 1>::Pointer ExtractSlice(
typename itk::Image<PixelType, Dim>::Pointer image,
unsigned int dim,
int ind)
{
typedef itk::Image<PixelType, Dim> InputImageType;
typedef itk::Image<PixelType, Dim - 1> OutputImageType;
typedef itk::ExtractImageFilter<InputImageType, OutputImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
auto region = image->GetLargestPossibleRegion();
typedef typename InputImageType::IndexType IndexType;
typedef typename InputImageType::SizeType SizeType;
IndexType index = region.GetIndex();
SizeType size = region.GetSize();
index[dim] = ind;
size[dim] = 0;
region.SetIndex(index);
region.SetSize(size);
FilterPointer filter = FilterType::New();
filter->SetExtractionRegion(region);
filter->SetInput(image);
filter->SetDirectionCollapseToIdentity(); // This is required.
filter->Update();
return filter->GetOutput();
}
template <typename T>
void VectorToCSV(const char *path, std::vector<T> &values)
{
FILE *f = fopen(path, "wb");
for (size_t i = 0; i < values.size(); ++i)
{
if (i > 0)
fprintf(f, ",");
fprintf(f, "%.7f", values[i]);
}
fclose(f);
}
template <typename ValueType, unsigned int Dim>
class IPT
{
public:
typedef itk::Image<ValueType, Dim> ImageType;
typedef typename ImageType::Pointer ImagePointer;
typedef itk::Image<unsigned char, Dim> ImageU8Type;
typedef typename ImageU8Type::Pointer ImageU8Pointer;
typedef itk::Image<unsigned short, Dim> ImageU16Type;
typedef typename ImageU16Type::Pointer ImageU16Pointer;
typedef itk::Image<unsigned short, Dim> LabelImageType;
typedef typename LabelImageType::Pointer LabelImagePointer;
typedef typename itk::Image<bool, Dim> BinaryImageType;
typedef typename BinaryImageType::Pointer BinaryImagePointer;
typedef typename ImageType::PointType PointType;
typedef typename ImageType::PointValueType PointValueType;
typedef std::vector<PointType> PointSetType;
typedef typename ImageType::RegionType RegionType;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef itk::Vector<PointValueType, Dim> VectorType;
typedef itk::CovariantVector<PointValueType, Dim> CovariantVectorType;
typedef itk::Transform<PointValueType, Dim, Dim> BaseTransformType;
typedef typename BaseTransformType::Pointer BaseTransformPointer;
typedef itk::CompositeTransform<PointValueType, Dim> CompositeTransformType;
typedef typename CompositeTransformType::Pointer CompositeTransformPointer;
//
// Routines for computing image sizes and centers.
//
static SizeType GetImageSize(
ImagePointer image)
{
RegionType region = image->GetLargestPossibleRegion();
SizeType size = region.GetSize();
return size;
}
private:
template <typename SourceType, typename DestType>
static DestType MakeVT(
SourceType src)
{
DestType result;
for (unsigned int i = 0; i < Dim; ++i)
{
result[i] = src[i];
}
return result;
}
public:
//
//
// Routines for creating vector-equivalent classes (VectorType, CovariantVectorType, PointType, SizeType, ...)
//
//
static VectorType MakeVector(
const PointValueType *p)
{
return MakeVT<const PointValueType *, VectorType>(p);
}
static VectorType MakeVector(
CovariantVectorType v)
{
return MakeVT<CovariantVectorType, VectorType>(v);
}
static VectorType MakeVector(
PointType v)
{
return MakeVT<PointType, VectorType>(v);
}
static CovariantVectorType MakeCovariantVector(
const PointValueType *p)
{
return MakeVT<const PointValueType *, CovariantVectorType>(p);
}
static CovariantVectorType MakeCovariantVector(
PointType p)
{
return MakeVT<PointType, CovariantVectorType>(p);
}
static CovariantVectorType MakeCovariantVector(
VectorType p)
{
return MakeVT<VectorType, CovariantVectorType>(p);
}
static PointType MakePoint(
const PointValueType *p)
{
return MakeVT<const PointValueType *, PointType>(p);
}
static VectorType ReLUVector(
VectorType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
if (v[i] < 0)
v[i] = 0;
}
return v;
}
static CovariantVectorType ReLUCovariantVector(
CovariantVectorType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
if (v[i] < 0)
v[i] = 0;
}
return v;
}
static PointType ReLUPoint(
PointType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
if (v[i] < 0)
v[i] = 0;
}
return v;
}
static VectorType RoundVector(
VectorType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = static_cast<PointValueType>(itk::Math::Round<long long, PointValueType>(v[i]));
}
return v;
}
static CovariantVectorType RoundCovariantVector(
CovariantVectorType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = static_cast<PointValueType>(itk::Math::Round<long long, PointValueType>(v[i]));
}
return v;
}
static PointType RoundPoint(
PointType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = static_cast<PointValueType>(itk::Math::Round<long long, PointValueType>(v[i]));
}
return v;
}
static VectorType AbsVector(
VectorType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = itk::Math::abs(v[i]);
}
return v;
}
static CovariantVectorType AbsCovariantVector(
CovariantVectorType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = itk::Math::abs(v[i]);
}
return v;
}
static PointType AbsPoint(
PointType v)
{
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = itk::Math::abs(v[i]);
}
return v;
}
static SizeType MakeSize(
CovariantVectorType v)
{
SizeType result;
for (size_t i = 0; i < Dim; ++i)
{
result[i] = itk::Math::ceil(v[i]); //1 + static_cast<itk::SizeValueType>(v[i]);
}
return result;
}
static SizeType MakeSize(
VectorType v)
{
SizeType result;
for (size_t i = 0; i < Dim; ++i)
{
result[i] = itk::Math::ceil(v[i]); //1 + static_cast<itk::SizeValueType>(v[i]);
}
return result;
}
static PointType ComputeImageCenter(
ImagePointer image,
CovariantVectorType offset,
bool considerSpacing)
{
PointType result;
RegionType region = image->GetLargestPossibleRegion();
SpacingType spacing = image->GetSpacing();
IndexType index = region.GetIndex();
SizeType size = region.GetSize();
if (considerSpacing)
{
for (unsigned int i = 0; i < Dim; ++i)
{
result[i] = (double)(index[i] + spacing[i] * size[i] * 0.5 + offset[i]);
}
}
else
{
for (unsigned int i = 0; i < Dim; ++i)
{
result[i] = (double)(index[i] + size[i] * 0.5 + offset[i]);
}
}
return result;
}
static PointType ComputeImageCenter(
ImagePointer image,
bool considerSpacing)
{
CovariantVectorType offset;
offset.Fill(0.0);
return ComputeImageCenter(image, offset, considerSpacing);
}
static PointValueType ComputeImageDiagonalSize(
ImagePointer image,
bool considerSpacing)
{
PointValueType result = 0;
typename itk::Image<ValueType, Dim>::RegionType region = image->GetLargestPossibleRegion();
typename itk::Image<ValueType, Dim>::SizeType size = region.GetSize();
if (considerSpacing)
{
for (unsigned int i = 0; i < Dim; ++i)
{
PointValueType sideLength = size[i] * image->GetSpacing()[i];
result += itk::Math::sqr(static_cast<PointValueType>(sideLength));
}
}
else
{
for (unsigned int i = 0; i < Dim; ++i)
{
result += itk::Math::sqr(static_cast<PointValueType>(size[i]));
}
}
return sqrt(result);
}
//
// Routines for image creation / duplication.
//
static ImagePointer ConstantImage(ValueType c, SizeType sz)
{
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::RegionType RegionType;
RegionType region;
IndexType index;
index.Fill(0);
region.SetIndex(index);
region.SetSize(sz);
ImagePointer image = ImageType::New();
image->SetRegions(region);
image->Allocate(false);
image->FillBuffer(c);
return image;
}
static ImagePointer ZeroImage(SizeType sz)
{
return ConstantImage(0, sz);
}
static PointType ImageGeometricalCenterPoint(
ImagePointer image)
{
const typename ImageType::RegionType & region =
image->GetLargestPossibleRegion();
const typename ImageType::IndexType & index =
region.GetIndex();
const typename ImageType::SizeType & size =
region.GetSize();
PointType point;
typedef typename PointType::ValueType CoordRepType;
typedef ContinuousIndex< CoordRepType,
Dim > ContinuousIndexType;
typedef typename ContinuousIndexType::ValueType ContinuousIndexValueType;
ContinuousIndexType centerIndex;
for ( unsigned int k = 0; k < Dim; k++ )
{
centerIndex[k] =
static_cast< ContinuousIndexValueType >( index[k] )
+ static_cast< ContinuousIndexValueType >( size[k] - 1 ) / 2.0;
}
image->TransformContinuousIndexToPhysicalPoint(centerIndex, point);
return point;
}
static ImagePointer CircularMask(
typename ImageType::RegionType region,
const SpacingType &spacing,
ValueType zero,
ValueType one)
{
ImagePointer image = ImageType::New();
typename ImageType::SizeType size = region.GetSize();
PointType center;
ValueType radius;
ValueType radiusRec;
image->SetRegions(region);
image->SetSpacing(spacing);
image->Allocate();
center = ImageGeometricalCenterPoint(image);
typename ImageType::IndexType index;
for(unsigned int i = 0; i < Dim; ++i) {
index[i] = size[i] / 2;
ValueType rad = spacing[i] * size[i] / 2.0;
if(i == 0 || rad < radius) {
radius = rad;
}
}
if(radius == 0.0) {
radiusRec = 0.0;
} else {
radiusRec = 1.0 / radius;
}
itk::ImageRegionIterator<ImageType> writeIter(image, image->GetLargestPossibleRegion());
writeIter.GoToBegin();
PointType point;
VectorType v;
while (!writeIter.IsAtEnd())
{
image->TransformIndexToPhysicalPoint(writeIter.GetIndex(), point);
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = (point[i] - center[i]) * radiusRec;
}
auto norm = v.GetNorm();
if (norm <= 1.0)
writeIter.Set(one);
else
writeIter.Set(zero);
++writeIter;
}
return image;
}
static ValueType HannFunc(
ValueType t)
{
ValueType tt = 0.5 + 0.5 * t;
return 0.5 * (1.0 - cos(itk::Math::twopi * tt));
}
static ImagePointer HannMask(
typename ImageType::RegionType region,
const SpacingType &spacing,
ValueType exponent = 1.0)
{
ImagePointer image = ImageType::New();
typename ImageType::SizeType size = region.GetSize();
PointType center;
ValueType radius;
ValueType radiusRec;
image->SetRegions(region);
image->SetSpacing(spacing);
image->Allocate();
center = ImageGeometricalCenterPoint(image);
typename ImageType::IndexType index;
for(unsigned int i = 0; i < Dim; ++i) {
index[i] = size[i] / 2;
ValueType rad = spacing[i] * size[i] / 2.0;
if(i == 0 || rad < radius) {
radius = rad;
}
}
if(radius == 0.0) {
radiusRec = 0.0;
} else {
radiusRec = 1.0 / radius;
}
itk::ImageRegionIterator<ImageType> writeIter(image, image->GetLargestPossibleRegion());
writeIter.GoToBegin();
PointType point;
VectorType v;
while (!writeIter.IsAtEnd())
{
image->TransformIndexToPhysicalPoint(writeIter.GetIndex(), point);
for (unsigned int i = 0; i < Dim; ++i)
{
v[i] = (point[i] - center[i]) * radiusRec;
}
auto norm = v.GetNorm();
if (norm <= 1.0)
writeIter.Set(pow(HannFunc(norm), exponent));
else
writeIter.Set(0.0);
++writeIter;
}
return image;
}
static ImagePointer CircularMask2(
typename ImageType::RegionType region,
const SpacingType &spacing,
ValueType zero,
ValueType one)
{
ImagePointer image = ImageType::New();
typename ImageType::IndexType start = region.GetIndex();
typename ImageType::SizeType size = region.GetSize();
PointType center;
ValueType radius[Dim];
for (unsigned int i = 0; i < Dim; ++i)
{
center[i] = 0.5 * ((double)size[i] - (double)start[i]);
radius[i] = 0.5 * ((double)size[i] - (double)start[i]);
if (radius[i] > 0.0)
{
radius[i] = 1.0 / radius[i];
}
else
{
radius[i] = 0.0;
}
}
image->SetRegions(region);
image->SetSpacing(spacing);
image->Allocate();
itk::ImageRegionIterator<ImageType> writeIter(image, image->GetLargestPossibleRegion());
writeIter.GoToBegin();
PointType point;
while (!writeIter.IsAtEnd())
{
image->TransformIndexToPhysicalPoint(writeIter.GetIndex(), point);
for (unsigned int i = 0; i < Dim; ++i)
{
point[i] = (point[i] - center[i]) * radius[i];
}
VectorType v = MakeVector(point);
//if(point.EuclideanDistanceTo(center) <= 1.0)
if (v.GetNorm() <= 1.0)
writeIter.Set(one);
else
writeIter.Set(zero);
++writeIter;
}
return image;
}
static ImagePointer RectMask(
typename ImageType::RegionType region,
const SpacingType &spacing,
ValueType one)
{
ImagePointer image = ImageType::New();
image->SetRegions(region);
image->SetSpacing(spacing);
image->Allocate();
itk::ImageRegionIterator<ImageType> writeIter(image, image->GetLargestPossibleRegion());
writeIter.GoToBegin();
PointType point;
while (!writeIter.IsAtEnd())
{
writeIter.Set(one);
++writeIter;
}
return image;
}
static ImagePointer CloneImage(ImagePointer image)
{
typedef itk::ImageDuplicator<ImageType> DuplicatorType;
typedef typename DuplicatorType::Pointer DuplicatorPointer;
DuplicatorPointer dup = DuplicatorType::New();
dup->SetInputImage(image);
dup->Update();
return dup->GetOutput();
}
static LabelImagePointer CloneLabelImage(LabelImagePointer image)
{
typedef itk::ImageDuplicator<LabelImageType> DuplicatorType;
typedef typename DuplicatorType::Pointer DuplicatorPointer;
DuplicatorPointer dup = DuplicatorType::New();
dup->SetInputImage(image);
dup->Update();
return dup->GetOutput();
}
static ImagePointer SubsampleImage(
ImagePointer image,
unsigned int factor)
{
if(!image)
return image;
if (factor <= 1)
return image;
typedef itk::ShrinkImageFilter<ImageType, ImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer filter = FilterType::New();
filter->SetInput(image);
filter->SetShrinkFactors(factor);
filter->Update();
return filter->GetOutput();
}
static LabelImagePointer SubsampleLabelImage(
LabelImagePointer image,
unsigned int factor)
{
if (factor <= 0)
return image;
typedef itk::ShrinkImageFilter<LabelImageType, LabelImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer filter = FilterType::New();
filter->SetInput(image);
filter->SetShrinkFactors(factor);
filter->Update();
return filter->GetOutput();
}
static ImagePointer LoadImageU8(
const char *path)
{
typedef itk::ImageFileReader<ImageU8Type> ReaderType;
typedef typename ReaderType::Pointer ReaderPointer;
ReaderPointer reader = ReaderType::New();
reader->SetFileName(path);
reader->Update();
return ConvertImageFromU8Format(reader->GetOutput());
}
static void SaveImageU8(
std::string path,
ImagePointer image)
{
typedef itk::ImageFileWriter<ImageU8Type> WriterType;
typedef typename WriterType::Pointer WriterPointer;
ImageU8Pointer imageu8 = ConvertImageToIntegerFormat<unsigned char>(image);
WriterPointer writer = WriterType::New();
writer->SetFileName(path.c_str());
writer->SetInput(imageu8);
writer->Update();
}
static void SaveImageU16(
std::string path,
ImagePointer image)
{
typedef itk::ImageFileWriter<ImageU16Type> WriterType;
typedef typename WriterType::Pointer WriterPointer;
ImageU16Pointer imageu16 = ConvertImageToIntegerFormat<unsigned short>(image);
WriterPointer writer = WriterType::New();
writer->SetFileName(path.c_str());
writer->SetInput(imageu16);
writer->Update();
}
static void SaveImage(
std::string path,
ImagePointer image,
bool format16U)
{
if(format16U)
SaveImageU16(path, image);
else
SaveImageU8(path, image);
}
template <typename ImagePixelType>
static typename itk::Image<ImagePixelType, Dim>::Pointer ReadImage(const char *path)
{
typedef itk::ImageFileReader<itk::Image<ImagePixelType, Dim>> ReaderType;
typedef typename ReaderType::Pointer ReaderPointer;
ReaderPointer reader = ReaderType::New();
reader->SetFileName(path);
reader->Update();
return reader->GetOutput();
}
static ImagePointer LoadImage(
const char *path)
{
typedef itk::ImageIOBase::IOComponentType ScalarPixelType;
itk::ImageIOBase::Pointer imageIO =
itk::ImageIOFactory::CreateImageIO(
path, itk::ImageIOFactory::ReadMode);
if (!imageIO)
{
std::cout << "Failed to create image io object to label image: " << path << "." << std::endl;
//itkExceptionMacro ("Failed to read image information for file: " << path << ".");
//throw itkExceptionObject("Failed to read image information.");
std::cout << "Failed to read image information for file: " << path << "." << std::endl;
assert(false);
}
imageIO->SetFileName(path);
imageIO->ReadImageInformation();
const ScalarPixelType pixelType = imageIO->GetComponentType();
switch (pixelType)
{
case ImageIOBase::UNKNOWNCOMPONENTTYPE: {
std::cout << "UNKNOWNCOMPONENTTYPE not supported." << std::endl;
break;
}
case itk::ImageIOBase::UCHAR:
{
typedef unsigned char ImagePixelType;
return ConvertImageFromIntegerFormat<ImagePixelType>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::CHAR:
{
typedef signed char ImagePixelType;
return ConvertImageFromIntegerFormat<ImagePixelType>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::USHORT:
{
typedef unsigned short ImagePixelType;
return ConvertImageFromIntegerFormat<ImagePixelType>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::SHORT:
{
typedef signed short ImagePixelType;
return ConvertImageFromIntegerFormat<ImagePixelType>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::UINT:
{
typedef unsigned int ImagePixelType;
return ConvertImageFromIntegerFormat<ImagePixelType>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::INT:
{
typedef signed int ImagePixelType;
return ConvertImageFromIntegerFormat<ImagePixelType>(ReadImage<ImagePixelType>(path));
}
case ImageIOBase::ULONG: {
std::cout << "ULONG datatype not supported." << std::endl;
break;
}
case ImageIOBase::LONG: {
std::cout << "LONG datatype not supported." << std::endl;
break;
}
case itk::ImageIOBase::FLOAT:
{
typedef float ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<ValueType, Dim> >(ReadImage<ImagePixelType>(path));
//std::cout << "Float-typed images not supported yet: " << path << "." << std::endl;
//assert(false);
//itkExceptionMacro ("Float-typed images not supported yet: " << path << ".");
}
case itk::ImageIOBase::DOUBLE:
{
return ReadImage<ValueType>(path);
}
}
return nullptr;
}
static typename itk::Image<unsigned short, Dim>::Pointer LoadLabelImage(
const char *path)
{
typedef unsigned short PixelType;
typedef itk::ImageIOBase::IOComponentType ScalarPixelType;
itk::ImageIOBase::Pointer imageIO =
itk::ImageIOFactory::CreateImageIO(
path, itk::ImageIOFactory::ReadMode);
if (!imageIO)
{
std::cout << "Failed to create image io object to label image: " << path << "." << std::endl;
//itkExceptionMacro ("Failed to read image information for file: " << path << ".");
//throw itkExceptionObject("Failed to read image information.");
assert(false);
}
imageIO->SetFileName(path);
imageIO->ReadImageInformation();
const ScalarPixelType pixelType = imageIO->GetComponentType();
switch (pixelType)
{
case ImageIOBase::UNKNOWNCOMPONENTTYPE: {
std::cout << "UNKNOWNCOMPONENTTYPE not supported." << std::endl;
break;
}
case itk::ImageIOBase::UCHAR:
{
typedef unsigned char ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::CHAR:
{
typedef signed char ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::USHORT:
{
typedef unsigned short ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::SHORT:
{
typedef signed short ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::UINT:
{
typedef unsigned int ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));
}
case itk::ImageIOBase::INT:
{
typedef signed int ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));
}
case ImageIOBase::ULONG: {
std::cout << "ULONG datatype not supported." << std::endl;
break;
}
case ImageIOBase::LONG: {
std::cout << "LONG datatype not supported." << std::endl;
break;
}
case itk::ImageIOBase::FLOAT:
{
typedef float ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));//ConvertImageF32ToIntegerFormat<PixelType, Dim>(ReadImage<ImagePixelType>(path));
//std::cout << "Float-typed images not supported yet: " << path << "." << std::endl;
//assert(false);
//itkExceptionMacro ("Float-typed images not supported yet: " << path << ".");
}
case itk::ImageIOBase::DOUBLE:
{
typedef double ImagePixelType;
return CastImage<itk::Image<ImagePixelType, Dim>, itk::Image<PixelType, Dim>>(ReadImage<ImagePixelType>(path));//itk::ConvertImageToIntegerFormat<PixelType, Dim>(ReadImage<ImagePixelType>(path));
//std::cout << "Float-typed images not supported yet: " << path << "." << std::endl;
//assert(false);
}
}
return nullptr;
}
static void SaveLabelImage(
std::string path,
LabelImagePointer image)
{
typedef itk::ImageFileWriter<LabelImageType> WriterType;
typedef typename WriterType::Pointer WriterPointer;
WriterPointer writer = WriterType::New();
writer->SetFileName(path.c_str());
writer->SetInput(image);
writer->Update();
}
//
// Creation and specification of image interpolators.
//
enum ImwarpInterpolationMode
{
kImwarpInterpNearest,
kImwarpInterpLinear,
kImwarpInterpCubic,
kImwarpInterpBSpline,
};
static typename itk::InterpolateImageFunction<ImageType, PointValueType>::Pointer MakeInterpolator(ImwarpInterpolationMode mode)
{
typedef itk::InterpolateImageFunction<ImageType, PointValueType> InterpolatorType;
typedef typename InterpolatorType::Pointer InterpolatorPointer;
InterpolatorPointer ptr;
if (mode == kImwarpInterpNearest)
{
ptr = itk::NearestNeighborInterpolateImageFunction<ImageType, PointValueType>::New();
}
else if (mode == kImwarpInterpLinear)
{
ptr = itk::LinearInterpolateImageFunction<ImageType, PointValueType>::New();
}
else if (mode == kImwarpInterpCubic)
{
typedef itk::BSplineInterpolateImageFunction<ImageType, PointValueType> BSplineInterpolatorType;
typedef typename BSplineInterpolatorType::Pointer BSplineInterpolatorPointer;
BSplineInterpolatorPointer bsplinePtr = itk::BSplineInterpolateImageFunction<ImageType, PointValueType>::New();
bsplinePtr->SetSplineOrder(3);
ptr = bsplinePtr;
}
else if (mode == kImwarpInterpBSpline)
{
ptr = itk::BSplineInterpolateImageFunction<ImageType, PointValueType>::New();
}
else
{
assert(false);
}
return ptr;
}
static typename itk::InterpolateImageFunction<LabelImageType, PointValueType>::Pointer MakeLabelInterpolator()
{
typedef itk::InterpolateImageFunction<LabelImageType, PointValueType> InterpolatorType;
typedef typename InterpolatorType::Pointer InterpolatorPointer;
InterpolatorPointer ptr;
ptr = itk::NearestNeighborInterpolateImageFunction<LabelImageType, PointValueType>::New();
return ptr;
}
//
// Format convertion routines.
//
template <typename ImagePixelType = unsigned char>
static typename itk::Image<ImagePixelType, Dim>::Pointer ConvertImageToIntegerFormat(ImagePointer image)
{
typedef itk::Image<ImagePixelType, Dim> ImageUType;
typedef itk::ShiftScaleImageFilter<ImageType, ImageType> RescaleFilter;
typedef typename RescaleFilter::Pointer RescaleFilterPointer;
typedef itk::ClampImageFilter<ImageType, ImageUType> CastFilter;
typedef typename CastFilter::Pointer CastFilterPointer;
ValueType minVal = (ValueType)itk::NumericTraits<ImagePixelType>::min();
ValueType maxVal = (ValueType)itk::NumericTraits<ImagePixelType>::max();
ValueType span = (maxVal - minVal);
//std::cout << "minVal: " << minVal << ", maxVal: " << maxVal << ", span: " << span << std::endl;
ValueType halfInt = (itk::NumericTraits<ValueType>::One / 2);
//(halfInt / span) + minVal
RescaleFilterPointer rescaleFilter = RescaleFilter::New();
rescaleFilter->SetInput(image);
rescaleFilter->SetShift(0);
rescaleFilter->SetScale(span);
rescaleFilter->Update();
CastFilterPointer castFilter = CastFilter::New();
castFilter->SetInput(rescaleFilter->GetOutput());
castFilter->Update();
return castFilter->GetOutput();
}
template <typename ImagePixelType = unsigned char>
static ImagePointer ConvertImageFromIntegerFormat(
typename itk::Image<ImagePixelType, Dim>::Pointer image)
{
typedef itk::Image<ImagePixelType, Dim> ImageUType;
typedef itk::CastImageFilter<ImageUType, ImageType> CastFilter;
typedef typename CastFilter::Pointer CastFilterPointer;
typedef itk::ShiftScaleImageFilter<ImageType, ImageType> RescaleFilter;
typedef typename RescaleFilter::Pointer RescaleFilterPointer;
CastFilterPointer castFilter = CastFilter::New();
castFilter->SetInput(image);
castFilter->Update();
ValueType minVal = (ValueType)itk::NumericTraits<ImagePixelType>::min();
ValueType maxVal = (ValueType)itk::NumericTraits<ImagePixelType>::max();
ValueType span = (maxVal - minVal);
// Something wrong HERE!
RescaleFilterPointer rescaleFilter = RescaleFilter::New();
rescaleFilter->SetInput(castFilter->GetOutput());
rescaleFilter->SetShift(0);
rescaleFilter->SetScale(itk::NumericTraits<ValueType>::One / span);
rescaleFilter->Update();
return rescaleFilter->GetOutput();
/* ValueType minVal = (ValueType)itk::NumericTraits<ImagePixelType>::min();
ValueType maxVal = (ValueType)itk::NumericTraits<ImagePixelType>::max();
ValueType span = (maxVal - minVal);
// Something wrong HERE!
RescaleFilterPointer rescaleFilter = RescaleFilter::New();
rescaleFilter->SetInput(castFilter->GetOutput());
rescaleFilter->SetShift(-minVal);
rescaleFilter->SetScale(itk::NumericTraits<ValueType>::One / span);
rescaleFilter->Update();
return rescaleFilter->GetOutput();
*/
}
//
// Noise generation routines.
//
static ImagePointer AdditiveNoise(ImagePointer image, double stdDev = 1.0, double mean = 0.0, unsigned int seed = 0, bool clampOutputFlag = true)
{
typedef itk::AdditiveGaussianNoiseImageFilter<ImageType, ImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
if (stdDev == 0.0)
return image;
FilterPointer ngen = FilterType::New();
ngen->SetInput(image);
ngen->SetMean(mean);
ngen->SetStandardDeviation(stdDev);
ngen->SetSeed(seed);
ngen->SetNumberOfThreads(1);
ngen->Update();
ImagePointer noisyImage = ngen->GetOutput();
if (clampOutputFlag)
{
typedef itk::ClampImageFilter<ImageType, ImageType> ClampFilterType;
typedef typename ClampFilterType::Pointer ClampFilterPointer;
ClampFilterPointer clampFilter = ClampFilterType::New();
clampFilter->SetInput(noisyImage);
clampFilter->SetBounds(0.0, 1.0);
clampFilter->Update();
return clampFilter->GetOutput();
}
else
{
return noisyImage;
}
}
static typename itk::Image<bool, Dim>::Pointer ThresholdImage(
ImagePointer image,
ValueType threshold)
{
typedef itk::BinaryThresholdImageFilter<ImageType, itk::Image<bool, Dim>> ThresholderType;
typename ThresholderType::Pointer thresholder = ThresholderType::New();
thresholder->SetInput(image);
thresholder->SetInsideValue(true);
thresholder->SetOutsideValue(false);
thresholder->SetLowerThreshold(threshold);
thresholder->Update(); // Finalize thresholding
return thresholder->GetOutput();
}
static LabelImagePointer ThresholdToLabelImage(
ImagePointer image,
ValueType threshold)
{
typedef itk::BinaryThresholdImageFilter<ImageType, LabelImageType> ThresholderType;
typename ThresholderType::Pointer thresholder = ThresholderType::New();
thresholder->SetInput(image);
thresholder->SetInsideValue(1U);
thresholder->SetOutsideValue(0U);
thresholder->SetLowerThreshold(threshold);
thresholder->Update(); // Finalize thresholding
return thresholder->GetOutput();
}
static unsigned int GetPixelCount(
ImagePointer image)
{
typename ImageType::RegionType region = image->GetLargestPossibleRegion();
unsigned int pixelCount = 1;
for(unsigned int i = 0; i < Dim; ++i) {
pixelCount = pixelCount * region.GetSize()[i];
}
return pixelCount;
}
struct MinMaxSpan
{
ValueType minimum;
ValueType maximum;
ValueType span;
};
static MinMaxSpan IntensityMinMax(ImagePointer image, double p)
{
assert(p < 0.5);
MinMaxSpan result;
result.minimum = itk::NumericTraits<ValueType>::max();
result.maximum = itk::NumericTraits<ValueType>::min();
result.span = itk::NumericTraits<ValueType>::max();
std::vector<ValueType> values;
itk::ImageRegionConstIterator<ImageType> reader(image, image->GetLargestPossibleRegion());
reader.GoToBegin();
values.reserve(GetPixelCount(image));
while (!reader.IsAtEnd())
{
values.push_back(reader.Get());
++reader;
}
std::sort(values.begin(), values.end());
if (values.size() == 0)
{
result.minimum = itk::NumericTraits<ValueType>::ZeroValue();
result.maximum = itk::NumericTraits<ValueType>::OneValue();
result.span = result.maximum;
}
else
{
size_t lowPos = (size_t)(p * values.size());
size_t hiPos = (size_t)((1.0 - p) * values.size());
if (lowPos >= values.size())
lowPos = values.size() - 1;
if (hiPos >= values.size())
hiPos = values.size() - 1;
result.minimum = values[lowPos];
result.maximum = values[hiPos];
result.span = result.maximum - result.minimum;
}
assert(result.maximum >= result.minimum);
if (result.span <= 0)
{
result.span = 1.0;
}
return result;
}
static MinMaxSpan IntensityMinMax(ImagePointer image, double p, BinaryImagePointer mask)
{
assert(p < 0.5);
MinMaxSpan result;
result.minimum = itk::NumericTraits<ValueType>::max();
result.maximum = itk::NumericTraits<ValueType>::min();
result.span = itk::NumericTraits<ValueType>::max();
std::vector<ValueType> values;
itk::ImageRegionConstIterator<ImageType> reader(image, image->GetLargestPossibleRegion());
reader.GoToBegin();
itk::ImageRegionConstIterator<BinaryImageType> maskReader(mask, mask->GetLargestPossibleRegion());
maskReader.GoToBegin();
values.reserve(GetPixelCount(image));
while (!reader.IsAtEnd())
{
if(maskReader.Get())
{
values.push_back(reader.Get());
}
++reader;
++maskReader;
}
std::sort(values.begin(), values.end());
if (values.size() == 0)
{
result.minimum = itk::NumericTraits<ValueType>::ZeroValue();
result.maximum = itk::NumericTraits<ValueType>::OneValue();
result.span = result.maximum;
}
else
{
size_t lowPos = (size_t)(p * values.size());
size_t hiPos = (size_t)((1.0 - p) * values.size());
if (lowPos >= values.size())
lowPos = values.size() - 1;
if (hiPos >= values.size())
hiPos = values.size() - 1;
result.minimum = values[lowPos];
result.maximum = values[hiPos];
result.span = result.maximum - result.minimum;
}
assert(result.maximum >= result.minimum);
if (result.span <= 0)
{
result.span = 1.0;
}
return result;
}
// Assumes that the image is normalized before-hand
static ImagePointer HistogramEqualization(
ImagePointer image,
BinaryImagePointer mask,
int bins
)
{
if (bins <= 0)
{
return image;
}
ImagePointer resultImage = CloneImage(image);
itk::ImageRegionIterator<ImageType> reader(image, image->GetLargestPossibleRegion());
reader.GoToBegin();
std::vector<unsigned int> hist;
for(unsigned int i = 0; i < bins + 1; ++i)
{
hist.push_back(0);
}
unsigned int totalCount = 0;
if (mask)
{
itk::ImageRegionIterator<BinaryImageType> maskReader(mask, mask->GetLargestPossibleRegion());
maskReader.GoToBegin();
while (!reader.IsAtEnd())
{
assert(!maskReader.IsAtEnd());
if (maskReader.Get())
{
unsigned int index = (unsigned int)(reader.Get() * bins + 0.5);
++hist[index];
++totalCount;
}
++reader;
++maskReader;
}
} else {
while (!reader.IsAtEnd())
{
unsigned int index = (unsigned int)(reader.Get() * bins + 0.5);
++hist[index];
++totalCount;
++reader;
}
}
unsigned int hist_min_index = hist.size();
unsigned int counter = 0;
for (unsigned int i = 0; i < hist.size(); ++i)
{
counter += hist[i];
hist[i] = counter;
if (hist_min_index == hist.size() && counter > 0)
{
hist_min_index = i;
}
}
unsigned int hist_min = hist[hist_min_index];
double denom = (double)(totalCount-hist_min);
if (totalCount == hist_min)
{
denom = 1.0;
}
itk::ImageRegionIterator<ImageType> writer(resultImage, resultImage->GetLargestPossibleRegion());
if (mask)
{
itk::ImageRegionIterator<BinaryImageType> maskReader(mask, mask->GetLargestPossibleRegion());
maskReader.GoToBegin();
while (!writer.IsAtEnd())
{
assert(!maskReader.IsAtEnd());
if (maskReader.Get())
{
unsigned int index = (unsigned int)(writer.Get() * bins + 0.5);
double f = (hist[index]-hist_min) / denom;
writer.Set(f);
}
++writer;
++maskReader;
}
} else {
while (!writer.IsAtEnd())
{
unsigned int index = (unsigned int)(writer.Get() * bins + 0.5);
double f = (hist[index]-hist_min) / denom;
writer.Set(f);
++writer;
}
}
return resultImage;
}
static ImagePointer NormalizeImage(
ImagePointer image,
MinMaxSpan mms)
{
image = CloneImage(image);
itk::ImageRegionIterator<ImageType> writer(image, image->GetLargestPossibleRegion());
writer.GoToBegin();
while (!writer.IsAtEnd())
{
ValueType val = writer.Get();
if (val <= mms.minimum)
val = itk::NumericTraits<ValueType>::ZeroValue();
else if (val >= mms.maximum)
val = itk::NumericTraits<ValueType>::OneValue();
else
val = static_cast<ValueType>((val - mms.minimum) / (double)(mms.span));
writer.Set(val);
++writer;
}
return image;
}
/* static ImagePointer PercentileRescaleImage(ImagePointer image, double p)
{
assert(p < 0.5);
ImagePointer result = ImageType::New();
result->SetDirection(image->GetDirection());
result->SetSpacing(image->GetSpacing());
result->SetRegions(image->GetLargestPossibleRegion());
result->Allocate();
std::vector<ValueType> values;
itk::ImageRegionConstIterator<ImageType> reader(image, image->GetLargestPossibleRegion());
reader.GoToBegin();
itk::ImageRegionIterator<ImageType> writer(result, result->GetLargestPossibleRegion());
writer.GoToBegin();
values.reserve(GetPixelCount(image));
while (!reader.IsAtEnd())
{
values.push_back(reader.Get());
++reader;
}
std::sort(values.begin(), values.end());
ValueType low;
ValueType hi;
ValueType span;
if (values.size() == 0)
{
low = 0;
hi = 1;
}
else
{
size_t lowPos = (size_t)(p * values.size());
size_t hiPos = (size_t)((1.0 - p) * values.size());
if (lowPos >= values.size())
lowPos = values.size() - 1;
if (hiPos >= values.size())
hiPos = values.size() - 1;
low = values[lowPos];
hi = values[hiPos];
}
assert(hi >= low);
span = hi - low;
if (span <= 0)
{
span = 1.0;
low = 0.0;
hi = 0.0;
}
reader.GoToBegin();
while (!reader.IsAtEnd())
{
assert(!writer.IsAtEnd());
ValueType val = reader.Get();
if (val <= low)
val = (ValueType)0;
else if (val >= hi)
val = (ValueType)1;
else
val = (ValueType)((val - low) / (double)(span));
writer.Set(val);
++reader;
++writer;
}
return result;
}
static ImagePointer PercentileRescaleImage(
ImagePointer image,
double p,
typename itk::Image<bool, Dim>::Pointer mask)
{
assert(p < 0.5);
ImagePointer result = ImageType::New();
result->SetDirection(image->GetDirection());
result->SetSpacing(image->GetSpacing());
result->SetRegions(image->GetLargestPossibleRegion());
result->Allocate();
std::vector<ValueType> values;
itk::ImageRegionConstIterator<ImageType> reader(image, image->GetLargestPossibleRegion());
reader.GoToBegin();
itk::ImageRegionConstIterator<itk::Image<bool, Dim>> maskReader(mask, mask->GetLargestPossibleRegion());
maskReader.GoToBegin();
itk::ImageRegionIterator<ImageType> writer(result, result->GetLargestPossibleRegion());
writer.GoToBegin();
values.reserve(GetPixelCount(image));
while (!reader.IsAtEnd())
{
assert(maskReader.IsAtEnd() == false);
if (maskReader.Get())
values.push_back(reader.Get());
++maskReader;
++reader;
}
std::sort(values.begin(), values.end());
ValueType low;
ValueType hi;
ValueType span;
if (values.size() == 0)
{
low = 0;
hi = 1;
}
else
{
size_t lowPos = (size_t)(p * values.size());
size_t hiPos = (size_t)((1.0 - p) * values.size());
if (lowPos >= values.size())
lowPos = values.size() - 1;
if (hiPos >= values.size())
hiPos = values.size() - 1;
low = values[lowPos];
hi = values[hiPos];
}
span = hi - low;
assert(hi >= low);
if (span <= 0)
{
span = 1.0;
low = 0.0;
hi = 0.0;
}
reader.GoToBegin();
maskReader.GoToBegin();
while (!reader.IsAtEnd())
{
assert(!writer.IsAtEnd());
assert(!maskReader.IsAtEnd());
ValueType val = reader.Get();
bool maskVal = maskReader.Get();
if (maskVal)
{
if (val <= low)
val = (ValueType)0;
else if (val >= hi)
val = (ValueType)1;
else
val = (ValueType)((val - low) / (double)(span));
} else {
val = 0;
}
writer.Set(val);
++maskReader;
++reader;
++writer;
}
return result;
}*/
static ImagePointer MultiplyImageByConstant(
ImagePointer image,
ValueType factor)
{
typedef itk::MultiplyImageFilter< ImageType, ImageType, ImageType > FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( image );
filter->SetConstant( factor );
filter->Update();
return filter->GetOutput();
}
static LabelImagePointer MultiplyLabelImageByConstant(
LabelImagePointer image,
ValueType factor)
{
ImagePointer tmpImage = itk::ConvertImageFromIntegerFormat<unsigned short, Dim>(image);
ImagePointer multImage = MultiplyImageByConstant(tmpImage, factor);
return itk::ConvertImageToIntegerFormat<unsigned short, Dim>(multImage);
}
static ImagePointer DifferenceImage(
ImagePointer image1,
ImagePointer image2)
{
typedef itk::AbsoluteValueDifferenceImageFilter<ImageType, ImageType, ImageType> AbsDiffFilterType;
typename AbsDiffFilterType::Pointer diffFilter = AbsDiffFilterType::New();
diffFilter->SetInput1(image1);
diffFilter->SetInput2(image2);
diffFilter->Update();
return diffFilter->GetOutput();
}
struct ImageStatisticsData {
ValueType min;
ValueType max;
ValueType mean;
ValueType sigma;
};
static ImageStatisticsData ImageStatistics(ImagePointer image) {
ImageStatisticsData result;
typedef itk::StatisticsImageFilter<ImageType> StatisticsImageFilterType;
typename StatisticsImageFilterType::Pointer statisticsImageFilter = StatisticsImageFilterType::New();
statisticsImageFilter->SetInput(image);
statisticsImageFilter->Update();
result.min = statisticsImageFilter->GetMinimum();
result.max = statisticsImageFilter->GetMaximum();
result.mean = statisticsImageFilter->GetMean();
result.sigma = statisticsImageFilter->GetSigma();
return result;
}
//
//
// Point set routines.
//
//
//
// Routines for computing image edge vertices (corners).
//
private:
static void ComputeImageEdgeVerticesRecursive(
PointSetType &points,
PointType &p,
IndexType &index,
SizeType &size,
const SpacingType &spacing,
unsigned int d)
{
if (d >= Dim)
{
points.push_back(p);
}
else
{
p[d] = static_cast<PointValueType>(index[d]);
ComputeImageEdgeVerticesRecursive(points, p, index, size, spacing, d + 1);
// Add (size - 1) to the point's position to locate it
// on the last pixel.
if (size[d] > static_cast<PointValueType>(0))
p[d] += static_cast<PointValueType>((size[d] - 1) * spacing[d]);
ComputeImageEdgeVerticesRecursive(points, p, index, size, spacing, d + 1);
}
}
static void ComputeImageEdgeVerticesRecursive(
PointSetType &points,
PointType &p,
IndexType &index,
SizeType &size,
unsigned int d)
{
if (d >= Dim)
{
points.push_back(p);
}
else
{
p[d] = static_cast<PointValueType>(index[d]);
ComputeImageEdgeVerticesRecursive(points, p, index, size, d + 1);
// Add (size - 1) to the point's position to locate it
// on the last pixel.
if (size[d] > static_cast<PointValueType>(0))
p[d] += static_cast<PointValueType>((size[d] - 1));
ComputeImageEdgeVerticesRecursive(points, p, index, size, d + 1);
}
}
public:
static void ComputeImageEdgeVertices(
ImagePointer image,
PointSetType &points,
bool considerSpacing)
{
RegionType region = image->GetLargestPossibleRegion();
IndexType index = region.GetIndex();
SizeType size = region.GetSize();
PointType p;
if (considerSpacing)
ComputeImageEdgeVerticesRecursive(points, p, index, size, image->GetSpacing(), 0U);
else
ComputeImageEdgeVerticesRecursive(points, p, index, size, 0U);
}
static PointValueType ComputeImageEdgeVertexMeanDistance(
PointSetType &points1,
PointSetType &points2)
{
assert(points1.size() == points2.size());
PointValueType mean = 0;
for (size_t i = 0; i < points1.size(); ++i)
{
PointType p1 = points1[i];
PointType p2 = points2[i];
mean += p1.EuclideanDistanceTo(p2);
}
return mean / static_cast<PointValueType>(points1.size());
}
static void PrintPointSet(const PointSetType &ps)
{
std::cout << "{";
for (size_t i = 0; i < ps.size(); ++i)
{
if (i > 0)
std::cout << ", ";
std::cout << ps[i];
}
std::cout << "}" << std::endl;
}
static void PointSetBoundingBox(
PointSetType &points,
PointType &minOut,
PointType &maxOut)
{
if (points.size() == 0)
{
minOut.Fill(0);
maxOut.Fill(0);
}
else
{
minOut = points[0];
maxOut = points[0];
for (size_t i = 1; i < points.size(); ++i)
{
PointType p = points[i];
for (unsigned int j = 0; j < Dim; ++j)
{
if (minOut[j] > p[j])
minOut[j] = p[j];
if (maxOut[j] < p[j])
maxOut[j] = p[j];
}
}
}
}
static double PointSetMeanEuclideanDistance(
PointSetType &a,
PointSetType &b)
{
double acc = 0.0;
assert(a.size() == b.size());
double sizeRec = a.size();
if (a.size() > 0)
{
sizeRec = 1.0 / sizeRec;
}
for (size_t i = 0; i < a.size(); ++i)
{
acc += a[i].EuclideanDistanceTo(b[i]);
}
return acc * sizeRec;
}
/**
* O(n^2) asymmetric SMD computation from the reference to target point-set.
**/
static double PointSetASMD(
PointSetType &ref,
PointSetType &target)
{
double acc = 0.0;
double sizeRec = ref.size();
if (ref.size() > 0)
{
sizeRec = 1.0 / sizeRec;
}
if (target.size() == 0)
{
return 0.0;
}
//#define POINTSET_ASMD_DEBUG_PRINTOUTS
#ifdef POINTSET_ASMD_DEBUG_PRINTOUTS
for (size_t i = 0; i < ref.size(); ++i)
{
std::cout << "From " << ref[i] << "..." << std::endl;
double cur = ref[i].EuclideanDistanceTo(target[0]);
std::cout << "To " << target[0] << (cur) << std::endl;
for (size_t j = 1; j < target.size(); ++j)
{
double d = ref[i].EuclideanDistanceTo(target[j]);
if (d < cur)
{
cur = d;
std::cout << "To " << target[j] << (d) << " [NEW BEST]" << std::endl;
}
else
{
std::cout << "To " << target[j] << (d) << std::endl;
}
}
acc += cur;
}
#else
for (size_t i = 0; i < ref.size(); ++i)
{
double cur = ref[i].EuclideanDistanceTo(target[0]);
for (size_t j = 1; j < target.size(); ++j)
{
double d = ref[i].EuclideanDistanceTo(target[j]);
if (d < cur)
{
cur = d;
}
}
acc += cur;
}
#endif
return acc * sizeRec;
}
//
// Transformation routines.
//
static PointSetType TransformPointSet(
typename itk::Transform<PointValueType, Dim, Dim>::Pointer transform,
PointSetType &points)
{
PointSetType result;
for (size_t i = 0; i < points.size(); ++i)
{
result.push_back(transform->TransformPoint(points[i]));
}
return result;
}
//static Point
static PointSetType TranslatePointSet(
VectorType offset,
PointSetType &points)
{
PointSetType result;
for (size_t i = 0; i < points.size(); ++i)
{
result.push_back(points[i] + offset);
}
return result;
}
static PointSetType &TranslatePointSetInPlace(
CovariantVectorType offset,
PointSetType &points)
{
for (size_t i = 0; i < points.size(); ++i)
{
points[i] += +offset;
}
return points;
}
static BaseTransformPointer MakeTranslationTransformation(
CovariantVectorType translation)
{
typedef itk::TranslationTransform<PointValueType, Dim> TranslationTransformType;
typedef typename TranslationTransformType::Pointer TranslationTransformPointer;
typedef typename TranslationTransformType::ParametersType ParametersType;
TranslationTransformPointer ttp = TranslationTransformType::New();
ParametersType param(ttp->GetNumberOfParameters());
for (unsigned int i = 0; i < Dim; ++i)
{
param[i] = translation[i];
}
ttp->SetParameters(param);
return itk::CastSmartPointer<TranslationTransformType, BaseTransformType>(ttp);
}
static BaseTransformPointer CompositeTransformWithTranslation(
typename itk::Transform<PointValueType, Dim, Dim>::Pointer transform,
CovariantVectorType translation)
{
typedef itk::CompositeTransform<PointValueType, Dim> CompositeTransformType;
typedef typename CompositeTransformType::Pointer CompositeTransformPointer;
bool anyNonZero = false;
for (unsigned int i = 0; i < Dim; ++i)
{
if (!itk::Math::AlmostEquals(translation[i], -0))
{
anyNonZero = true;
break;
}
}
if (!anyNonZero)
return transform;
CompositeTransformPointer compositeTransform = CompositeTransformType::New();
compositeTransform->AddTransform(transform);
compositeTransform->AddTransform(MakeTranslationTransformation(translation));
return itk::CastSmartPointer<CompositeTransformType, BaseTransformType>(compositeTransform);
}
static ImagePointer TransformImage(
ImagePointer inputImage,
typename itk::Transform<double, Dim, Dim>::Pointer transform,
PointType originPoint,
SizeType outputSize,
ImwarpInterpolationMode interpMode,
ValueType bgValue = 0)
{
typedef itk::ResampleImageFilter<ImageType, ImageType> ResampleFilterType;
typedef typename ResampleFilterType::Pointer ResampleFilterPointer;
ResampleFilterPointer resampler = ResampleFilterType::New();
resampler->SetInput(inputImage);
transform = CompositeTransformWithTranslation(transform, MakeCovariantVector(originPoint));
itk::Transform<double, Dim, Dim> *transformRawPtr = transform.GetPointer();
resampler->SetTransform(transformRawPtr);
resampler->SetSize(outputSize);
resampler->SetOutputOrigin(inputImage->GetOrigin());
resampler->SetOutputSpacing(inputImage->GetSpacing());
resampler->SetOutputDirection(inputImage->GetDirection());
resampler->SetDefaultPixelValue(bgValue);
resampler->SetInterpolator(MakeInterpolator(interpMode));
resampler->Update();
return resampler->GetOutput();
}
static ImagePointer TransformImage(
ImagePointer inputImage,
ImagePointer refImage,
typename itk::Transform<double, Dim, Dim>::Pointer transform,
ImwarpInterpolationMode interpMode,
ValueType bgValue = 0)
{
typedef itk::ResampleImageFilter<ImageType, ImageType> ResampleFilterType;
typedef typename ResampleFilterType::Pointer ResampleFilterPointer;
ResampleFilterPointer resampler = ResampleFilterType::New();
resampler->SetInput(inputImage);
itk::Transform<double, Dim, Dim> *transformRawPtr = transform.GetPointer();
resampler->SetTransform(transformRawPtr);
resampler->SetReferenceImage(refImage);
resampler->SetUseReferenceImage(true);
resampler->SetDefaultPixelValue(bgValue);
resampler->SetInterpolator(MakeInterpolator(interpMode));
resampler->Update();
return resampler->GetOutput();
}
static LabelImagePointer TransformLabelImage(
LabelImagePointer inputImage,
typename itk::Transform<double, Dim, Dim>::Pointer transform,
PointType originPoint,
SizeType outputSize,
unsigned short bgValue = 0)
{
typedef itk::ResampleImageFilter<LabelImageType, LabelImageType> ResampleFilterType;
typedef typename ResampleFilterType::Pointer ResampleFilterPointer;
ResampleFilterPointer resampler = ResampleFilterType::New();
resampler->SetInput(inputImage);
transform = CompositeTransformWithTranslation(transform, MakeCovariantVector(originPoint));
itk::Transform<double, Dim, Dim> *transformRawPtr = transform.GetPointer();
resampler->SetTransform(transformRawPtr);
resampler->SetSize(outputSize);
resampler->SetOutputOrigin(inputImage->GetOrigin());
resampler->SetOutputSpacing(inputImage->GetSpacing());
resampler->SetOutputDirection(inputImage->GetDirection());
resampler->SetDefaultPixelValue(bgValue);
resampler->SetInterpolator(MakeLabelInterpolator());
resampler->Update();
return resampler->GetOutput();
}
static LabelImagePointer TransformLabelImage(
LabelImagePointer inputImage,
LabelImagePointer refImage,
typename itk::Transform<double, Dim, Dim>::Pointer transform,
unsigned short bgValue = 0)
{
typedef itk::ResampleImageFilter<LabelImageType, LabelImageType> ResampleFilterType;
typedef typename ResampleFilterType::Pointer ResampleFilterPointer;
ResampleFilterPointer resampler = ResampleFilterType::New();
resampler->SetInput(inputImage);
itk::Transform<double, Dim, Dim> *transformRawPtr = transform.GetPointer();
resampler->SetTransform(transformRawPtr);
resampler->SetReferenceImage(refImage);
resampler->SetUseReferenceImage(true);
resampler->SetDefaultPixelValue(bgValue);
resampler->SetInterpolator(MakeLabelInterpolator());
resampler->Update();
return resampler->GetOutput();
}
static ImagePointer TransformImageAutoCrop(
ImagePointer image,
BaseTransformPointer transform,
ImwarpInterpolationMode interpMode,
PointSetType *outPointSet,
ValueType bgValue = 0)
{
PointSetType inputPointSet;
ComputeImageEdgeVertices(image, inputPointSet, true);
PointSetType outputPointSet = TransformPointSet(transform->GetInverseTransform(), inputPointSet);
PointType minPoint;
PointType maxPoint;
PointSetBoundingBox(outputPointSet, minPoint, maxPoint);
VectorType sizeVec = maxPoint - minPoint;
SizeType size = MakeSize(sizeVec);
if (outPointSet)
{
*outPointSet = TranslatePointSet(-MakeVector(minPoint), outputPointSet);
}
return TransformImage(image, transform, minPoint, size, interpMode, bgValue);
}
static ImagePointer TranslateImage(
ImagePointer image,
CovariantVectorType t,
ValueType bgValue = 0)
{
t = RoundCovariantVector(t);
SizeType origSize = GetImageSize(image);
SizeType extSize = MakeSize(AbsCovariantVector(t));
SizeType newSize = origSize + extSize;
PointType origin;
origin.Fill(0);
for (unsigned int i = 0; i < Dim; ++i)
{
if (t[i] < 0.0)
t[i] = 0.0;
}
return TransformImage(image,
MakeTranslationTransformation(-t),
origin,
newSize,
kImwarpInterpNearest,
bgValue);
}
static void RoundPointSet(
PointSetType &points)
{
for (size_t i = 0; i < points.size(); ++i)
{
for (unsigned int d = 0; d < Dim; ++d)
{
points[i][d] = (PointValueType)((long long)(points[i][d] + 0.5));
}
}
}
struct OverlapScore
{
int label;
double jaccard;
double dice;
};
static std::vector<OverlapScore> ComputeLabelOverlap(
LabelImagePointer labelImage1,
LabelImagePointer labelImage2)
{
typedef itk::LabelOverlapMeasuresImageFilter<LabelImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer filter = FilterType::New();
filter->SetSourceImage(labelImage1);
filter->SetTargetImage(labelImage2);
filter->Update();
typedef typename FilterType::MapType MapType;
std::vector<OverlapScore> result;
MapType labelMap = filter->GetLabelSetMeasures();
typename MapType::const_iterator it;
for (it = labelMap.begin(); it != labelMap.end(); ++it)
{
if ((*it).first == 0)
{ // Ignore background
continue;
}
OverlapScore score;
score.label = it->first;
score.jaccard = filter->GetUnionOverlap(score.label);
score.dice = filter->GetMeanOverlap(score.label);
result.push_back(score);
}
OverlapScore allScore;
allScore.label = 0;
allScore.jaccard = filter->GetUnionOverlap();
allScore.dice = filter->GetMeanOverlap();
result.push_back(allScore);
return result;
}
static std::vector<OverlapScore> ComputeMaskOverlap(
ImagePointer refImage,
ImagePointer floatingImage,
ValueType threshold)
{
typedef itk::Image<bool, Dim> MaskImageType;
typedef typename MaskImageType::Pointer MaskImagePointer;
MaskImagePointer refImageBool = ThresholdImage(refImage, threshold);
MaskImagePointer floatingImageBool = ThresholdImage(floatingImage, threshold);
LabelImagePointer refImageLabel = itk::CastImage<MaskImageType, LabelImageType>(refImageBool);
LabelImagePointer floatingImageLabel = itk::CastImage<MaskImageType, LabelImageType>(floatingImageBool);
std::vector<OverlapScore> result = ComputeLabelOverlap(refImageLabel, floatingImageLabel);
if(result.size() > 0) {
result[0].label = 65534U;
}
return result;
}
static std::vector<OverlapScore> ComputeTotalOverlap(
LabelImagePointer labelImage1,
LabelImagePointer labelImage2)
{
labelImage1 = CloneLabelImage(labelImage1);
labelImage2 = CloneLabelImage(labelImage2);
SaturateLabelImage(labelImage1, 0U, 1U);
SaturateLabelImage(labelImage2, 0U, 1U);
std::vector<OverlapScore> result = ComputeLabelOverlap(labelImage1, labelImage2);
if(result.size() > 0) {
result[0].label = 65535U;
}
return result;
}
static void SaveLabelOverlapCSV(
const char *path,
std::vector<OverlapScore> &scores,
bool writeHeaders = false)
{
FILE *f = fopen(path, "wb");
if (f)
{
if (writeHeaders)
{
fprintf(f, "Label,Jaccard,Dice\n");
}
for (size_t i = 0; i < scores.size(); ++i)
{
fprintf(f, "%d,%.7f,%.7f\n", scores[i].label, scores[i].jaccard, scores[i].dice);
}
fclose(f);
}
}
static ImagePointer SmoothImage(
ImagePointer image,
double sigma)
{
if(sigma <= 0.0)
return image;
typedef itk::DiscreteGaussianImageFilter<
ImageType, ImageType>
filterType;
// Create and setup a Gaussian filter
typename filterType::Pointer gaussianFilter = filterType::New();
gaussianFilter->SetInput(image);
gaussianFilter->SetUseImageSpacingOn();
gaussianFilter->SetMaximumKernelWidth(128);
gaussianFilter->SetVariance(sigma * sigma);
gaussianFilter->Update();
return gaussianFilter->GetOutput();
}
static ImagePointer MedianFilterImage(
ImagePointer image,
double radius)
{
if(radius <= 0.0)
return image;
typedef itk::MedianImageFilter<
ImageType, ImageType>
FilterType;
// Create and setup a Gaussian filter
typename FilterType::Pointer filter = FilterType::New();
auto spacing = image->GetSpacing();
typename FilterType::InputSizeType rad;
for (unsigned int i = 0; i < Dim; ++i) {
rad[i] = static_cast<typename ImageType::SizeValueType>(spacing[i] * radius + 0.5);
if(rad[i] == 0) {
return image;
}
}
filter->SetInput(image);
filter->SetRadius(rad);
filter->Update();
return filter->GetOutput();
}
static void SaturateImage(
ImagePointer image,
ValueType lower,
ValueType upper)
{
itk::ImageRegionIterator<ImageType> writeIter(image, image->GetRequestedRegion());
writeIter.GoToBegin();
while (!writeIter.IsAtEnd())
{
if (writeIter.Get() < lower)
writeIter.Set(lower);
if (writeIter.Get() > upper)
writeIter.Set(upper);
++writeIter;
}
}
static void SaturateLabelImage(
LabelImagePointer image,
unsigned short lower,
unsigned short upper)
{
itk::ImageRegionIterator<LabelImageType> writeIter(image, image->GetRequestedRegion());
writeIter.GoToBegin();
while (!writeIter.IsAtEnd())
{
if (writeIter.Get() < lower)
writeIter.Set(lower);
if (writeIter.Get() > upper)
writeIter.Set(upper);
++writeIter;
}
}
static ImagePointer SubtractImage(
ImagePointer image1,
ImagePointer image2)
{
typedef itk::SubtractImageFilter<ImageType, ImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer f = FilterType::New();
f->SetInput1(image1);
f->SetInput2(image2);
f->Update();
return f->GetOutput();
}
static ImagePointer BandpassFilterImage(
ImagePointer image,
double lo_sigma,
double hi_sigma)
{
ImagePointer i1 = SmoothImage(image, hi_sigma);
ImagePointer i2;
if (lo_sigma > 0.0)
i2 = SmoothImage(image, lo_sigma);
else
i2 = image;
ImagePointer i3 = SubtractImage(i2, i1);
SaturateImage(i3, 0.0, 1.0);
return i3;
}
static ImagePointer MatchHistogram(
ImagePointer reference,
ImagePointer source,
itk::SizeValueType bins,
itk::SizeValueType matchPoints)
{
typedef itk::HistogramMatchingImageFilter<ImageType, ImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer f = FilterType::New();
f->SetReferenceImage(reference);
f->SetSourceImage(source);
f->SetNumberOfHistogramLevels(bins);
f->SetNumberOfMatchPoints(matchPoints);
f->Update();
return f->GetOutput();
}
// TODO: COMPLETE THIS
static PointSetType LoadPointSet(
const char *path,
bool skipHeaderRow = false)
{
PointSetType points;
itk::CSVFile csv = itk::ReadCSV(path);
if(csv.success == false) {
std::cout << "Failed to read file." << std::endl;
}
size_t i = skipHeaderRow ? 1U : 0U;
for(; i < csv.contents.size(); ++i) {
std::vector<std::string> row = csv.contents[i];
PointType p;
if(row.size() == 0U) {
continue;
}
if(row.size() == Dim + 1) { // Assume a row header
for (unsigned int j = 0; j < Dim; ++j)
{
if(row[j+1].empty()) {
p[j] = NAN;
} else {
p[j] = atof(row[j+1].c_str());
}
}
} else if(row.size() == Dim) { // No row header
for (unsigned int j = 0; j < Dim; ++j)
{
if(row[j].empty()) {
p[j] = NAN;
} else {
p[j] = atof(row[j].c_str());
}
}
} else {
std::cout << "Row " << i << " contains an illegal number of entries" << std::endl;
return points;
}
points.push_back(p);
}
return points;
}
/*
typedef itk::CSVArray2DFileReader<double> ReaderType;
typedef typename ReaderType::Pointer ReaderPointer;
typedef itk::CSVArray2DDataObject<double> DataFrameObjectType;
typedef typename DataFrameObjectType::Pointer DataFrameObjectPointer;
ReaderPointer reader = ReaderType::New();
reader->SetFileName(path);
reader->SetFieldDelimiterCharacter(',');
reader->HasColumnHeadersOff();
reader->HasRowHeadersOff();
reader->UseStringDelimiterCharacterOff();
std::cout << "Before parsing" << std::endl;
reader->Parse();
reader->Update();
DataFrameObjectPointer dfo = reader->GetOutput();
std::cout << "File loaded" << std::endl;
unsigned int i = 0;
while (true)
{
try
{
std::vector<double> vec = dfo->GetRow(i);
if (vec.empty())
break;
PointType p;
for (unsigned int j = 0; j < Dim; ++j)
{
p[j] = vec.at(j);
}
points.push_back(p);
++i;
}
catch (itk::ExceptionObject &e)
{
std::cout << e << std::endl;
break;
}
}
//ArrayRawPointer arr = reader->GetOutput();
//ArrayType matrix = arr->GetMatrix();
//matrix->GetData(row, column);
// arr->GetData(row, column)
//unsigned int columns = reeader->GetColumnHeaders().size();
//unsigned int rows = reeader->GetRowHeaders().size();
return points;
}*/
static void SavePointSet(
const char* path,
PointSetType& pointSet)
{
FILE *f = fopen(path, "wb");
if(f) {
for(size_t i = 0; i < pointSet.size(); ++i) {
fprintf(f, "%.7f", pointSet[i][0]);
for(unsigned int j = 1; j < Dim; ++j) {
fprintf(f, ",%.7f", pointSet[i][j]);
}
if(i + 1 < pointSet.size()) {
fprintf(f, "\n");
}
}
fclose(f);
}
}
enum SpacingMode
{
kDefaultSpacingMode,
kRemoveSpacingMode,
kResampleSpacingMode
};
static ImagePointer RemoveSpacing(
ImagePointer image,
SpacingMode mode = kDefaultSpacingMode)
{
typename ImageType::SpacingType spacing = image->GetSpacing();
bool all_are_unit = true;
for (unsigned int i = 0; i < Dim; ++i)
{
if (!itk::Math::AlmostEquals<double, double>(spacing[i], 1.0))
{
all_are_unit = false;
break;
}
}
if (all_are_unit)
return image;
if (mode == kResampleSpacingMode)
{
typedef itk::AffineTransform<double, Dim> AffineTransformType;
typedef typename AffineTransformType::Pointer AffineTransformPointer;
AffineTransformPointer transform = AffineTransformType::New();
typename AffineTransformType::ParametersType parameters(Dim * Dim + Dim);
parameters.Fill(0);
transform->SetParameters(parameters);
transform->SetIdentity();
VectorType scaleVec;
for (unsigned int i = 0; i < Dim; ++i)
{
scaleVec[i] = 1.0 / spacing[i];
}
transform->Scale(scaleVec);
PointType origin;
origin.Fill(0.0);
typename ImageType::SizeType sz = GetImageSize(image);
for (unsigned int i = 0; i < Dim; ++i)
{
sz[i] = (itk::SizeValueType)(sz[i] * (spacing[i]));
}
ImagePointer result = IPT::TransformImage(image, itk::CastSmartPointer<itk::AffineTransform<double, Dim>, itk::Transform<double, Dim, Dim>>(transform), origin, sz, kImwarpInterpLinear);
return RemoveSpacing(result, kRemoveSpacingMode);
}
else if (mode == kRemoveSpacingMode)
{
for (unsigned int i = 0; i < Dim; ++i)
{
spacing[i] = 1;
}
typedef itk::ChangeInformationImageFilter<ImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer filter = FilterType::New();
filter->SetInput(image);
filter->SetOutputSpacing(spacing);
filter->ChangeSpacingOn();
filter->Update();
return filter->GetOutput();
}
else
{
return image;
}
}
static LabelImagePointer RemoveLabelSpacing(
LabelImagePointer image,
SpacingMode mode = kDefaultSpacingMode)
{
typename LabelImageType::SpacingType spacing = image->GetSpacing();
bool all_are_unit = true;
for (unsigned int i = 0; i < Dim; ++i)
{
if (!itk::Math::AlmostEquals<double, double>(spacing[i], 1.0))
{
all_are_unit = false;
break;
}
}
if (all_are_unit)
return image;
if (mode == kResampleSpacingMode)
{
typedef itk::AffineTransform<double, Dim> AffineTransformType;
typedef typename AffineTransformType::Pointer AffineTransformPointer;
AffineTransformPointer transform = AffineTransformType::New();
typename AffineTransformType::ParametersType parameters(Dim * Dim + Dim);
parameters.Fill(0);
transform->SetParameters(parameters);
transform->SetIdentity();
VectorType scaleVec;
for (unsigned int i = 0; i < Dim; ++i)
{
scaleVec[i] = 1.0 / spacing[i];
}
transform->Scale(scaleVec);
PointType origin;
origin.Fill(0.0);
typename LabelImageType::SizeType sz = image->GetLargestPossibleRegion().GetSize(); //GetImageSize(image);
for (unsigned int i = 0; i < Dim; ++i)
{
sz[i] = (itk::SizeValueType)(sz[i] * (spacing[i]));
}
LabelImagePointer result = IPT::TransformLabelImage(image, itk::CastSmartPointer<itk::AffineTransform<double, Dim>, itk::Transform<double, Dim, Dim>>(transform), origin, sz);
return RemoveLabelSpacing(result, kRemoveSpacingMode);
}
else if (mode == kRemoveSpacingMode)
{
for (unsigned int i = 0; i < Dim; ++i)
{
spacing[i] = 1;
}
typedef itk::ChangeInformationImageFilter<LabelImageType> FilterType;
typedef typename FilterType::Pointer FilterPointer;
FilterPointer filter = FilterType::New();
filter->SetInput(image);
filter->SetOutputSpacing(spacing);
filter->ChangeSpacingOn();
filter->Update();
return filter->GetOutput();
}
else
{
return image;
}
}
static bool StringHasPrefix(const char* str, const char* prefix) {
while(*prefix) {
if(*str) {
if(*str != *prefix) {
return false;
} else {
++str;
++prefix;
}
} else {
return false;
}
}
return true;
}
// TODO: Finish the transform extraction functions
// BEGIN HERE
static unsigned int GetTransformCount(
BaseTransformPointer transform)
{
if(!transform)
return 0U;
if(StringHasPrefix(transform->GetNameOfClass(), "CompositeTransform")) {
CompositeTransformPointer tf = static_cast<CompositeTransformType*>(transform.GetPointer());
return tf->GetNumberOfTransforms();
} else {
return 1U;
}
}
static BaseTransformPointer GetNthTransform(
BaseTransformPointer transform,
unsigned int index)
{
if(StringHasPrefix(transform->GetNameOfClass(), "CompositeTransform")) {
CompositeTransformPointer tf = static_cast<CompositeTransformType*>(transform.GetPointer());
return tf->GetNthTransform(index);
} else if(index == 0) {
return transform;
} else {
return nullptr;
}
}
//static BaseTransformPointer ConvertTransformToAffine(
// BaseTransformPointer transform)
//{
//}
// END HERE
static void SaveTransformFile(
const char* path,
BaseTransformPointer transform)
{
typedef itk::TransformFileWriterTemplate<double> TransformWriterType;
TransformWriterType::Pointer writer = TransformWriterType::New();
writer->SetInput(transform);
writer->SetFileName(path);
writer->Update();
}
static BaseTransformPointer LoadTransformFile(
const char* path)
{
typedef itk::TransformFileReaderTemplate<double> TransformReaderType;
TransformReaderType::Pointer reader = TransformReaderType::New();
reader->SetFileName(path);
reader->Update();
typedef typename TransformReaderType::TransformListType* const TransformListRawPointer;
TransformListRawPointer transforms = reader->GetTransformList();
typedef itk::CompositeTransform<double, Dim> CompositeTransformType;
typedef typename CompositeTransformType::Pointer CompositeTransformPointer;
auto it = transforms->begin();
auto itEnd = transforms->end();
if(it == itEnd) {
CompositeTransformPointer composite = CompositeTransformType::New();
return static_cast< BaseTransformType* >(composite.GetPointer() );
} else {
auto itPlusOne = it;
++itPlusOne;
if(itPlusOne == itEnd) {
return static_cast< BaseTransformType* >((*it).GetPointer());
} else {
CompositeTransformPointer composite = CompositeTransformType::New();
for(; it != itEnd; ++it) {
composite->AddTransform(static_cast<BaseTransformType*>((*it).GetPointer()));
}
return static_cast< BaseTransformType* >(composite.GetPointer());
}
}
}
};
template <typename PixelType, unsigned short Dim>
inline void Save3DImageSlicesU8(
const char *path,
const char *name,
const char *type,
typename itk::Image<PixelType, Dim>::Pointer image)
{
assert(Dim == 3U);
char buf[512];
typename itk::Image<PixelType, Dim>::SizeType sz = image->GetLargestPossibleRegion().GetSize();
typedef PixelType ValueType;
sprintf(buf, "%s%s_xy.%s", path, name, type);
itk::IPT<ValueType, Dim - 1>::SaveImageU8(buf, itk::ExtractSlice<ValueType, Dim>(image, 2, sz[2] / 2));
sprintf(buf, "%s%s_xz.%s", path, name, type);
itk::IPT<ValueType, Dim - 1>::SaveImageU8(buf, itk::ExtractSlice<ValueType, Dim>(image, 1, sz[1] / 2));
sprintf(buf, "%s%s_yz.%s", path, name, type);
itk::IPT<ValueType, Dim - 1>::SaveImageU8(buf, itk::ExtractSlice<ValueType, Dim>(image, 0, sz[0] / 2));
}
template <unsigned short Dim>
inline void Save3DLabelImageSlices(
const char *path,
const char *name,
const char *type,
typename itk::Image<unsigned short, Dim>::Pointer image)
{
assert(Dim == 3U);
char buf[512];
typename itk::Image<unsigned short, Dim>::SizeType sz = image->GetLargestPossibleRegion().GetSize();
typedef double ValueType;
sprintf(buf, "%s%s_label_xy.%s", path, name, type);
itk::IPT<ValueType, Dim - 1>::SaveLabelImage(buf, itk::ExtractSlice<unsigned short, Dim>(image, 2, sz[2] / 2));
sprintf(buf, "%s%s_label_xz.%s", path, name, type);
itk::IPT<ValueType, Dim - 1>::SaveLabelImage(buf, itk::ExtractSlice<unsigned short, Dim>(image, 1, sz[1] / 2));
sprintf(buf, "%s%s_label_yz.%s", path, name, type);
itk::IPT<ValueType, Dim - 1>::SaveLabelImage(buf, itk::ExtractSlice<unsigned short, Dim>(image, 0, sz[0] / 2));
}
/**
* Parsing routines for reading strings of numbers of the form '4x2x1' and '2.0x1.0x0.0'
* for reading sequences of numbers as command-line parameters.
*/
inline std::vector<std::string> SplitOnX(
const std::string& s)
{
std::vector<std::string> result;
size_t cur = 0;
size_t start = 0;
size_t len = s.length();
while(cur < len) {
char c = s[cur];
if(c == 'x') {
result.push_back(s.substr(start, cur-start));
start = cur + 1;
}
++cur;
}
if(start < cur) {
result.push_back(s.substr(start, cur-start));
}
return result;
}
inline std::vector<unsigned int> ParseSamplingFactors(
const std::string& s)
{
std::vector<unsigned int> result;
std::vector<std::string> tokens = SplitOnX(s);
for(size_t i = 0; i < tokens.size(); ++i) {
result.push_back( static_cast<unsigned int>( atoi(tokens[i].c_str() ) ) );
}
return result;
}
inline std::vector<double> ParseSmoothingSigmas(
const std::string& s)
{
std::vector<double> result;
std::vector<std::string> tokens = SplitOnX(s);
for(size_t i = 0; i < tokens.size(); ++i)
{
result.push_back(atof(tokens[i].c_str()));
}
return result;
}
}
inline double VectorMean(
std::vector<double>& v)
{
double s = 0.0;
for(size_t i = 0; i < v.size(); ++i)
{
s += v[i];
}
if(v.size() > 0)
{
return s / v.size();
} else {
return s;
}
}
inline double VectorStdDev(
std::vector<double>& v,
double mean)
{
double s = 0.0;
for(size_t i = 0; i < v.size(); ++i)
{
double x = v[i] - mean;
s += x * x;
}
if(v.size() <= 1)
{
return 0.0;
} else {
return sqrt(s / (v.size() - 1));
}
}
#endif
| 29.005185 | 207 | 0.580382 | [
"object",
"vector",
"transform"
] |
1915a8c7a6c4712062921043eeebb57ad1716e65 | 14,721 | h | C | storage_engine.h | klundeen/5300-Butterfly | 06bec6c459f48956ab8e02903b4bde235ad5fbdf | [
"MIT"
] | 2 | 2018-07-22T22:44:18.000Z | 2020-04-02T23:58:20.000Z | storage_engine.h | klundeen/5300-Dolphin | fb64d69e27cde56009db9e4709c942356d279048 | [
"MIT"
] | null | null | null | storage_engine.h | klundeen/5300-Dolphin | fb64d69e27cde56009db9e4709c942356d279048 | [
"MIT"
] | 5 | 2019-07-07T00:45:50.000Z | 2021-04-20T02:24:08.000Z | /**
* @file storage_engine.h - Storage engine abstract classes.
* DbBlock
* DbFile
* DbRelation
*
* @author Kevin Lundeen
* @see "Seattle University, CPSC5300, Spring 2021"
*/
#pragma once
#include <exception>
#include <map>
#include <utility>
#include <vector>
#include "db_cxx.h"
/**
* Global variable to hold dbenv.
*/
extern DbEnv *_DB_ENV;
/*
* Convenient aliases for types
*/
typedef u_int16_t RecordID;
typedef u_int32_t BlockID;
typedef std::vector<RecordID> RecordIDs;
typedef std::length_error DbBlockNoRoomError;
/**
* @class DbBlock - abstract base class for blocks in our database files
* (DbBlock's belong to DbFile's.)
*
* Methods for putting/getting records in blocks:
* add(data)
* get(record_id)
* put(record_id, data)
* del(record_id)
* ids()
* Accessors:
* get_block()
* get_data()
* get_block_id()
*/
class DbBlock {
public:
/**
* our blocks are 4kB
*/
static const uint BLOCK_SZ = 4096;
/**
* ctor/dtor (subclasses should handle the big-5)
*/
DbBlock(Dbt &block, BlockID block_id, bool is_new = false) : block(block), block_id(block_id) {}
virtual ~DbBlock() {}
/**
* Add a new record to this block.
* @param data the data to store for the new record
* @returns the new RecordID for the new record
* @throws DbBlockNoRoomError if insufficient room in the block
*/
virtual RecordID add(const Dbt *data) = 0;
/**
* Get a record from this block.
* @param record_id which record to fetch
* @returns the data stored for the given record
*/
virtual Dbt *get(RecordID record_id) const = 0;
/**
* Change the data stored for a record in this block.
* @param record_id which record to update
* @param data the new data to store for the given record
* @throws DbBlockNoRoomError if insufficient room in the block
* (old record is retained)
*/
virtual void put(RecordID record_id, const Dbt &data) = 0;
/**
* Delete a record from this block.
* @param record_id which record to delete
*/
virtual void del(RecordID record_id) = 0;
/**
* Get all the record ids in this block (excluding deleted ones).
* @returns pointer to list of record ids (freed by caller)
*/
virtual RecordIDs *ids() const = 0;
/**
* Delete all the records from this block.
*/
virtual void clear() = 0;
/**
* Get number of active (undeleted) records in this block.
* @returns number of active records
*/
virtual u_int16_t size() const = 0;
/**
* Get the number of bytes not currently used to store data or for overhead.
* @returns number of unused bytes
*/
virtual u_int16_t unused_bytes() const = 0;
/**
* Access the whole block's memory as a BerkeleyDB Dbt pointer.
* @returns Dbt used by this block
*/
virtual Dbt *get_block() { return █ }
/**
* Access the whole block's memory within the BerkeleyDb Dbt.
* @returns Raw byte stream of this block
*/
virtual void *get_data() { return block.get_data(); }
/**
* Get this block's BlockID within its DbFile.
* @returns this block's id
*/
virtual BlockID get_block_id() { return block_id; }
protected:
Dbt block;
BlockID block_id;
};
// convenience type alias
typedef std::vector<BlockID> BlockIDs; // FIXME: will need to turn this into an iterator at some point
/**
* @class DbFile - abstract base class which represents a disk-based collection of DbBlocks
* create()
* drop()
* open()
* close()
* get_new()
* get(block_id)
* put(block)
* block_ids()
*/
class DbFile {
public:
// ctor/dtor -- subclasses should handle big-5
DbFile(std::string name) : name(name) {}
virtual ~DbFile() {}
/**
* Create the file.
*/
virtual void create() = 0;
/**
* Remove the file.
*/
virtual void drop() = 0;
/**
* Open the file.
*/
virtual void open() = 0;
/**
* Close the file.
*/
virtual void close() = 0;
/**
* Add a new block for this file.
* @returns the newly appended block
*/
virtual DbBlock *get_new() = 0;
/**
* Get a specific block in this file.
* @param block_id which block to get
* @returns pointer to the DbBlock (freed by caller)
*/
virtual DbBlock *get(BlockID block_id) = 0;
/**
* Write a block to this file (the block knows its BlockID)
* @param block block to write (overwrites existing block on disk)
*/
virtual void put(DbBlock *block) = 0;
/**
* Get a list of all the valid BlockID's in the file
* FIXME - not a good long-term approach, but we'll do this until we put in iterators
* @returns a pointer to vector of BlockIDs (freed by caller)
*/
virtual BlockIDs *block_ids() const = 0;
protected:
std::string name; // filename (or part of it)
};
/**
* @class ColumnAttribute - holds datatype and other info for a column
*/
class ColumnAttribute {
public:
enum DataType {
INT, TEXT, BOOLEAN
};
ColumnAttribute() : data_type(INT) {}
ColumnAttribute(DataType data_type) : data_type(data_type) {}
virtual ~ColumnAttribute() {}
virtual DataType get_data_type() { return data_type; }
virtual void set_data_type(DataType data_type) { this->data_type = data_type; }
protected:
DataType data_type;
};
/**
* @class Value - holds value for a field
*/
class Value {
public:
ColumnAttribute::DataType data_type;
int32_t n;
std::string s;
Value() : n(0) { data_type = ColumnAttribute::INT; }
Value(int32_t n) : n(n) { data_type = ColumnAttribute::INT; }
Value(std::string s) : s(s) { data_type = ColumnAttribute::TEXT; }
bool operator==(const Value &other) const;
bool operator!=(const Value &other) const;
bool operator<(const Value &other) const;
friend std::ostream &operator<<(std::ostream &out, const Value &value);
};
// More type aliases
typedef std::string Identifier;
typedef std::vector<Identifier> ColumnNames;
typedef std::vector<ColumnAttribute> ColumnAttributes;
typedef std::pair<BlockID, RecordID> Handle;
typedef std::vector<Handle> Handles; // FIXME: will need to turn this into an iterator at some point
typedef std::map<Identifier, Value> ValueDict;
typedef std::vector<ValueDict *> ValueDicts;
/**
* @class DbRelationError - generic exception class for DbRelation
*/
class DbRelationError : public std::runtime_error {
public:
explicit DbRelationError(std::string s) : runtime_error(s) {}
};
/**
* @class DbRelation - top-level object handling a physical database relation
*
* Methods:
* create()
* create_if_not_exists()
* drop()
*
* open()
* close()
*
* insert(row)
* update(handle, new_values)
* del(handle)
* select()
* select(where)
* project(handle)
* project(handle, column_names)
*/
class DbRelation {
public:
// ctor/dtor
DbRelation(Identifier table_name, ColumnNames column_names, ColumnAttributes column_attributes) : table_name(
table_name), column_names(column_names), column_attributes(column_attributes) {}
virtual ~DbRelation() {}
/**
* Execute: CREATE TABLE <table_name> ( <columns> )
* Assumes the metadata and validation are already done.
*/
virtual void create() = 0;
/**
* Execute: CREATE TABLE IF NOT EXISTS <table_name> ( <columns> )
* Assumes the metadata and validate are already done.
*/
virtual void create_if_not_exists() = 0;
/**
* Execute: DROP TABLE <table_name>
*/
virtual void drop() = 0;
/**
* Open existing table.
* Enables: insert, update, del, select, project.
*/
virtual void open() = 0;
/**
* Closes an open table.
* Disables: insert, update, del, select, project.
*/
virtual void close() = 0;
/**
* Execute: INSERT INTO <table_name> ( <row_keys> ) VALUES ( <row_values> )
* @param row a dictionary keyed by column names
* @returns a handle to the new row
*/
virtual Handle insert(const ValueDict *row) = 0;
/**
* Conceptually, execute: UPDATE INTO <table_name> SET <new_values> WHERE <handle>
* where handle is sufficient to identify one specific record (e.g., returned
* from an insert or select).
* @param handle the row to update
* @param new_values a dictionary keyed by column names for changing columns
*/
virtual void update(const Handle handle, const ValueDict *new_values) = 0;
/**
* Conceptually, execute: DELETE FROM <table_name> WHERE <handle>
* where handle is sufficient to identify one specific record (e.g, returned
* from an insert or select).
* @param handle the row to delete
*/
virtual void del(const Handle handle) = 0;
/**
* Conceptually, execute: SELECT <handle> FROM <table_name> WHERE 1
* @returns a pointer to a list of handles for qualifying rows (caller frees)
*/
virtual Handles *select() = 0;
/**
* Conceptually, execute: SELECT <handle> FROM <table_name> WHERE <where>
* @param where where-clause predicates
* @returns a pointer to a list of handles for qualifying rows (freed by caller)
*/
virtual Handles *select(const ValueDict *where) = 0;
/**
* Conceptually, execute: SELECT <handle> FROM <table_name> WHERE <where>
* This version does a restricted selection based on current_selection.
* @param current_selection restrict selection to be from these rows
* @param where where-clause predicates
* @returns a pointer to a list of handles for qualifying rows (freed by caller)
*/
virtual Handles *select(Handles *current_selection, const ValueDict *where) = 0;
/**
* Return a sequence of all values for handle (SELECT *).
* @param handle row to get values from
* @returns dictionary of values from row (keyed by all column names)
*/
virtual ValueDict *project(Handle handle) = 0;
/**
* Return a sequence of values for handle given by column_names
* (SELECT <column_names>).
* @param handle row to get values from
* @param column_names list of column names to project
* @returns dictionary of values from row (keyed by column_names)
*/
virtual ValueDict *project(Handle handle, const ColumnNames *column_names) = 0;
/**
* Return a sequence of values for handle given by column_names (from dictionary)
* (SELECT <column_names>).
* @param handle row to get values from
* @param column_names list of column names to project (taken from keys of dict)
* @return dictionary of values from row (keyed by column_names)
*/
virtual ValueDict *project(Handle handle, const ValueDict *column_names);
// additional versions of project for multiple rows
virtual ValueDicts *project(Handles *handles);
virtual ValueDicts *project(Handles *handles, const ColumnNames *column_names);
virtual ValueDicts *project(Handles *handles, const ValueDict *column_names);
/**
* Accessor for column_names.
* @returns column_names list of column names for this relation, in order
*/
virtual const ColumnNames &get_column_names() const {
return column_names;
}
/**
* Accessor for column_attributes.
* @returns column_attributes dictionary of column attributes keyed by column names
*/
virtual const ColumnAttributes get_column_attributes() const {
return column_attributes;
}
/**
* A version of accessor for column_attributes that further
* restricts returned attributes to a subset of columns.
* @param select_column_names list of column names to get attributes for
* @returns column_attributes dictionary of column attributes keyed
* by column names
*/
virtual ColumnAttributes *get_column_attributes(const ColumnNames &select_column_names) const;
/**
* Accessor method for table_name
* @returns table_name
*/
virtual Identifier get_table_name() const {
return table_name;
}
protected:
Identifier table_name;
ColumnNames column_names;
ColumnAttributes column_attributes;
};
class DbIndex {
public:
/**
* Maximum number of columns in a composite index
*/
static const uint MAX_COMPOSITE = 32U;
// ctor/dtor
DbIndex(DbRelation &relation, Identifier name, ColumnNames key_columns, bool unique) : relation(relation),
name(name),
key_columns(key_columns),
unique(unique) {}
virtual ~DbIndex() {}
/**
* Create this index.
*/
virtual void create() = 0;
/**
* Drop this index.
*/
virtual void drop() = 0;
/**
* Open this index.
*/
virtual void open() = 0;
/**
* Close this index.
*/
virtual void close() = 0;
/**
* Lookup a specific search key.
* @param key_values dictionary of values for the search key
* @returns list of DbFile handles for records with key_values
*/
virtual Handles *lookup(ValueDict *key_values) const = 0;
/**
* Lookup a range of search keys.
* @param min_key dictionary of min (inclusive) search key
* @param max_key dictionary of max (inclusive) search key
* @returns list of DbFile handles for records in range
*/
virtual Handles *range(ValueDict *min_key, ValueDict *max_key) const {
throw DbRelationError("range index query not supported");
}
/**
* Insert the index entry for the given record.
* @param record handle (into relation) to the record to insert
* (must be in the relation at time of insertion)
*/
virtual void insert(Handle record) = 0;
/**
* Delete the index entry for the given record.
* @param record handle (into relation) to the record to remove
* (must still be in the relation at time of removal)
*/
virtual void del(Handle record) = 0;
protected:
DbRelation &relation;
Identifier name;
ColumnNames key_columns;
bool unique;
};
| 28.255278 | 116 | 0.627131 | [
"object",
"vector"
] |
191638de38b5c412bc118120868656730f851f5a | 8,588 | h | C | src/feat/feature-functions.h | boostpapa/kaldi | 1727fa234ef505b8550cab991e30c5ee6aaff64d | [
"Apache-2.0"
] | 1 | 2021-04-29T16:09:26.000Z | 2021-04-29T16:09:26.000Z | src/feat/feature-functions.h | boostpapa/kaldi | 1727fa234ef505b8550cab991e30c5ee6aaff64d | [
"Apache-2.0"
] | 2 | 2019-04-09T06:57:51.000Z | 2019-04-09T07:12:48.000Z | src/feat/feature-functions.h | ishine/kaldi | 1845b94477c1ca0066797c320bf4eaf56cbd75cc | [
"Apache-2.0"
] | 2 | 2017-08-20T10:24:05.000Z | 2019-02-28T02:48:53.000Z | // feat/feature-functions.h
// Copyright 2009-2011 Karel Vesely; Petr Motlicek; Microsoft Corporation
// 2014 IMSL, PKU-HKUST (author: Wei Shi)
// 2016 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_FEAT_FEATURE_FUNCTIONS_H_
#define KALDI_FEAT_FEATURE_FUNCTIONS_H_
#include <string>
#include <vector>
#include "matrix/matrix-lib.h"
#include "util/common-utils.h"
#include "base/kaldi-error.h"
namespace kaldi {
/// @addtogroup feat FeatureExtraction
/// @{
// ComputePowerSpectrum converts a complex FFT (as produced by the FFT
// functions in matrix/matrix-functions.h), and converts it into
// a power spectrum. If the complex FFT is a vector of size n (representing
// half the complex FFT of a real signal of size n, as described there),
// this function computes in the first (n/2) + 1 elements of it, the
// energies of the fft bins from zero to the Nyquist frequency. Contents of the
// remaining (n/2) - 1 elements are undefined at output.
void ComputePowerSpectrum(VectorBase<BaseFloat> *complex_fft);
struct DeltaFeaturesOptions {
int32 order;
int32 window; // e.g. 2; controls window size (window size is 2*window + 1)
// the behavior at the edges is to replicate the first or last frame.
// this is not configurable.
DeltaFeaturesOptions(int32 order = 2, int32 window = 2):
order(order), window(window) { }
void Register(OptionsItf *opts) {
opts->Register("delta-order", &order, "Order of delta computation");
opts->Register("delta-window", &window,
"Parameter controlling window for delta computation (actual window"
" size for each delta order is 1 + 2*delta-window-size)");
}
};
class DeltaFeatures {
public:
// This class provides a low-level function to compute delta features.
// The function takes as input a matrix of features and a frame index
// that it should compute the deltas on. It puts its output in an object
// of type VectorBase, of size (original-feature-dimension) * (opts.order+1).
// This is not the most efficient way to do the computation, but it's
// state-free and thus easier to understand
explicit DeltaFeatures(const DeltaFeaturesOptions &opts);
void Process(const MatrixBase<BaseFloat> &input_feats,
int32 frame,
VectorBase<BaseFloat> *output_frame) const;
private:
DeltaFeaturesOptions opts_;
std::vector<Vector<BaseFloat> > scales_; // a scaling window for each
// of the orders, including zero: multiply the features for each
// dimension by this window.
};
struct ShiftedDeltaFeaturesOptions {
int32 window, // The time delay and advance
num_blocks,
block_shift; // Distance between consecutive blocks
ShiftedDeltaFeaturesOptions():
window(1), num_blocks(7), block_shift(3) { }
void Register(OptionsItf *opts) {
opts->Register("delta-window", &window, "Size of delta advance and delay.");
opts->Register("num-blocks", &num_blocks, "Number of delta blocks in advance"
" of each frame to be concatenated");
opts->Register("block-shift", &block_shift, "Distance between each block");
}
};
class ShiftedDeltaFeatures {
public:
// This class provides a low-level function to compute shifted
// delta cesptra (SDC).
// The function takes as input a matrix of features and a frame index
// that it should compute the deltas on. It puts its output in an object
// of type VectorBase, of size original-feature-dimension + (1 * num_blocks).
explicit ShiftedDeltaFeatures(const ShiftedDeltaFeaturesOptions &opts);
void Process(const MatrixBase<BaseFloat> &input_feats,
int32 frame,
SubVector<BaseFloat> *output_frame) const;
private:
ShiftedDeltaFeaturesOptions opts_;
Vector<BaseFloat> scales_; // a scaling window for each
};
// ComputeDeltas is a convenience function that computes deltas on a feature
// file. If you want to deal with features coming in bit by bit you would have
// to use the DeltaFeatures class directly, and do the computation frame by
// frame. Later we will have to come up with a nice mechanism to do this for
// features coming in.
void ComputeDeltas(const DeltaFeaturesOptions &delta_opts,
const MatrixBase<BaseFloat> &input_features,
Matrix<BaseFloat> *output_features);
// ComputeShiftedDeltas computes deltas from a feature file by applying
// ShiftedDeltaFeatures over the frames. This function is provided for
// convenience, however, ShiftedDeltaFeatures can be used directly.
void ComputeShiftedDeltas(const ShiftedDeltaFeaturesOptions &delta_opts,
const MatrixBase<BaseFloat> &input_features,
Matrix<BaseFloat> *output_features);
// SpliceFrames will normally be used together with LDA.
// It splices frames together to make a window. At the
// start and end of an utterance, it duplicates the first
// and last frames.
// Will throw if input features are empty.
// left_context and right_context must be nonnegative.
// these both represent a number of frames (e.g. 4, 4 is
// a good choice).
void SpliceFrames(const MatrixBase<BaseFloat> &input_features,
int32 left_context,
int32 right_context,
Matrix<BaseFloat> *output_features);
// ReverseFrames reverses the frames in time (used for backwards decoding)
void ReverseFrames(const MatrixBase<BaseFloat> &input_features,
Matrix<BaseFloat> *output_features);
void InitIdftBases(int32 n_bases, int32 dimension, Matrix<BaseFloat> *mat_out);
// This is used for speaker-id. Also see OnlineCmnOptions in ../online2/, which
// is online CMN with no latency, for online speech recognition.
struct SlidingWindowCmnOptions {
int32 cmn_window;
int32 min_window;
int32 update_window;
int32 max_warnings;
bool normalize_variance;
bool center;
SlidingWindowCmnOptions():
cmn_window(600),
min_window(100),
update_window(0),
max_warnings(5),
normalize_variance(false),
center(false) { }
void Register(OptionsItf *opts) {
opts->Register("cmn-window", &cmn_window, "Window in frames for running "
"average CMN computation");
opts->Register("min-cmn-window", &min_window, "Minimum CMN window "
"used at start of decoding (adds latency only at start). "
"Only applicable if center == false, ignored if center==true");
opts->Register("update-window", &update_window, "Window in frames for update CMN");
opts->Register("max-warnings", &max_warnings, "Maximum warnings to report "
"per utterance. 0 to disable, -1 to show all.");
opts->Register("norm-vars", &normalize_variance, "If true, normalize "
"variance to one."); // naming this as in apply-cmvn.cc
opts->Register("center", ¢er, "If true, use a window centered on the "
"current frame (to the extent possible, modulo end effects). "
"If false, window is to the left.");
}
void Check() const;
};
/// Applies sliding-window cepstral mean and/or variance normalization. See the
/// strings registering the options in the options class for information on how
/// this works and what the options are. input and output must have the same
/// dimension.
void SlidingWindowCmn(const SlidingWindowCmnOptions &opts,
const MatrixBase<BaseFloat> &input,
MatrixBase<BaseFloat> *output, const Matrix<double> *global_stats = NULL);
void SlidingWindowCmnHTK(const SlidingWindowCmnOptions &opts,
const MatrixBase<BaseFloat> &input,
MatrixBase<BaseFloat> *output);
/// @} End of "addtogroup feat"
} // namespace kaldi
#endif // KALDI_FEAT_FEATURE_FUNCTIONS_H_
| 40.895238 | 96 | 0.700862 | [
"object",
"vector"
] |
191a50f79b3abbfad5c4250e33a59e4fa5c524ad | 3,458 | h | C | ios/versioned-react-native/ABI28_0_0/React/Base/ABI28_0_0RCTJavaScriptLoader.h | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 2 | 2019-05-23T20:39:18.000Z | 2019-05-24T14:00:32.000Z | ios/versioned-react-native/ABI28_0_0/React/Base/ABI28_0_0RCTJavaScriptLoader.h | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 2 | 2022-02-14T18:22:55.000Z | 2022-02-26T02:17:58.000Z | ios/versioned-react-native/ABI28_0_0/React/Base/ABI28_0_0RCTJavaScriptLoader.h | ThakurKarthik/expo | ed78ed4f07c950184a59422ebd95645253f44e3d | [
"Apache-2.0",
"MIT"
] | 1 | 2020-03-01T01:28:59.000Z | 2020-03-01T01:28:59.000Z | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <ReactABI28_0_0/ABI28_0_0RCTDefines.h>
extern NSString *const ABI28_0_0RCTJavaScriptLoaderErrorDomain;
NS_ENUM(NSInteger) {
ABI28_0_0RCTJavaScriptLoaderErrorNoScriptURL = 1,
ABI28_0_0RCTJavaScriptLoaderErrorFailedOpeningFile = 2,
ABI28_0_0RCTJavaScriptLoaderErrorFailedReadingFile = 3,
ABI28_0_0RCTJavaScriptLoaderErrorFailedStatingFile = 3,
ABI28_0_0RCTJavaScriptLoaderErrorURLLoadFailed = 3,
ABI28_0_0RCTJavaScriptLoaderErrorBCVersion = 4,
ABI28_0_0RCTJavaScriptLoaderErrorBCNotSupported = 4,
ABI28_0_0RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously = 1000,
};
NS_ENUM(NSInteger) {
ABI28_0_0RCTSourceFilesChangedCountNotBuiltByBundler = -2,
ABI28_0_0RCTSourceFilesChangedCountRebuiltFromScratch = -1,
};
@interface ABI28_0_0RCTLoadingProgress : NSObject
@property (nonatomic, copy) NSString *status;
@property (strong, nonatomic) NSNumber *done;
@property (strong, nonatomic) NSNumber *total;
@end
@interface ABI28_0_0RCTSource : NSObject
/**
* URL of the source object.
*/
@property (strong, nonatomic, readonly) NSURL *url;
/**
* JS source (or simply the binary header in the case of a RAM bundle).
*/
@property (strong, nonatomic, readonly) NSData *data;
/**
* Length of the entire JS bundle. Note that self.length != self.data.length in the case of certain bundle formats. For
* instance, when using RAM bundles:
*
* - self.data will point to the bundle header
* - self.data.length is the length of the bundle header, i.e. sizeof(facebook::ReactABI28_0_0::BundleHeader)
* - self.length is the length of the entire bundle file (header + contents)
*/
@property (nonatomic, readonly) NSUInteger length;
/**
* Returns number of files changed when building this bundle:
*
* - ABI28_0_0RCTSourceFilesChangedCountNotBuiltByBundler if the source wasn't built by the bundler (e.g. read from disk)
* - ABI28_0_0RCTSourceFilesChangedCountRebuiltFromScratch if the source was rebuilt from scratch by the bundler
* - Otherwise, the number of files changed when incrementally rebuilding the source
*/
@property (nonatomic, readonly) NSInteger filesChangedCount;
@end
typedef void (^ABI28_0_0RCTSourceLoadProgressBlock)(ABI28_0_0RCTLoadingProgress *progressData);
typedef void (^ABI28_0_0RCTSourceLoadBlock)(NSError *error, ABI28_0_0RCTSource *source);
@interface ABI28_0_0RCTJavaScriptLoader : NSObject
+ (void)loadBundleAtURL:(NSURL *)scriptURL onProgress:(ABI28_0_0RCTSourceLoadProgressBlock)onProgress onComplete:(ABI28_0_0RCTSourceLoadBlock)onComplete;
/**
* @experimental
* Attempts to synchronously load the script at the given URL. The following two conditions must be met:
* 1. It must be a file URL.
* 2. It must not point to a text/javascript file.
* If the URL does not meet those conditions, this method will return nil and supply an error with the domain
* ABI28_0_0RCTJavaScriptLoaderErrorDomain and the code ABI28_0_0RCTJavaScriptLoaderErrorCannotBeLoadedSynchronously.
*/
+ (NSData *)attemptSynchronousLoadOfBundleAtURL:(NSURL *)scriptURL
runtimeBCVersion:(int32_t)runtimeBCVersion
sourceLength:(int64_t *)sourceLength
error:(NSError **)error;
@end
| 37.182796 | 153 | 0.766339 | [
"object"
] |
191caecc163a356f94ce34a396c6dd4f601eac66 | 10,936 | c | C | channels/rdpsnd/client/opensles/opensl_io.c | kdienes/FreeRDP | 8fd926f08524bcdad8adbb5d908ebb1ad2ce6106 | [
"Apache-2.0"
] | null | null | null | channels/rdpsnd/client/opensles/opensl_io.c | kdienes/FreeRDP | 8fd926f08524bcdad8adbb5d908ebb1ad2ce6106 | [
"Apache-2.0"
] | null | null | null | channels/rdpsnd/client/opensles/opensl_io.c | kdienes/FreeRDP | 8fd926f08524bcdad8adbb5d908ebb1ad2ce6106 | [
"Apache-2.0"
] | 1 | 2022-01-02T07:24:06.000Z | 2022-01-02T07:24:06.000Z | /*
opensl_io.c:
Android OpenSL input/output module
Copyright (c) 2012, Victor Lazzarini
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include "rdpsnd_main.h"
#include "opensl_io.h"
#define CONV16BIT 32768
#define CONVMYFLT (1./32768.)
static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* context);
// creates the OpenSL ES audio engine
static SLresult openSLCreateEngine(OPENSL_STREAM* p)
{
SLresult result;
// create engine
result = slCreateEngine(&(p->engineObject), 0, NULL, 0, NULL, NULL);
DEBUG_SND("engineObject=%p", (void*) p->engineObject);
if (result != SL_RESULT_SUCCESS) goto engine_end;
// realize the engine
result = (*p->engineObject)->Realize(p->engineObject, SL_BOOLEAN_FALSE);
DEBUG_SND("Realize=%"PRIu32"", result);
if (result != SL_RESULT_SUCCESS) goto engine_end;
// get the engine interface, which is needed in order to create other objects
result = (*p->engineObject)->GetInterface(p->engineObject, SL_IID_ENGINE,
&(p->engineEngine));
DEBUG_SND("engineEngine=%p", (void*) p->engineEngine);
if (result != SL_RESULT_SUCCESS) goto engine_end;
engine_end:
return result;
}
// opens the OpenSL ES device for output
static SLresult openSLPlayOpen(OPENSL_STREAM* p)
{
SLresult result;
SLuint32 sr = p->sr;
SLuint32 channels = p->outchannels;
assert(p->engineObject);
assert(p->engineEngine);
if (channels)
{
// configure audio source
SLDataLocator_AndroidSimpleBufferQueue loc_bufq =
{
SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
p->queuesize
};
switch (sr)
{
case 8000:
sr = SL_SAMPLINGRATE_8;
break;
case 11025:
sr = SL_SAMPLINGRATE_11_025;
break;
case 16000:
sr = SL_SAMPLINGRATE_16;
break;
case 22050:
sr = SL_SAMPLINGRATE_22_05;
break;
case 24000:
sr = SL_SAMPLINGRATE_24;
break;
case 32000:
sr = SL_SAMPLINGRATE_32;
break;
case 44100:
sr = SL_SAMPLINGRATE_44_1;
break;
case 48000:
sr = SL_SAMPLINGRATE_48;
break;
case 64000:
sr = SL_SAMPLINGRATE_64;
break;
case 88200:
sr = SL_SAMPLINGRATE_88_2;
break;
case 96000:
sr = SL_SAMPLINGRATE_96;
break;
case 192000:
sr = SL_SAMPLINGRATE_192;
break;
default:
return -1;
}
const SLInterfaceID ids[] = {SL_IID_VOLUME};
const SLboolean req[] = {SL_BOOLEAN_FALSE};
result = (*p->engineEngine)->CreateOutputMix(p->engineEngine,
&(p->outputMixObject), 1, ids, req);
DEBUG_SND("engineEngine=%p", (void*) p->engineEngine);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// realize the output mix
result = (*p->outputMixObject)->Realize(p->outputMixObject, SL_BOOLEAN_FALSE);
DEBUG_SND("Realize=%"PRIu32"", result);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
int speakers;
if (channels > 1)
speakers = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
else speakers = SL_SPEAKER_FRONT_CENTER;
SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, channels, sr,
SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
speakers, SL_BYTEORDER_LITTLEENDIAN
};
SLDataSource audioSrc = {&loc_bufq, &format_pcm};
// configure audio sink
SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, p->outputMixObject};
SLDataSink audioSnk = {&loc_outmix, NULL};
// create audio player
const SLInterfaceID ids1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_VOLUME};
const SLboolean req1[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
result = (*p->engineEngine)->CreateAudioPlayer(p->engineEngine,
&(p->bqPlayerObject), &audioSrc, &audioSnk, 2, ids1, req1);
DEBUG_SND("bqPlayerObject=%p", (void*) p->bqPlayerObject);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// realize the player
result = (*p->bqPlayerObject)->Realize(p->bqPlayerObject, SL_BOOLEAN_FALSE);
DEBUG_SND("Realize=%"PRIu32"", result);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// get the play interface
result = (*p->bqPlayerObject)->GetInterface(p->bqPlayerObject, SL_IID_PLAY,
&(p->bqPlayerPlay));
DEBUG_SND("bqPlayerPlay=%p", (void*) p->bqPlayerPlay);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// get the volume interface
result = (*p->bqPlayerObject)->GetInterface(p->bqPlayerObject, SL_IID_VOLUME,
&(p->bqPlayerVolume));
DEBUG_SND("bqPlayerVolume=%p", (void*) p->bqPlayerVolume);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// get the buffer queue interface
result = (*p->bqPlayerObject)->GetInterface(p->bqPlayerObject,
SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
&(p->bqPlayerBufferQueue));
DEBUG_SND("bqPlayerBufferQueue=%p", (void*) p->bqPlayerBufferQueue);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// register callback on the buffer queue
result = (*p->bqPlayerBufferQueue)->RegisterCallback(p->bqPlayerBufferQueue,
bqPlayerCallback, p);
DEBUG_SND("bqPlayerCallback=%p", (void*) p->bqPlayerCallback);
assert(!result);
if (result != SL_RESULT_SUCCESS) goto end_openaudio;
// set the player's state to playing
result = (*p->bqPlayerPlay)->SetPlayState(p->bqPlayerPlay,
SL_PLAYSTATE_PLAYING);
DEBUG_SND("SetPlayState=%"PRIu32"", result);
assert(!result);
end_openaudio:
assert(!result);
return result;
}
return SL_RESULT_SUCCESS;
}
// close the OpenSL IO and destroy the audio engine
static void openSLDestroyEngine(OPENSL_STREAM* p)
{
// destroy buffer queue audio player object, and invalidate all associated interfaces
if (p->bqPlayerObject != NULL)
{
(*p->bqPlayerObject)->Destroy(p->bqPlayerObject);
p->bqPlayerObject = NULL;
p->bqPlayerVolume = NULL;
p->bqPlayerPlay = NULL;
p->bqPlayerBufferQueue = NULL;
p->bqPlayerEffectSend = NULL;
}
// destroy output mix object, and invalidate all associated interfaces
if (p->outputMixObject != NULL)
{
(*p->outputMixObject)->Destroy(p->outputMixObject);
p->outputMixObject = NULL;
}
// destroy engine object, and invalidate all associated interfaces
if (p->engineObject != NULL)
{
(*p->engineObject)->Destroy(p->engineObject);
p->engineObject = NULL;
p->engineEngine = NULL;
}
}
// open the android audio device for and/or output
OPENSL_STREAM* android_OpenAudioDevice(int sr, int outchannels,
int bufferframes)
{
OPENSL_STREAM* p;
p = (OPENSL_STREAM*) calloc(sizeof(OPENSL_STREAM), 1);
if (!p)
return NULL;
p->queuesize = bufferframes;
p->outchannels = outchannels;
p->sr = sr;
if (openSLCreateEngine(p) != SL_RESULT_SUCCESS)
{
android_CloseAudioDevice(p);
return NULL;
}
if (openSLPlayOpen(p) != SL_RESULT_SUCCESS)
{
android_CloseAudioDevice(p);
return NULL;
}
p->queue = Queue_New(TRUE, -1, -1);
if (!p->queue)
{
android_CloseAudioDevice(p);
return NULL;
}
return p;
}
// close the android audio device
void android_CloseAudioDevice(OPENSL_STREAM* p)
{
if (p == NULL)
return;
openSLDestroyEngine(p);
if (p->queue)
Queue_Free(p->queue);
free(p);
}
// this callback handler is called every time a buffer finishes playing
static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* context)
{
OPENSL_STREAM* p = (OPENSL_STREAM*) context;
assert(p);
assert(p->queue);
void* data = Queue_Dequeue(p->queue);
free(data);
}
// puts a buffer of size samples to the device
int android_AudioOut(OPENSL_STREAM* p, const short* buffer, int size)
{
assert(p);
assert(buffer);
assert(size > 0);
/* Assure, that the queue is not full. */
if (p->queuesize <= Queue_Count(p->queue)
&& WaitForSingleObject(p->queue->event, INFINITE) == WAIT_FAILED)
{
DEBUG_SND("WaitForSingleObject failed!");
return -1;
}
void* data = calloc(size, sizeof(short));
if (!data)
{
DEBUG_SND("unable to allocate a buffer");
return -1;
}
memcpy(data, buffer, size * sizeof(short));
Queue_Enqueue(p->queue, data);
(*p->bqPlayerBufferQueue)->Enqueue(p->bqPlayerBufferQueue,
data, sizeof(short) * size);
return size;
}
int android_GetOutputMute(OPENSL_STREAM* p)
{
SLboolean mute;
assert(p);
assert(p->bqPlayerVolume);
SLresult rc = (*p->bqPlayerVolume)->GetMute(p->bqPlayerVolume, &mute);
if (SL_RESULT_SUCCESS != rc)
return SL_BOOLEAN_FALSE;
return mute;
}
BOOL android_SetOutputMute(OPENSL_STREAM* p, BOOL _mute)
{
SLboolean mute = _mute;
assert(p);
assert(p->bqPlayerVolume);
SLresult rc = (*p->bqPlayerVolume)->SetMute(p->bqPlayerVolume, mute);
if (SL_RESULT_SUCCESS != rc)
return FALSE;
return TRUE;
}
int android_GetOutputVolume(OPENSL_STREAM* p)
{
SLmillibel level;
assert(p);
assert(p->bqPlayerVolume);
SLresult rc = (*p->bqPlayerVolume)->GetVolumeLevel(p->bqPlayerVolume, &level);
if (SL_RESULT_SUCCESS != rc)
return 0;
return level;
}
int android_GetOutputVolumeMax(OPENSL_STREAM* p)
{
SLmillibel level;
assert(p);
assert(p->bqPlayerVolume);
SLresult rc = (*p->bqPlayerVolume)->GetMaxVolumeLevel(p->bqPlayerVolume,
&level);
if (SL_RESULT_SUCCESS != rc)
return 0;
return level;
}
BOOL android_SetOutputVolume(OPENSL_STREAM* p, int level)
{
SLresult rc = (*p->bqPlayerVolume)->SetVolumeLevel(p->bqPlayerVolume, level);
if (SL_RESULT_SUCCESS != rc)
return FALSE;
return TRUE;
}
| 26.22542 | 90 | 0.708486 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.