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
8043f67fc002664ec3976898b849c30fcd3cdec0
5,097
h
C
aws-cpp-sdk-wafv2/include/aws/wafv2/model/RuleAction.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-wafv2/include/aws/wafv2/model/RuleAction.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-wafv2/include/aws/wafv2/model/RuleAction.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/wafv2/WAFV2_EXPORTS.h> #include <aws/wafv2/model/BlockAction.h> #include <aws/wafv2/model/AllowAction.h> #include <aws/wafv2/model/CountAction.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace WAFV2 { namespace Model { /** * <note> <p>This is the latest version of <b>AWS WAF</b>, named AWS WAFV2, * released in November, 2019. For information, including how to migrate your AWS * WAF resources from the prior release, see the <a * href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS * WAF Developer Guide</a>. </p> </note> <p>The action that AWS WAF should take on * a web request when it matches a rule's statement. Settings at the web ACL level * can override the rule action setting. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/wafv2-2019-07-29/RuleAction">AWS * API Reference</a></p> */ class AWS_WAFV2_API RuleAction { public: RuleAction(); RuleAction(Aws::Utils::Json::JsonView jsonValue); RuleAction& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Instructs AWS WAF to block the web request.</p> */ inline const BlockAction& GetBlock() const{ return m_block; } /** * <p>Instructs AWS WAF to block the web request.</p> */ inline bool BlockHasBeenSet() const { return m_blockHasBeenSet; } /** * <p>Instructs AWS WAF to block the web request.</p> */ inline void SetBlock(const BlockAction& value) { m_blockHasBeenSet = true; m_block = value; } /** * <p>Instructs AWS WAF to block the web request.</p> */ inline void SetBlock(BlockAction&& value) { m_blockHasBeenSet = true; m_block = std::move(value); } /** * <p>Instructs AWS WAF to block the web request.</p> */ inline RuleAction& WithBlock(const BlockAction& value) { SetBlock(value); return *this;} /** * <p>Instructs AWS WAF to block the web request.</p> */ inline RuleAction& WithBlock(BlockAction&& value) { SetBlock(std::move(value)); return *this;} /** * <p>Instructs AWS WAF to allow the web request.</p> */ inline const AllowAction& GetAllow() const{ return m_allow; } /** * <p>Instructs AWS WAF to allow the web request.</p> */ inline bool AllowHasBeenSet() const { return m_allowHasBeenSet; } /** * <p>Instructs AWS WAF to allow the web request.</p> */ inline void SetAllow(const AllowAction& value) { m_allowHasBeenSet = true; m_allow = value; } /** * <p>Instructs AWS WAF to allow the web request.</p> */ inline void SetAllow(AllowAction&& value) { m_allowHasBeenSet = true; m_allow = std::move(value); } /** * <p>Instructs AWS WAF to allow the web request.</p> */ inline RuleAction& WithAllow(const AllowAction& value) { SetAllow(value); return *this;} /** * <p>Instructs AWS WAF to allow the web request.</p> */ inline RuleAction& WithAllow(AllowAction&& value) { SetAllow(std::move(value)); return *this;} /** * <p>Instructs AWS WAF to count the web request and allow it.</p> */ inline const CountAction& GetCount() const{ return m_count; } /** * <p>Instructs AWS WAF to count the web request and allow it.</p> */ inline bool CountHasBeenSet() const { return m_countHasBeenSet; } /** * <p>Instructs AWS WAF to count the web request and allow it.</p> */ inline void SetCount(const CountAction& value) { m_countHasBeenSet = true; m_count = value; } /** * <p>Instructs AWS WAF to count the web request and allow it.</p> */ inline void SetCount(CountAction&& value) { m_countHasBeenSet = true; m_count = std::move(value); } /** * <p>Instructs AWS WAF to count the web request and allow it.</p> */ inline RuleAction& WithCount(const CountAction& value) { SetCount(value); return *this;} /** * <p>Instructs AWS WAF to count the web request and allow it.</p> */ inline RuleAction& WithCount(CountAction&& value) { SetCount(std::move(value)); return *this;} private: BlockAction m_block; bool m_blockHasBeenSet; AllowAction m_allow; bool m_allowHasBeenSet; CountAction m_count; bool m_countHasBeenSet; }; } // namespace Model } // namespace WAFV2 } // namespace Aws
30.890909
103
0.660585
[ "model" ]
8046c57ae8f75c0ceafea3249d68a8d73f536753
7,491
h
C
lib/sergut/marshaller/RequestClient.h
belgoking/sergut
1c924e23f09823557b54a661ec50bc2c9829e41d
[ "MIT" ]
5
2018-01-20T10:28:39.000Z
2020-04-28T22:13:24.000Z
lib/sergut/marshaller/RequestClient.h
belgoking/sergut
1c924e23f09823557b54a661ec50bc2c9829e41d
[ "MIT" ]
null
null
null
lib/sergut/marshaller/RequestClient.h
belgoking/sergut
1c924e23f09823557b54a661ec50bc2c9829e41d
[ "MIT" ]
null
null
null
/* Copyright (c) 2016 Tobias Koelsch * * 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. */ #pragma once #include "sergut/marshaller/InvalidCodePathException.h" #include "sergut/marshaller/RemoteCallingException.h" #include "sergut/marshaller/UnknownFunctionException.h" #include "sergut/marshaller/detail/FunctionSignatureExtractor.h" #include "sergut/misc/ConstStringRef.h" #include "sergut/misc/ReadHelper.h" #include "sergut/UrlSerializeToVector.h" #include "sergut/XmlDeserializer.h" #include "sergut/XmlSerializer.h" #include <type_traits> namespace sergut { namespace marshaller { namespace { template<typename T> std::string toString(const T& d) { (void)d; // this implementation exists merely as some code paths // that should never be executed require it for template // instantication throw sergut::marshaller::InvalidCodePathException("Trying to read non-simple parameter from string"); } } class RequestClient { public: typedef sergut::marshaller::detail::FunctionSignatureExtractor::Parameter Parameter; typedef sergut::marshaller::detail::FunctionSignatureExtractor::Input Input; typedef sergut::marshaller::detail::FunctionSignatureExtractor::NestedInput NestedInput; public: struct Request { /// The name of the remote function std::string _functionName; /// The serialized parameters std::vector<std::pair<std::string, std::string>> _params; /// The content type of the input std::string _inputContentType; /// The request body std::string _input; /// The supported result types std::string _acceptContentType; }; class RequestHandler { public: virtual ~RequestHandler(); /** * @brief handleRequest Executes the remote function call with the serialized parameters * @return A pair with the content type of the result and the result bytes * * The implementer of a remote request backend has to implement this function and map * the different input types to the corresponding coding of the implemented calling * method and the result has to be mapped to the return type. */ virtual std::pair<std::string,std::vector<char>> handleRequest(const Request& request) const = 0; }; RequestClient(const RequestHandler& requestHandler) : _requestHandler(requestHandler) { } virtual ~RequestClient() { } template<typename Cls, typename RetT, typename ...FunArgs, typename ...Converters> void add(const std::string& funName, const Cls* cls, const std::string& returnWrapperName, RetT(Cls::*fun)(FunArgs ...funArgs) const, const Converters& ...converters) { (void)cls; _functionSignatures.add(funName, cls, returnWrapperName, fun, converters...); } template<std::size_t ParamPos> void fillRequest(Request& request, UrlSerializeToVector& urlSerializer, const detail::FunctionSignatureExtractor::FunctionSignature& signature) const { (void)request; (void)urlSerializer; (void)signature; } template<std::size_t ParamPos, typename FunArg, typename ...FunArgs> void fillRequest(Request& request, UrlSerializeToVector& urlSerializer, const detail::FunctionSignatureExtractor::FunctionSignature& signature, FunArg&& funArg, FunArgs&& ...funArgs) const { // first fill the current parameter (we take advantage that the last parameter // is handled just the same as all other parameters if(signature._inputData._parameterPosition == ParamPos) { request._inputContentType = "application/xml"; sergut::XmlSerializer ser; if(!signature._inputData._innerTagName.empty()) { ser.serializeNestedData(signature._inputData._outerTagName.c_str(), signature._inputData._innerTagName.c_str(), signature._inputData._xmlValueType, funArg); //TODO: check why std::forward does not work } else { ser.serializeData(signature._inputData._outerTagName.c_str(), funArg); //TODO: check why std::forward does not work } request._input = ser.str(); } else { urlSerializer.serializeData(signature._parameters[ParamPos]._name, funArg); //TODO: check why std::forward does not work } // then we handle the remaining parameters fillRequest<ParamPos+1>(request, urlSerializer, signature, funArgs...); //TODO: check why std::forward does not work } template<typename RetT, typename ...FunArgs> RetT call(const std::string& funName, FunArgs&& ...funArgs) const { const auto i = _functionSignatures._mappings.find( detail::FunctionSignatureExtractor::FunctionNameNParameterCount{funName, sizeof...(FunArgs)}); if(i == _functionSignatures._mappings.end()) { std::cout << funName << " gibt es nicht" << std::endl; throw sergut::marshaller::UnknownFunctionException(funName); } const detail::FunctionSignatureExtractor::FunctionSignature& signature = i->second; std::cout << "rufe " << funName << " auf" << std::endl; Request request; request._functionName = funName; request._acceptContentType = "application/xml"; // I know the following reserves one element too much in case we have input data but don't care request._params.reserve(signature._parameters.size()); if(sizeof...(funArgs) > 0) { UrlSerializeToVector urlSerializer; fillRequest<0>(request, urlSerializer, signature, funArgs...); //TODO: check why std::forward does not work request._params = std::move(urlSerializer.takeParams()); } std::pair<std::string, std::vector<char>> result = _requestHandler.handleRequest(request); if(!result.second.empty() && result.first != "application/xml") { throw RemoteCallingException("Unsupported return format: '" + result.first + "'"); } XmlDeserializer deser(std::move(result.second)); if(signature._returnData._innerTagName.empty()) { return deser.deserializeData<RetT>(signature._returnData._outerTagName.c_str()); } else { return deser.deserializeNestedData<RetT>( signature._returnData._outerTagName.c_str(), signature._returnData._innerTagName.c_str(), signature._returnData._xmlValueType); } } private: const RequestHandler& _requestHandler; detail::FunctionSignatureExtractor _functionSignatures; }; } }
41.159341
126
0.708984
[ "vector" ]
8048964606ffcb4d511f1c1f9850393367237648
13,309
c
C
src/data.c
simpzan/libdispatch
919fa52453a3a42b674a135147a1905fc69beead
[ "Apache-2.0" ]
null
null
null
src/data.c
simpzan/libdispatch
919fa52453a3a42b674a135147a1905fc69beead
[ "Apache-2.0" ]
null
null
null
src/data.c
simpzan/libdispatch
919fa52453a3a42b674a135147a1905fc69beead
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2009-2011 Apple Inc. All rights reserved. * * @APPLE_APACHE_LICENSE_HEADER_START@ * * 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. * * @APPLE_APACHE_LICENSE_HEADER_END@ */ #include "internal.h" // Dispatch data objects are dispatch objects with standard retain/release // memory management. A dispatch data object either points to a number of other // dispatch data objects or is a leaf data object. A leaf data object contains // a pointer to represented memory. A composite data object specifies the total // size of data it represents and list of constituent records. // // A leaf data object has a single entry in records[], the object size is the // same as records[0].length and records[0].from is always 0. In other words, a // leaf data object always points to a full represented buffer, so a composite // dispatch data object is needed to represent a subrange of a memory region. #define _dispatch_data_retain(x) dispatch_retain(x) #define _dispatch_data_release(x) dispatch_release(x) #if DISPATCH_DATA_MOVABLE #if DISPATCH_USE_RESOLVERS && !defined(DISPATCH_RESOLVED_VARIANT) #error Resolved variant required for movable #endif static const dispatch_block_t _dispatch_data_destructor_unlock = ^{ DISPATCH_CRASH("unlock destructor called"); }; #define DISPATCH_DATA_DESTRUCTOR_UNLOCK (_dispatch_data_destructor_unlock) #endif const dispatch_block_t _dispatch_data_destructor_free = ^{ DISPATCH_CRASH("free destructor called"); }; const dispatch_block_t _dispatch_data_destructor_none = ^{ DISPATCH_CRASH("none destructor called"); }; const dispatch_block_t _dispatch_data_destructor_vm_deallocate = ^{ DISPATCH_CRASH("vmdeallocate destructor called"); }; struct dispatch_data_s _dispatch_data_empty = { .do_vtable = DISPATCH_VTABLE(data), .do_ref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT, .do_xref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT, .do_next = DISPATCH_OBJECT_LISTLESS, }; static dispatch_data_t _dispatch_data_init(size_t n) { dispatch_data_t data = _dispatch_alloc(DISPATCH_VTABLE(data), sizeof(struct dispatch_data_s) + n * sizeof(range_record)); data->num_records = n; data->do_targetq = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); data->do_next = DISPATCH_OBJECT_LISTLESS; return data; } static void _dispatch_data_destroy_buffer(const void* buffer, size_t size, dispatch_queue_t queue, dispatch_block_t destructor) { if (destructor == DISPATCH_DATA_DESTRUCTOR_FREE) { free((void*)buffer); } else if (destructor == DISPATCH_DATA_DESTRUCTOR_NONE) { // do nothing } else if (destructor == DISPATCH_DATA_DESTRUCTOR_VM_DEALLOCATE) { vm_deallocate(mach_task_self(), (vm_address_t)buffer, size); } else { if (!queue) { queue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); } dispatch_async_f(queue, destructor, _dispatch_call_block_and_release); } } dispatch_data_t dispatch_data_create(const void* buffer, size_t size, dispatch_queue_t queue, dispatch_block_t destructor) { dispatch_data_t data; if (!buffer || !size) { // Empty data requested so return the singleton empty object. Call // destructor immediately in this case to ensure any unused associated // storage is released. if (destructor) { _dispatch_data_destroy_buffer(buffer, size, queue, _dispatch_Block_copy(destructor)); } return dispatch_data_empty; } data = _dispatch_data_init(1); // Leaf objects always point to the entirety of the memory region data->leaf = true; data->size = size; data->records[0].from = 0; data->records[0].length = size; if (destructor == DISPATCH_DATA_DESTRUCTOR_DEFAULT) { // The default destructor was provided, indicating the data should be // copied. void *data_buf = malloc(size); if (slowpath(!data_buf)) { free(data); return NULL; } buffer = memcpy(data_buf, buffer, size); data->destructor = DISPATCH_DATA_DESTRUCTOR_FREE; } else { data->destructor = _dispatch_Block_copy(destructor); #if DISPATCH_DATA_MOVABLE // A non-default destructor was provided, indicating the system does not // own the buffer. Mark the object as locked since the application has // direct access to the buffer and it cannot be reallocated/moved. data->locked = 1; #endif } data->records[0].data_object = (void*)buffer; if (queue) { _dispatch_retain(queue); data->do_targetq = queue; } return data; } void _dispatch_data_dispose(dispatch_data_t dd) { dispatch_block_t destructor = dd->destructor; if (destructor == NULL) { size_t i; for (i = 0; i < dd->num_records; ++i) { _dispatch_data_release(dd->records[i].data_object); } #if DISPATCH_DATA_MOVABLE } else if (destructor == DISPATCH_DATA_DESTRUCTOR_UNLOCK) { dispatch_data_t data = (dispatch_data_t)dd->records[0].data_object; (void)dispatch_atomic_dec2o(data, locked); _dispatch_data_release(data); #endif } else { _dispatch_data_destroy_buffer(dd->records[0].data_object, dd->records[0].length, dd->do_targetq, destructor); } } size_t _dispatch_data_debug(dispatch_data_t dd, char* buf, size_t bufsiz) { size_t offset = 0; if (dd->leaf) { offset += snprintf(&buf[offset], bufsiz - offset, "leaf: %d, size: %zd, data: %p", dd->leaf, dd->size, dd->records[0].data_object); } else { offset += snprintf(&buf[offset], bufsiz - offset, "leaf: %d, size: %zd, num_records: %zd", dd->leaf, dd->size, dd->num_records); size_t i; for (i = 0; i < dd->num_records; ++i) { range_record r = dd->records[i]; offset += snprintf(&buf[offset], bufsiz - offset, "records[%zd] from: %zd, length %zd, data_object: %p", i, r.from, r.length, r.data_object); } } return offset; } size_t dispatch_data_get_size(dispatch_data_t dd) { return dd->size; } dispatch_data_t dispatch_data_create_concat(dispatch_data_t dd1, dispatch_data_t dd2) { dispatch_data_t data; if (!dd1->size) { _dispatch_data_retain(dd2); return dd2; } if (!dd2->size) { _dispatch_data_retain(dd1); return dd1; } data = _dispatch_data_init(dd1->num_records + dd2->num_records); data->size = dd1->size + dd2->size; // Copy the constituent records into the newly created data object memcpy(data->records, dd1->records, dd1->num_records * sizeof(range_record)); memcpy(data->records + dd1->num_records, dd2->records, dd2->num_records * sizeof(range_record)); // Reference leaf objects as sub-objects if (dd1->leaf) { data->records[0].data_object = dd1; } if (dd2->leaf) { data->records[dd1->num_records].data_object = dd2; } size_t i; for (i = 0; i < data->num_records; ++i) { _dispatch_data_retain(data->records[i].data_object); } return data; } dispatch_data_t dispatch_data_create_subrange(dispatch_data_t dd, size_t offset, size_t length) { dispatch_data_t data; if (offset >= dd->size || !length) { return dispatch_data_empty; } else if ((offset + length) > dd->size) { length = dd->size - offset; } else if (length == dd->size) { _dispatch_data_retain(dd); return dd; } if (dd->leaf) { data = _dispatch_data_init(1); data->size = length; data->records[0].from = offset; data->records[0].length = length; data->records[0].data_object = dd; _dispatch_data_retain(dd); return data; } // Subrange of a composite dispatch data object: find the record containing // the specified offset data = dispatch_data_empty; size_t i = 0, bytes_left = length; while (i < dd->num_records && offset >= dd->records[i].length) { offset -= dd->records[i++].length; } while (i < dd->num_records) { size_t record_len = dd->records[i].length - offset; if (record_len > bytes_left) { record_len = bytes_left; } dispatch_data_t subrange = dispatch_data_create_subrange( dd->records[i].data_object, dd->records[i].from + offset, record_len); dispatch_data_t concat = dispatch_data_create_concat(data, subrange); _dispatch_data_release(data); _dispatch_data_release(subrange); data = concat; bytes_left -= record_len; if (!bytes_left) { return data; } offset = 0; i++; } // Crashing here indicates memory corruption of passed in data object DISPATCH_CRASH("dispatch_data_create_subrange out of bounds"); return NULL; } // When mapping a leaf object or a subrange of a leaf object, return a direct // pointer to the represented buffer. For all other data objects, copy the // represented buffers into a contiguous area. In the future it might // be possible to relocate the buffers instead (if not marked as locked). dispatch_data_t dispatch_data_create_map(dispatch_data_t dd, const void **buffer_ptr, size_t *size_ptr) { dispatch_data_t data = dd; void *buffer = NULL; size_t size = dd->size, offset = 0; if (!size) { data = dispatch_data_empty; goto out; } if (!dd->leaf && dd->num_records == 1 && ((dispatch_data_t)dd->records[0].data_object)->leaf) { offset = dd->records[0].from; dd = (dispatch_data_t)(dd->records[0].data_object); } if (dd->leaf) { #if DISPATCH_DATA_MOVABLE data = _dispatch_data_init(1); // Make sure the underlying leaf object does not move the backing buffer (void)dispatch_atomic_inc2o(dd, locked); data->size = size; data->destructor = DISPATCH_DATA_DESTRUCTOR_UNLOCK; data->records[0].data_object = dd; data->records[0].from = offset; data->records[0].length = size; _dispatch_data_retain(dd); #else _dispatch_data_retain(data); #endif buffer = dd->records[0].data_object + offset; goto out; } // Composite data object, copy the represented buffers buffer = malloc(size); if (!buffer) { data = NULL; size = 0; goto out; } dispatch_data_apply(dd, ^(dispatch_data_t region DISPATCH_UNUSED, size_t off, const void* buf, size_t len) { memcpy(buffer + off, buf, len); return (bool)true; }); data = dispatch_data_create(buffer, size, NULL, DISPATCH_DATA_DESTRUCTOR_FREE); out: if (buffer_ptr) { *buffer_ptr = buffer; } if (size_ptr) { *size_ptr = size; } return data; } static bool _dispatch_data_apply(dispatch_data_t dd, size_t offset, size_t from, size_t size, dispatch_data_applier_t applier) { bool result = true; dispatch_data_t data = dd; const void *buffer; dispatch_assert(dd->size); #if DISPATCH_DATA_MOVABLE if (dd->leaf) { data = _dispatch_data_init(1); // Make sure the underlying leaf object does not move the backing buffer (void)dispatch_atomic_inc2o(dd, locked); data->size = size; data->destructor = DISPATCH_DATA_DESTRUCTOR_UNLOCK; data->records[0].data_object = dd; data->records[0].from = from; data->records[0].length = size; _dispatch_data_retain(dd); buffer = dd->records[0].data_object + from; result = applier(data, offset, buffer, size); _dispatch_data_release(data); return result; } #else if (!dd->leaf && dd->num_records == 1 && ((dispatch_data_t)dd->records[0].data_object)->leaf) { from = dd->records[0].from; dd = (dispatch_data_t)(dd->records[0].data_object); } if (dd->leaf) { buffer = dd->records[0].data_object + from; return applier(data, offset, buffer, size); } #endif size_t i; for (i = 0; i < dd->num_records && result; ++i) { result = _dispatch_data_apply(dd->records[i].data_object, offset, dd->records[i].from, dd->records[i].length, applier); offset += dd->records[i].length; } return result; } bool dispatch_data_apply(dispatch_data_t dd, dispatch_data_applier_t applier) { if (!dd->size) { return true; } return _dispatch_data_apply(dd, 0, 0, dd->size, applier); } // Returs either a leaf object or an object composed of a single leaf object dispatch_data_t dispatch_data_copy_region(dispatch_data_t dd, size_t location, size_t *offset_ptr) { if (location >= dd->size) { *offset_ptr = 0; return dispatch_data_empty; } dispatch_data_t data; size_t size = dd->size, offset = 0, from = 0; while (true) { if (dd->leaf) { _dispatch_data_retain(dd); *offset_ptr = offset; if (size == dd->size) { return dd; } else { // Create a new object for the requested subrange of the leaf data = _dispatch_data_init(1); data->size = size; data->records[0].from = from; data->records[0].length = size; data->records[0].data_object = dd; return data; } } else { // Find record at the specified location size_t i, pos; for (i = 0; i < dd->num_records; ++i) { pos = offset + dd->records[i].length; if (location < pos) { size = dd->records[i].length; from = dd->records[i].from; data = (dispatch_data_t)(dd->records[i].data_object); if (dd->num_records == 1 && data->leaf) { // Return objects composed of a single leaf node *offset_ptr = offset; _dispatch_data_retain(dd); return dd; } else { // Drill down into other objects dd = data; break; } } else { offset = pos; } } } } }
29.707589
79
0.714329
[ "object" ]
804d3880922cd1a8931e0180432af8b688f63203
6,831
h
C
google/cloud/spanner/results.h
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
google/cloud/spanner/results.h
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
google/cloud/spanner/results.h
antfitch/google-cloud-cpp-spanner
05a2e3ad3ee0ac96164013ce4d9cfce251059569
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // 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 GOOGLE_CLOUD_CPP_SPANNER_GOOGLE_CLOUD_SPANNER_RESULTS_H_ #define GOOGLE_CLOUD_CPP_SPANNER_GOOGLE_CLOUD_SPANNER_RESULTS_H_ #include "google/cloud/spanner/row.h" #include "google/cloud/spanner/timestamp.h" #include "google/cloud/optional.h" #include <google/spanner/v1/spanner.pb.h> #include <memory> #include <string> #include <unordered_map> namespace google { namespace cloud { namespace spanner { inline namespace SPANNER_CLIENT_NS { /** * Contains a hierarchical representation of the operations the database server * performs in order to execute a particular SQL statement. * [Query Plan * proto](https://github.com/googleapis/googleapis/blob/master/google/spanner/v1/query_plan.proto) */ using ExecutionPlan = ::google::spanner::v1::QueryPlan; namespace internal { class ResultSourceInterface { public: virtual ~ResultSourceInterface() = default; // Returns OK Status with an empty Row to indicate end-of-stream. virtual StatusOr<Row> NextRow() = 0; virtual optional<google::spanner::v1::ResultSetMetadata> Metadata() = 0; virtual optional<google::spanner::v1::ResultSetStats> Stats() const = 0; }; } // namespace internal /** * Represents the stream of `Rows` returned from `spanner::Client::Read()` or * `spanner::Client::ExecuteQuery()`. * * A `RowStream` object is a range defined by the [Input * Iterators][input-iterator] returned from its `begin()` and `end()` members. * Callers may directly iterate a `RowStream` instance, which will return a * sequence of `StatusOr<Row>` objects. * * For convenience, callers may wrap a `RowStream` instance in a * `StreamOf<std::tuple<...>>` object, which will automatically parse each * `Row` into a `std::tuple` with the specified types. * * [input-iterator]: https://en.cppreference.com/w/cpp/named_req/InputIterator */ class RowStream { public: RowStream() = default; explicit RowStream(std::unique_ptr<internal::ResultSourceInterface> source) : source_(std::move(source)) {} // This class is movable but not copyable. RowStream(RowStream&&) = default; RowStream& operator=(RowStream&&) = default; /// Returns a `RowStreamIterator` defining the beginning of this range. RowStreamIterator begin() { return RowStreamIterator([this]() mutable { return source_->NextRow(); }); } /// Returns a `RowStreamIterator` defining the end of this range. RowStreamIterator end() { return {}; } /** * Retrieves the timestamp at which the read occurred. * * @note Only available if a read-only transaction was used. */ optional<Timestamp> ReadTimestamp() const; private: std::unique_ptr<internal::ResultSourceInterface> source_; }; /** * Represents the result of a data modifying operation using * `spanner::Client::ExecuteDml()`. * * This class encapsulates the result of a Cloud Spanner DML operation, i.e., * `INSERT`, `UPDATE`, or `DELETE`. * * @note `ExecuteDmlResult` returns the number of rows modified, query plan * (if requested), and execution statistics (if requested). */ class DmlResult { public: DmlResult() = default; explicit DmlResult(std::unique_ptr<internal::ResultSourceInterface> source) : source_(std::move(source)) {} // This class is movable but not copyable. DmlResult(DmlResult&&) = default; DmlResult& operator=(DmlResult&&) = default; /** * Returns the number of rows modified by the DML statement. * * @note Partitioned DML only provides a lower bound of the rows modified, all * other DML statements provide an exact count. */ std::int64_t RowsModified() const; private: std::unique_ptr<internal::ResultSourceInterface> source_; }; class ProfileQueryResult { public: ProfileQueryResult() = default; explicit ProfileQueryResult( std::unique_ptr<internal::ResultSourceInterface> source) : source_(std::move(source)) {} // This class is movable but not copyable. ProfileQueryResult(ProfileQueryResult&&) = default; ProfileQueryResult& operator=(ProfileQueryResult&&) = default; /// Returns a `RowStreamIterator` defining the beginning of this result set. RowStreamIterator begin() { return RowStreamIterator([this]() mutable { return source_->NextRow(); }); } /// Returns a `RowStreamIterator` defining the end of this result set. RowStreamIterator end() { return {}; } /** * Retrieves the timestamp at which the read occurred. * * @note Only available if a read-only transaction was used. */ optional<Timestamp> ReadTimestamp() const; /** * Returns a collection of key value pair statistics for the SQL statement * execution. * * @note Only available when the statement is executed and all results have * been read. */ optional<std::unordered_map<std::string, std::string>> ExecutionStats() const; /** * Returns the plan of execution for the SQL statement. */ optional<spanner::ExecutionPlan> ExecutionPlan() const; private: std::unique_ptr<internal::ResultSourceInterface> source_; }; class ProfileDmlResult { public: ProfileDmlResult() = default; explicit ProfileDmlResult( std::unique_ptr<internal::ResultSourceInterface> source) : source_(std::move(source)) {} // This class is movable but not copyable. ProfileDmlResult(ProfileDmlResult&&) = default; ProfileDmlResult& operator=(ProfileDmlResult&&) = default; /** * Returns the number of rows modified by the DML statement. * * @note Partitioned DML only provides a lower bound of the rows modified, all * other DML statements provide an exact count. */ std::int64_t RowsModified() const; /** * Returns a collection of key value pair statistics for the SQL statement * execution. * * @note Only available when the SQL statement is executed. */ optional<std::unordered_map<std::string, std::string>> ExecutionStats() const; /** * Returns the plan of execution for the SQL statement. */ optional<spanner::ExecutionPlan> ExecutionPlan() const; private: std::unique_ptr<internal::ResultSourceInterface> source_; }; } // namespace SPANNER_CLIENT_NS } // namespace spanner } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_SPANNER_GOOGLE_CLOUD_SPANNER_RESULTS_H_
32.374408
98
0.722881
[ "object" ]
804d751ddddf7f8ca1b76a3039c291235be854ff
26,272
c
C
riscv_machine.c
carlosbaraza/riscvemu
d03862e4946efcbb3834d53a0042ad682954767d
[ "MIT" ]
2
2018-06-11T22:58:47.000Z
2018-06-12T01:53:37.000Z
riscv_machine.c
carlosbaraza/riscvemu
d03862e4946efcbb3834d53a0042ad682954767d
[ "MIT" ]
null
null
null
riscv_machine.c
carlosbaraza/riscvemu
d03862e4946efcbb3834d53a0042ad682954767d
[ "MIT" ]
1
2021-12-08T22:41:01.000Z
2021-12-08T22:41:01.000Z
/* * RISCV machine * * Copyright (c) 2016-2017 Fabrice Bellard * * 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. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <inttypes.h> #include <assert.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <time.h> #include "cutils.h" #include "iomem.h" #include "riscv_cpu.h" #include "virtio.h" #include "machine.h" /* RISCV machine */ typedef struct RISCVMachine { VirtMachine common; PhysMemoryMap *mem_map; RISCVCPUState *cpu_state; uint64_t ram_size; /* RTC */ BOOL rtc_real_time; uint64_t rtc_start_time; uint64_t timecmp; /* PLIC */ uint32_t plic_pending_irq, plic_served_irq; IRQSignal plic_irq[32]; /* IRQ 0 is not used */ /* HTIF */ uint64_t htif_tohost, htif_fromhost; VIRTIODevice *keyboard_dev; VIRTIODevice *mouse_dev; int virtio_count; } RISCVMachine; #define LOW_RAM_SIZE 0x00010000 /* 64KB */ #define RAM_BASE_ADDR 0x80000000 #define CLINT_BASE_ADDR 0x02000000 #define CLINT_SIZE 0x000c0000 #define HTIF_BASE_ADDR 0x40008000 #define IDE_BASE_ADDR 0x40009000 #define VIRTIO_BASE_ADDR 0x40010000 #define VIRTIO_SIZE 0x1000 #define VIRTIO_IRQ 1 #define PLIC_BASE_ADDR 0x40100000 #define PLIC_SIZE 0x00400000 #define FRAMEBUFFER_BASE_ADDR 0x41000000 #define RTC_FREQ 10000000 #define RTC_FREQ_DIV 16 /* arbitrary, relative to CPU freq to have a 10 MHz frequency */ static uint64_t rtc_get_real_time(RISCVMachine *s) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * RTC_FREQ + (ts.tv_nsec / (1000000000 / RTC_FREQ)); } static uint64_t rtc_get_time(RISCVMachine *m) { uint64_t val; if (m->rtc_real_time) { val = rtc_get_real_time(m) - m->rtc_start_time; } else { val = riscv_cpu_get_cycles(m->cpu_state) / RTC_FREQ_DIV; } // printf("rtc_time=%" PRId64 "\n", val); return val; } static uint32_t htif_read(void *opaque, uint32_t offset, int size_log2) { RISCVMachine *s = opaque; uint32_t val; assert(size_log2 == 2); switch(offset) { case 0: val = s->htif_tohost; break; case 4: val = s->htif_tohost >> 32; break; case 8: val = s->htif_fromhost; break; case 12: val = s->htif_fromhost >> 32; break; default: val = 0; break; } return val; } static void htif_handle_cmd(RISCVMachine *s) { uint32_t device, cmd; device = s->htif_tohost >> 56; cmd = (s->htif_tohost >> 48) & 0xff; if (s->htif_tohost == 1) { /* shuthost */ printf("\nPower off.\n"); exit(0); } else if (device == 1 && cmd == 1) { uint8_t buf[1]; buf[0] = s->htif_tohost & 0xff; s->common.console->write_data(s->common.console->opaque, buf, 1); s->htif_tohost = 0; s->htif_fromhost = ((uint64_t)device << 56) | ((uint64_t)cmd << 48); } else if (device == 1 && cmd == 0) { /* request keyboard interrupt */ s->htif_tohost = 0; } else { printf("HTIF: unsupported tohost=0x%016" PRIx64 "\n", s->htif_tohost); } } static void htif_write(void *opaque, uint32_t offset, uint32_t val, int size_log2) { RISCVMachine *s = opaque; assert(size_log2 == 2); switch(offset) { case 0: s->htif_tohost = (s->htif_tohost & ~0xffffffff) | val; break; case 4: s->htif_tohost = (s->htif_tohost & 0xffffffff) | ((uint64_t)val << 32); htif_handle_cmd(s); break; case 8: s->htif_fromhost = (s->htif_fromhost & ~0xffffffff) | val; break; case 12: s->htif_fromhost = (s->htif_fromhost & 0xffffffff) | (uint64_t)val << 32; break; default: break; } } #if 0 static void htif_poll(RISCVMachine *s) { uint8_t buf[1]; int ret; if (s->htif_fromhost == 0) { ret = s->console->read_data(s->console->opaque, buf, 1); if (ret == 1) { s->htif_fromhost = ((uint64_t)1 << 56) | ((uint64_t)0 << 48) | buf[0]; } } } #endif static uint32_t clint_read(void *opaque, uint32_t offset, int size_log2) { RISCVMachine *m = opaque; uint32_t val; assert(size_log2 == 2); switch(offset) { case 0xbff8: val = rtc_get_time(m); break; case 0xbffc: val = rtc_get_time(m) >> 32; break; case 0x4000: val = m->timecmp; break; case 0x4004: val = m->timecmp >> 32; break; default: val = 0; break; } return val; } static void clint_write(void *opaque, uint32_t offset, uint32_t val, int size_log2) { RISCVMachine *m = opaque; assert(size_log2 == 2); switch(offset) { case 0x4000: m->timecmp = (m->timecmp & ~0xffffffff) | val; riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP); break; case 0x4004: m->timecmp = (m->timecmp & 0xffffffff) | ((uint64_t)val << 32); riscv_cpu_reset_mip(m->cpu_state, MIP_MTIP); break; default: break; } } static void plic_update_mip(RISCVMachine *s) { RISCVCPUState *cpu = s->cpu_state; uint32_t mask; mask = s->plic_pending_irq & ~s->plic_served_irq; if (mask) { riscv_cpu_set_mip(cpu, MIP_MEIP | MIP_SEIP); } else { riscv_cpu_reset_mip(cpu, MIP_MEIP | MIP_SEIP); } } #define PLIC_HART_BASE 0x200000 #define PLIC_HART_SIZE 0x1000 static uint32_t plic_read(void *opaque, uint32_t offset, int size_log2) { RISCVMachine *s = opaque; uint32_t val, mask; int i; assert(size_log2 == 2); switch(offset) { case PLIC_HART_BASE: val = 0; break; case PLIC_HART_BASE + 4: mask = s->plic_pending_irq & ~s->plic_served_irq; if (mask != 0) { i = ctz32(mask); s->plic_served_irq |= 1 << i; plic_update_mip(s); val = i + 1; } else { val = 0; } break; default: val = 0; break; } return val; } static void plic_write(void *opaque, uint32_t offset, uint32_t val, int size_log2) { RISCVMachine *s = opaque; assert(size_log2 == 2); switch(offset) { case PLIC_HART_BASE + 4: val--; if (val < 32) { s->plic_served_irq &= ~(1 << val); plic_update_mip(s); } break; default: break; } } static void plic_set_irq(void *opaque, int irq_num, int state) { RISCVMachine *s = opaque; uint32_t mask; mask = 1 << (irq_num - 1); if (state) s->plic_pending_irq |= mask; else s->plic_pending_irq &= ~mask; plic_update_mip(s); } static uint8_t *get_ram_ptr(RISCVMachine *s, uint64_t paddr) { PhysMemoryRange *pr = get_phys_mem_range(s->mem_map, paddr); if (!pr || !pr->is_ram) return NULL; return pr->phys_mem + (uintptr_t)(paddr - pr->addr); } /* FDT machine description */ #define FDT_MAGIC 0xd00dfeed #define FDT_VERSION 17 struct fdt_header { uint32_t magic; uint32_t totalsize; uint32_t off_dt_struct; uint32_t off_dt_strings; uint32_t off_mem_rsvmap; uint32_t version; uint32_t last_comp_version; /* <= 17 */ uint32_t boot_cpuid_phys; uint32_t size_dt_strings; uint32_t size_dt_struct; }; struct fdt_reserve_entry { uint64_t address; uint64_t size; }; #define FDT_BEGIN_NODE 1 #define FDT_END_NODE 2 #define FDT_PROP 3 #define FDT_NOP 4 #define FDT_END 9 typedef struct { uint32_t *tab; int tab_len; int tab_size; int open_node_count; char *string_table; int string_table_len; int string_table_size; } FDTState; static FDTState *fdt_init(void) { FDTState *s; s = mallocz(sizeof(*s)); return s; } static void fdt_alloc_len(FDTState *s, int len) { int new_size; if (unlikely(len > s->tab_size)) { new_size = max_int(len, s->tab_size * 3 / 2); s->tab = realloc(s->tab, new_size * sizeof(uint32_t)); s->tab_size = new_size; } } static void fdt_put32(FDTState *s, int v) { fdt_alloc_len(s, s->tab_len + 1); s->tab[s->tab_len++] = cpu_to_be32(v); } /* the data is zero padded */ static void fdt_put_data(FDTState *s, const uint8_t *data, int len) { int len1; len1 = (len + 3) / 4; fdt_alloc_len(s, s->tab_len + len1); memcpy(s->tab + s->tab_len, data, len); memset((uint8_t *)(s->tab + s->tab_len) + len, 0, -len & 3); s->tab_len += len1; } static void fdt_begin_node(FDTState *s, const char *name) { fdt_put32(s, FDT_BEGIN_NODE); fdt_put_data(s, (uint8_t *)name, strlen(name) + 1); s->open_node_count++; } static void fdt_begin_node_num(FDTState *s, const char *name, uint64_t n) { char buf[256]; snprintf(buf, sizeof(buf), "%s@%" PRIx64, name, n); fdt_begin_node(s, buf); } static void fdt_end_node(FDTState *s) { fdt_put32(s, FDT_END_NODE); s->open_node_count--; } static int fdt_get_string_offset(FDTState *s, const char *name) { int pos, new_size, name_size, new_len; pos = 0; while (pos < s->string_table_len) { if (!strcmp(s->string_table + pos, name)) return pos; pos += strlen(s->string_table + pos) + 1; } /* add a new string */ name_size = strlen(name) + 1; new_len = s->string_table_len + name_size; if (new_len > s->string_table_size) { new_size = max_int(new_len, s->string_table_size * 3 / 2); s->string_table = realloc(s->string_table, new_size); s->string_table_size = new_size; } pos = s->string_table_len; memcpy(s->string_table + pos, name, name_size); s->string_table_len = new_len; return pos; } static void fdt_prop(FDTState *s, const char *prop_name, const void *data, int data_len) { fdt_put32(s, FDT_PROP); fdt_put32(s, data_len); fdt_put32(s, fdt_get_string_offset(s, prop_name)); fdt_put_data(s, data, data_len); } static void fdt_prop_tab_u32(FDTState *s, const char *prop_name, uint32_t *tab, int tab_len) { int i; fdt_put32(s, FDT_PROP); fdt_put32(s, tab_len * sizeof(uint32_t)); fdt_put32(s, fdt_get_string_offset(s, prop_name)); for(i = 0; i < tab_len; i++) fdt_put32(s, tab[i]); } static void fdt_prop_u32(FDTState *s, const char *prop_name, uint32_t val) { fdt_prop_tab_u32(s, prop_name, &val, 1); } static void fdt_prop_tab_u64_2(FDTState *s, const char *prop_name, uint64_t v0, uint64_t v1) { uint32_t tab[4]; tab[0] = v0 >> 32; tab[1] = v0; tab[2] = v1 >> 32; tab[3] = v1; fdt_prop_tab_u32(s, prop_name, tab, 4); } static void fdt_prop_str(FDTState *s, const char *prop_name, const char *str) { fdt_prop(s, prop_name, str, strlen(str) + 1); } /* NULL terminated string list */ static void fdt_prop_tab_str(FDTState *s, const char *prop_name, ...) { va_list ap; int size, str_size; char *ptr, *tab; va_start(ap, prop_name); size = 0; for(;;) { ptr = va_arg(ap, char *); if (!ptr) break; str_size = strlen(ptr) + 1; size += str_size; } va_end(ap); tab = malloc(size); va_start(ap, prop_name); size = 0; for(;;) { ptr = va_arg(ap, char *); if (!ptr) break; str_size = strlen(ptr) + 1; memcpy(tab + size, ptr, str_size); size += str_size; } va_end(ap); fdt_prop(s, prop_name, tab, size); free(tab); } /* write the FDT to 'dst1'. return the FDT size in bytes */ int fdt_output(FDTState *s, uint8_t *dst) { struct fdt_header *h; struct fdt_reserve_entry *re; int dt_struct_size; int dt_strings_size; int pos; assert(s->open_node_count == 0); fdt_put32(s, FDT_END); dt_struct_size = s->tab_len * sizeof(uint32_t); dt_strings_size = s->string_table_len; h = (struct fdt_header *)dst; h->magic = cpu_to_be32(FDT_MAGIC); h->version = cpu_to_be32(FDT_VERSION); h->last_comp_version = cpu_to_be32(16); h->boot_cpuid_phys = cpu_to_be32(0); h->size_dt_strings = cpu_to_be32(dt_strings_size); h->size_dt_struct = cpu_to_be32(dt_struct_size); pos = sizeof(struct fdt_header); h->off_dt_struct = cpu_to_be32(pos); memcpy(dst + pos, s->tab, dt_struct_size); pos += dt_struct_size; /* align to 8 */ while ((pos & 7) != 0) { dst[pos++] = 0; } h->off_mem_rsvmap = cpu_to_be32(pos); re = (struct fdt_reserve_entry *)(dst + pos); re->address = 0; /* no reserved entry */ re->size = 0; pos += sizeof(struct fdt_reserve_entry); h->off_dt_strings = cpu_to_be32(pos); memcpy(dst + pos, s->string_table, dt_strings_size); pos += dt_strings_size; /* align to 8, just in case */ while ((pos & 7) != 0) { dst[pos++] = 0; } h->totalsize = cpu_to_be32(pos); return pos; } void fdt_end(FDTState *s) { free(s->tab); free(s->string_table); free(s); } static int riscv_build_fdt(RISCVMachine *m, uint8_t *dst, const char *cmd_line) { FDTState *s; int size, max_xlen, i, cur_phandle, intc_phandle, plic_phandle; char isa_string[128], *q; uint32_t misa; uint32_t tab[4]; FBDevice *fb_dev; s = fdt_init(); cur_phandle = 1; fdt_begin_node(s, ""); fdt_prop_u32(s, "#address-cells", 2); fdt_prop_u32(s, "#size-cells", 2); fdt_prop_str(s, "compatible", "ucbbar,riscvemu-bar_dev"); fdt_prop_str(s, "model", "ucbbar,riscvemu-bare"); /* CPU list */ fdt_begin_node(s, "cpus"); fdt_prop_u32(s, "#address-cells", 1); fdt_prop_u32(s, "#size-cells", 0); fdt_prop_u32(s, "timebase-frequency", RTC_FREQ); /* cpu */ fdt_begin_node_num(s, "cpu", 0); fdt_prop_str(s, "device_type", "cpu"); fdt_prop_u32(s, "reg", 0); fdt_prop_str(s, "status", "okay"); fdt_prop_str(s, "compatible", "riscv"); max_xlen = riscv_cpu_get_max_xlen(); misa = riscv_cpu_get_misa(m->cpu_state); q = isa_string; q += snprintf(isa_string, sizeof(isa_string), "rv%d", max_xlen); for(i = 0; i < 26; i++) { if (misa & (1 << i)) *q++ = 'a' + i; } *q = '\0'; fdt_prop_str(s, "riscv,isa", isa_string); fdt_prop_str(s, "mmu-type", max_xlen <= 32 ? "sv32" : "sv48"); fdt_prop_u32(s, "clock-frequency", 2000000000); fdt_begin_node(s, "interrupt-controller"); fdt_prop_u32(s, "#interrupt-cells", 1); fdt_prop(s, "interrupt-controller", NULL, 0); fdt_prop_str(s, "compatible", "riscv,cpu-intc"); intc_phandle = cur_phandle++; fdt_prop_u32(s, "phandle", intc_phandle); fdt_end_node(s); /* interrupt-controller */ fdt_end_node(s); /* cpu */ fdt_end_node(s); /* cpus */ fdt_begin_node_num(s, "memory", RAM_BASE_ADDR); fdt_prop_str(s, "device_type", "memory"); tab[0] = (uint64_t)RAM_BASE_ADDR >> 32; tab[1] = RAM_BASE_ADDR; tab[2] = m->ram_size >> 32; tab[3] = m->ram_size; fdt_prop_tab_u32(s, "reg", tab, 4); fdt_end_node(s); /* memory */ fdt_begin_node(s, "soc"); fdt_prop_u32(s, "#address-cells", 2); fdt_prop_u32(s, "#size-cells", 2); fdt_prop_tab_str(s, "compatible", "ucbbar,riscvemu-bar-soc", "simple-bus", NULL); fdt_prop(s, "ranges", NULL, 0); fdt_begin_node_num(s, "clint", CLINT_BASE_ADDR); fdt_prop_str(s, "compatible", "riscv,clint0"); tab[0] = intc_phandle; tab[1] = 3; /* M IPI irq */ tab[2] = intc_phandle; tab[3] = 7; /* M timer irq */ fdt_prop_tab_u32(s, "interrupts-extended", tab, 4); fdt_prop_tab_u64_2(s, "reg", CLINT_BASE_ADDR, CLINT_SIZE); fdt_end_node(s); /* clint */ fdt_begin_node_num(s, "plic", PLIC_BASE_ADDR); fdt_prop_u32(s, "#interrupt-cells", 1); fdt_prop(s, "interrupt-controller", NULL, 0); fdt_prop_str(s, "compatible", "riscv,plic0"); fdt_prop_u32(s, "riscv,ndev", 31); fdt_prop_tab_u64_2(s, "reg", PLIC_BASE_ADDR, PLIC_SIZE); tab[0] = intc_phandle; tab[1] = 9; /* S ext irq */ tab[2] = intc_phandle; tab[3] = 11; /* M ext irq */ fdt_prop_tab_u32(s, "interrupts-extended", tab, 4); plic_phandle = cur_phandle++; fdt_prop_u32(s, "phandle", plic_phandle); fdt_end_node(s); /* plic */ for(i = 0; i < m->virtio_count; i++) { fdt_begin_node_num(s, "virtio", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE); fdt_prop_str(s, "compatible", "virtio,mmio"); fdt_prop_tab_u64_2(s, "reg", VIRTIO_BASE_ADDR + i * VIRTIO_SIZE, VIRTIO_SIZE); tab[0] = plic_phandle; tab[1] = VIRTIO_IRQ + i; fdt_prop_tab_u32(s, "interrupts-extended", tab, 2); fdt_end_node(s); /* virtio */ } fb_dev = m->common.fb_dev; if (fb_dev) { fdt_begin_node_num(s, "framebuffer", FRAMEBUFFER_BASE_ADDR); fdt_prop_str(s, "compatible", "simple-framebuffer"); fdt_prop_tab_u64_2(s, "reg", FRAMEBUFFER_BASE_ADDR, fb_dev->fb_size); fdt_prop_u32(s, "width", fb_dev->width); fdt_prop_u32(s, "height", fb_dev->height); fdt_prop_u32(s, "stride", fb_dev->stride); fdt_prop_str(s, "format", "a8r8g8b8"); fdt_end_node(s); /* framebuffer */ } fdt_end_node(s); /* soc */ fdt_begin_node(s, "chosen"); fdt_prop_str(s, "bootargs", cmd_line ? cmd_line : ""); fdt_end_node(s); /* chosen */ fdt_end_node(s); /* / */ size = fdt_output(s, dst); #if 0 { FILE *f; f = fopen("/tmp/riscvemu.dtb", "wb"); fwrite(dst, 1, size, f); fclose(f); } #endif fdt_end(s); return size; } static void copy_kernel(RISCVMachine *s, const uint8_t *buf, int buf_len, const char *cmd_line) { uint32_t fdt_addr; uint8_t *ram_ptr; uint32_t *q; if (buf_len > s->ram_size) { vm_error("Kernel too big\n"); exit(1); } ram_ptr = get_ram_ptr(s, RAM_BASE_ADDR); memcpy(ram_ptr, buf, buf_len); ram_ptr = get_ram_ptr(s, 0); fdt_addr = 0x1000 + 8 * 8; riscv_build_fdt(s, ram_ptr + fdt_addr, cmd_line); /* jump_addr = 0x80000000 */ q = (uint32_t *)(ram_ptr + 0x1000); q[0] = 0x297 + 0x80000000 - 0x1000; /* auipc t0, jump_addr */ q[1] = 0x597; /* auipc a1, dtb */ q[2] = 0x58593 + ((fdt_addr - 4) << 20); /* addi a1, a1, dtb */ q[3] = 0xf1402573; /* csrr a0, mhartid */ q[4] = 0x00028067; /* jalr zero, t0, jump_addr */ } static void riscv_flush_tlb_write_range(void *opaque, uint8_t *ram_addr, size_t ram_size) { RISCVMachine *s = opaque; riscv_cpu_flush_tlb_write_range_ram(s->cpu_state, ram_addr, ram_size); } void virt_machine_set_defaults(VirtMachineParams *p) { memset(p, 0, sizeof(*p)); } VirtMachine *virt_machine_init(const VirtMachineParams *p) { RISCVMachine *s; VIRTIODevice *blk_dev; int irq_num, i; VIRTIOBusDef vbus_s, *vbus = &vbus_s; s = mallocz(sizeof(*s)); s->ram_size = p->ram_size; s->mem_map = phys_mem_map_init(); /* needed to handle the RAM dirty bits */ s->mem_map->opaque = s; s->mem_map->flush_tlb_write_range = riscv_flush_tlb_write_range; s->cpu_state = riscv_cpu_init(s->mem_map); /* RAM */ cpu_register_ram(s->mem_map, RAM_BASE_ADDR, p->ram_size, 0); cpu_register_ram(s->mem_map, 0x00000000, LOW_RAM_SIZE, 0); s->rtc_real_time = p->rtc_real_time; if (p->rtc_real_time) { s->rtc_start_time = rtc_get_real_time(s); } cpu_register_device(s->mem_map, CLINT_BASE_ADDR, CLINT_SIZE, s, clint_read, clint_write, DEVIO_SIZE32); cpu_register_device(s->mem_map, PLIC_BASE_ADDR, PLIC_SIZE, s, plic_read, plic_write, DEVIO_SIZE32); for(i = 1; i < 32; i++) { irq_init(&s->plic_irq[i], plic_set_irq, s, i); } cpu_register_device(s->mem_map, HTIF_BASE_ADDR, 16, s, htif_read, htif_write, DEVIO_SIZE32); s->common.console = p->console; memset(vbus, 0, sizeof(*vbus)); vbus->mem_map = s->mem_map; vbus->addr = VIRTIO_BASE_ADDR; irq_num = VIRTIO_IRQ; /* virtio console */ if (p->console) { vbus->irq = &s->plic_irq[irq_num]; s->common.console_dev = virtio_console_init(vbus, p->console); vbus->addr += VIRTIO_SIZE; irq_num++; s->virtio_count++; } /* virtio net device */ for(i = 0; i < p->eth_count; i++) { vbus->irq = &s->plic_irq[irq_num]; virtio_net_init(vbus, p->tab_eth[i].net); s->common.net = p->tab_eth[i].net; vbus->addr += VIRTIO_SIZE; irq_num++; s->virtio_count++; } /* virtio block device */ for(i = 0; i < p->drive_count; i++) { vbus->irq = &s->plic_irq[irq_num]; blk_dev = virtio_block_init(vbus, p->tab_drive[i].block_dev); (void)blk_dev; vbus->addr += VIRTIO_SIZE; irq_num++; s->virtio_count++; } /* virtio filesystem */ for(i = 0; i < p->fs_count; i++) { VIRTIODevice *fs_dev; vbus->irq = &s->plic_irq[irq_num]; fs_dev = virtio_9p_init(vbus, p->tab_fs[i].fs_dev, p->tab_fs[i].tag); (void)fs_dev; // virtio_set_debug(fs_dev, VIRTIO_DEBUG_9P); vbus->addr += VIRTIO_SIZE; irq_num++; s->virtio_count++; } if (p->display_device) { FBDevice *fb_dev; fb_dev = mallocz(sizeof(*fb_dev)); s->common.fb_dev = fb_dev; if (!strcmp(p->display_device, "simplefb")) { simplefb_init(s->mem_map, FRAMEBUFFER_BASE_ADDR, fb_dev, p->width, p->height); } else { vm_error("unsupported display device: %s\n", p->display_device); exit(1); } } if (p->input_device) { if (!strcmp(p->input_device, "virtio")) { vbus->irq = &s->plic_irq[irq_num]; s->keyboard_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_KEYBOARD); vbus->addr += VIRTIO_SIZE; irq_num++; s->virtio_count++; vbus->irq = &s->plic_irq[irq_num]; s->mouse_dev = virtio_input_init(vbus, VIRTIO_INPUT_TYPE_TABLET); vbus->addr += VIRTIO_SIZE; irq_num++; s->virtio_count++; } else { vm_error("unsupported input device: %s\n", p->input_device); exit(1); } } if (!p->files[VM_FILE_BIOS].buf) { vm_error("No bios found"); } copy_kernel(s, p->files[VM_FILE_BIOS].buf, p->files[VM_FILE_BIOS].len, p->cmdline); return (VirtMachine *)s; } void virt_machine_end(VirtMachine *s1) { RISCVMachine *s = (RISCVMachine *)s1; /* XXX: stop all */ riscv_cpu_end(s->cpu_state); phys_mem_map_end(s->mem_map); free(s); } /* in ms */ int virt_machine_get_sleep_duration(VirtMachine *s1, int delay) { RISCVMachine *m = (RISCVMachine *)s1; RISCVCPUState *s = m->cpu_state; int64_t delay1; /* wait for an event: the only asynchronous event is the RTC timer */ if (!(riscv_cpu_get_mip(s) & MIP_MTIP)) { delay1 = m->timecmp - rtc_get_time(m); if (delay1 <= 0) { riscv_cpu_set_mip(s, MIP_MTIP); delay = 0; } else { /* convert delay to ms */ delay1 = delay1 / (RTC_FREQ / 1000); if (delay1 < delay) delay = delay1; } } if (!riscv_cpu_get_power_down(s)) delay = 0; return delay; } void virt_machine_interp(VirtMachine *s1, int max_exec_cycle) { RISCVMachine *s = (RISCVMachine *)s1; riscv_cpu_interp(s->cpu_state, max_exec_cycle); } const char *virt_machine_get_name(void) { switch(riscv_cpu_get_max_xlen()) { case 32: return "riscv32"; case 64: return "riscv64"; case 128: return "riscv128"; default: abort(); } } void vm_send_key_event(VirtMachine *s1, BOOL is_down, uint16_t key_code) { RISCVMachine *s = (RISCVMachine *)s1; if (s->keyboard_dev) { virtio_input_send_key_event(s->keyboard_dev, is_down, key_code); } } BOOL vm_mouse_is_absolute(VirtMachine *s) { return TRUE; } void vm_send_mouse_event(VirtMachine *s1, int dx, int dy, int dz, unsigned int buttons) { RISCVMachine *s = (RISCVMachine *)s1; if (s->mouse_dev) { virtio_input_send_mouse_event(s->mouse_dev, dx, dy, dz, buttons); } }
26.780836
80
0.59238
[ "model" ]
8053766f68f851b8733a9ed0b1b384bec7b3acf9
530
h
C
ZHKKeyBoard/Classes/Defines/ZHKTextInput.h
ZHK1024/ZHKKeyBoard
e8c451931d83e0fb5e43e75c3e3296eb8d632806
[ "MIT" ]
null
null
null
ZHKKeyBoard/Classes/Defines/ZHKTextInput.h
ZHK1024/ZHKKeyBoard
e8c451931d83e0fb5e43e75c3e3296eb8d632806
[ "MIT" ]
null
null
null
ZHKKeyBoard/Classes/Defines/ZHKTextInput.h
ZHK1024/ZHKKeyBoard
e8c451931d83e0fb5e43e75c3e3296eb8d632806
[ "MIT" ]
null
null
null
// // ZHKIputTarget.h // Pods // // Created by ZHK on 2018/7/30. // // #import <UIKit/UIKit.h> #import "ZHKBlockObject.h" #import "ZHKSelectionModels.h" @protocol ZHKTextInput <UITextInput> @property (nonatomic, strong) UIView *inputView; // Block 容器对象 @property (nonatomic, strong, readonly) ZHKBlockObject *keyboardBlockObject; @property (nonatomic, strong) id <ZHKSelectionInfo> selectionInfo; /// 设置输入对象回调 /// @param block 回调键盘输入的对象: NSDate, NSString, NSArray 等 - (void)setKeyboardBlock:(void(^)(id object))block; @end
22.083333
76
0.730189
[ "object" ]
8054be10186561dbdf7e9e3ea1b61ea785628b08
262
h
C
pedsim_simulator/include/pedsim_simulator/transpose.h
vdBerg93/pedsim_ros
088abbeb9e830e2d180e775b3cabf080d9df3629
[ "BSD-2-Clause" ]
2
2020-03-23T22:45:41.000Z
2020-12-16T19:33:26.000Z
pedsim_simulator/include/pedsim_simulator/transpose.h
vdBerg93/pedsim_ros
088abbeb9e830e2d180e775b3cabf080d9df3629
[ "BSD-2-Clause" ]
null
null
null
pedsim_simulator/include/pedsim_simulator/transpose.h
vdBerg93/pedsim_ros
088abbeb9e830e2d180e775b3cabf080d9df3629
[ "BSD-2-Clause" ]
7
2019-07-15T09:51:42.000Z
2021-02-02T01:36:51.000Z
#ifndef TRANSPOSE_H #define TRANSPOSE_H #include <cstdlib> #include <cmath> #include <iostream> #include <sstream> #include <fstream> #include <deque> #include <vector> void transpose_CSV( const std::string& filename ); int main(int argc, char** argv); #endif
17.466667
50
0.740458
[ "vector" ]
80586cef05f576033d49b7ba9a5df1def348fc96
30,715
h
C
vendor/go.universe.tf/netboot/third_party/ipxe/src/drivers/net/intelxl.h
dingyin/arktos-vm-runtime
3182bb5da9b7932c189059f196d0bd5948075532
[ "Apache-2.0" ]
5
2020-02-21T19:54:22.000Z
2020-08-20T09:00:42.000Z
vendor/go.universe.tf/netboot/third_party/ipxe/src/drivers/net/intelxl.h
dingyin/arktos-vm-runtime
3182bb5da9b7932c189059f196d0bd5948075532
[ "Apache-2.0" ]
26
2020-05-06T03:50:25.000Z
2020-09-02T23:00:43.000Z
vendor/go.universe.tf/netboot/third_party/ipxe/src/drivers/net/intelxl.h
dingyin/arktos-vm-runtime
3182bb5da9b7932c189059f196d0bd5948075532
[ "Apache-2.0" ]
2
2020-02-21T04:41:01.000Z
2020-02-27T19:21:52.000Z
#ifndef _INTELX_H #define _INTELX_H /** @file * * Intel 40 Gigabit Ethernet network card driver * */ FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); #include <stdint.h> #include <ipxe/if_ether.h> #include <ipxe/pcimsix.h> struct intelxl_nic; /** BAR size */ #define INTELXL_BAR_SIZE 0x200000 /** Alignment * * No data structure requires greater than 256 byte alignment. */ #define INTELXL_ALIGN 256 /****************************************************************************** * * Admin queue * ****************************************************************************** */ /** PF Admin Command Queue register block */ #define INTELXL_ADMIN_CMD 0x080000 /** PF Admin Event Queue register block */ #define INTELXL_ADMIN_EVT 0x080080 /** Admin Queue Base Address Low Register (offset) */ #define INTELXL_ADMIN_BAL 0x000 /** Admin Queue Base Address High Register (offset) */ #define INTELXL_ADMIN_BAH 0x100 /** Admin Queue Length Register (offset) */ #define INTELXL_ADMIN_LEN 0x200 #define INTELXL_ADMIN_LEN_LEN(x) ( (x) << 0 ) /**< Queue length */ #define INTELXL_ADMIN_LEN_ENABLE 0x80000000UL /**< Queue enable */ /** Admin Queue Head Register (offset) */ #define INTELXL_ADMIN_HEAD 0x300 /** Admin Queue Tail Register (offset) */ #define INTELXL_ADMIN_TAIL 0x400 /** Admin queue register offsets * * The physical and virtual function register maps have no discernible * relationship. */ struct intelxl_admin_offsets { /** Base Address Low Register offset */ unsigned int bal; /** Base Address High Register offset */ unsigned int bah; /** Length Register offset */ unsigned int len; /** Head Register offset */ unsigned int head; /** Tail Register offset */ unsigned int tail; }; /** Admin queue data buffer command parameters */ struct intelxl_admin_buffer_params { /** Reserved */ uint8_t reserved[8]; /** Buffer address high */ uint32_t high; /** Buffer address low */ uint32_t low; } __attribute__ (( packed )); /** Admin queue Get Version command */ #define INTELXL_ADMIN_VERSION 0x0001 /** Admin queue version number */ struct intelxl_admin_version { /** Major version number */ uint16_t major; /** Minor version number */ uint16_t minor; } __attribute__ (( packed )); /** Admin queue Get Version command parameters */ struct intelxl_admin_version_params { /** ROM version */ uint32_t rom; /** Firmware build ID */ uint32_t build; /** Firmware version */ struct intelxl_admin_version firmware; /** API version */ struct intelxl_admin_version api; } __attribute__ (( packed )); /** Admin queue Driver Version command */ #define INTELXL_ADMIN_DRIVER 0x0002 /** Admin queue Driver Version command parameters */ struct intelxl_admin_driver_params { /** Driver version */ uint8_t major; /** Minor version */ uint8_t minor; /** Build version */ uint8_t build; /** Sub-build version */ uint8_t sub; /** Reserved */ uint8_t reserved[4]; /** Data buffer address */ uint64_t address; } __attribute__ (( packed )); /** Admin queue Driver Version data buffer */ struct intelxl_admin_driver_buffer { /** Driver name */ char name[32]; } __attribute__ (( packed )); /** Admin queue Shutdown command */ #define INTELXL_ADMIN_SHUTDOWN 0x0003 /** Admin queue Shutdown command parameters */ struct intelxl_admin_shutdown_params { /** Driver unloading */ uint8_t unloading; /** Reserved */ uint8_t reserved[15]; } __attribute__ (( packed )); /** Driver is unloading */ #define INTELXL_ADMIN_SHUTDOWN_UNLOADING 0x01 /** Admin queue Clear PXE Mode command */ #define INTELXL_ADMIN_CLEAR_PXE 0x0110 /** Admin queue Clear PXE Mode command parameters */ struct intelxl_admin_clear_pxe_params { /** Magic value */ uint8_t magic; /** Reserved */ uint8_t reserved[15]; } __attribute__ (( packed )); /** Clear PXE Mode magic value */ #define INTELXL_ADMIN_CLEAR_PXE_MAGIC 0x02 /** Admin queue Get Switch Configuration command */ #define INTELXL_ADMIN_SWITCH 0x0200 /** Switching element configuration */ struct intelxl_admin_switch_config { /** Switching element type */ uint8_t type; /** Revision */ uint8_t revision; /** Switching element ID */ uint16_t seid; /** Uplink switching element ID */ uint16_t uplink; /** Downlink switching element ID */ uint16_t downlink; /** Reserved */ uint8_t reserved_b[3]; /** Connection type */ uint8_t connection; /** Reserved */ uint8_t reserved_c[2]; /** Element specific information */ uint16_t info; } __attribute__ (( packed )); /** Virtual Station Inferface element type */ #define INTELXL_ADMIN_SWITCH_TYPE_VSI 19 /** Admin queue Get Switch Configuration command parameters */ struct intelxl_admin_switch_params { /** Starting switching element identifier */ uint16_t next; /** Reserved */ uint8_t reserved[6]; /** Data buffer address */ uint64_t address; } __attribute__ (( packed )); /** Admin queue Get Switch Configuration data buffer */ struct intelxl_admin_switch_buffer { /** Number of switching elements reported */ uint16_t count; /** Total number of switching elements */ uint16_t total; /** Reserved */ uint8_t reserved_a[12]; /** Switch configuration */ struct intelxl_admin_switch_config cfg; } __attribute__ (( packed )); /** Admin queue Get VSI Parameters command */ #define INTELXL_ADMIN_VSI 0x0212 /** Admin queue Get VSI Parameters command parameters */ struct intelxl_admin_vsi_params { /** VSI switching element ID */ uint16_t vsi; /** Reserved */ uint8_t reserved[6]; /** Data buffer address */ uint64_t address; } __attribute__ (( packed )); /** Admin queue Get VSI Parameters data buffer */ struct intelxl_admin_vsi_buffer { /** Reserved */ uint8_t reserved_a[30]; /** Queue numbers */ uint16_t queue[16]; /** Reserved */ uint8_t reserved_b[34]; /** Queue set handles for each traffic class */ uint16_t qset[8]; /** Reserved */ uint8_t reserved_c[16]; } __attribute__ (( packed )); /** Admin queue Set VSI Promiscuous Modes command */ #define INTELXL_ADMIN_PROMISC 0x0254 /** Admin queue Set VSI Promiscuous Modes command parameters */ struct intelxl_admin_promisc_params { /** Flags */ uint16_t flags; /** Valid flags */ uint16_t valid; /** VSI switching element ID */ uint16_t vsi; /** Reserved */ uint8_t reserved[10]; } __attribute__ (( packed )); /** Promiscuous unicast mode */ #define INTELXL_ADMIN_PROMISC_FL_UNICAST 0x0001 /** Promiscuous multicast mode */ #define INTELXL_ADMIN_PROMISC_FL_MULTICAST 0x0002 /** Promiscuous broadcast mode */ #define INTELXL_ADMIN_PROMISC_FL_BROADCAST 0x0004 /** Promiscuous VLAN mode */ #define INTELXL_ADMIN_PROMISC_FL_VLAN 0x0010 /** Admin queue Restart Autonegotiation command */ #define INTELXL_ADMIN_AUTONEG 0x0605 /** Admin queue Restart Autonegotiation command parameters */ struct intelxl_admin_autoneg_params { /** Flags */ uint8_t flags; /** Reserved */ uint8_t reserved[15]; } __attribute__ (( packed )); /** Restart autonegotiation */ #define INTELXL_ADMIN_AUTONEG_FL_RESTART 0x02 /** Enable link */ #define INTELXL_ADMIN_AUTONEG_FL_ENABLE 0x04 /** Admin queue Get Link Status command */ #define INTELXL_ADMIN_LINK 0x0607 /** Admin queue Get Link Status command parameters */ struct intelxl_admin_link_params { /** Link status notification */ uint8_t notify; /** Reserved */ uint8_t reserved_a; /** PHY type */ uint8_t phy; /** Link speed */ uint8_t speed; /** Link status */ uint8_t status; /** Reserved */ uint8_t reserved_b[11]; } __attribute__ (( packed )); /** Notify driver of link status changes */ #define INTELXL_ADMIN_LINK_NOTIFY 0x03 /** Link is up */ #define INTELXL_ADMIN_LINK_UP 0x01 /** Admin queue Send Message to PF command */ #define INTELXL_ADMIN_SEND_TO_PF 0x0801 /** Admin queue Send Message to VF command */ #define INTELXL_ADMIN_SEND_TO_VF 0x0802 /** Admin Queue VF Reset opcode */ #define INTELXL_ADMIN_VF_RESET 0x00000002 /** Admin Queue VF Get Resources opcode */ #define INTELXL_ADMIN_VF_GET_RESOURCES 0x00000003 /** Admin Queue VF Get Resources data buffer */ struct intelxl_admin_vf_get_resources_buffer { /** Reserved */ uint8_t reserved_a[20]; /** VSI switching element ID */ uint16_t vsi; /** Reserved */ uint8_t reserved_b[8]; /** MAC address */ uint8_t mac[ETH_ALEN]; } __attribute__ (( packed )); /** Admin Queue VF Status Change Event opcode */ #define INTELXL_ADMIN_VF_STATUS 0x00000011 /** Link status change event type */ #define INTELXL_ADMIN_VF_STATUS_LINK 0x00000001 /** Link status change event data */ struct intelxl_admin_vf_status_link { /** Link speed */ uint32_t speed; /** Link status */ uint8_t status; /** Reserved */ uint8_t reserved[3]; } __attribute__ (( packed )); /** Admin Queue VF Status Change Event data buffer */ struct intelxl_admin_vf_status_buffer { /** Event type */ uint32_t event; /** Event data */ union { /** Link change event data */ struct intelxl_admin_vf_status_link link; } data; /** Reserved */ uint8_t reserved[4]; } __attribute__ (( packed )); /** Admin Queue VF Configure Queues opcode */ #define INTELXL_ADMIN_VF_CONFIGURE 0x00000006 /** Admin Queue VF Configure Queues data buffer */ struct intelxl_admin_vf_configure_buffer { /** VSI switching element ID */ uint16_t vsi; /** Number of queue pairs */ uint16_t count; /** Reserved */ uint8_t reserved_a[4]; /** Transmit queue */ struct { /** VSI switching element ID */ uint16_t vsi; /** Queue ID */ uint16_t id; /** Queue count */ uint16_t count; /** Reserved */ uint8_t reserved_a[2]; /** Base address */ uint64_t base; /** Reserved */ uint8_t reserved_b[8]; } __attribute__ (( packed )) tx; /** Receive queue */ struct { /** VSI switching element ID */ uint16_t vsi; /** Queue ID */ uint16_t id; /** Queue count */ uint32_t count; /** Reserved */ uint8_t reserved_a[4]; /** Data buffer length */ uint32_t len; /** Maximum frame size */ uint32_t mfs; /** Reserved */ uint8_t reserved_b[4]; /** Base address */ uint64_t base; /** Reserved */ uint8_t reserved_c[8]; } __attribute__ (( packed )) rx; /** Reserved * * This field exists only due to a bug in the PF driver's * message validation logic, which causes it to miscalculate * the expected message length. */ uint8_t reserved_b[64]; } __attribute__ (( packed )); /** Admin Queue VF IRQ Map opcode */ #define INTELXL_ADMIN_VF_IRQ_MAP 0x00000007 /** Admin Queue VF IRQ Map data buffer */ struct intelxl_admin_vf_irq_map_buffer { /** Number of interrupt vectors */ uint16_t count; /** VSI switching element ID */ uint16_t vsi; /** Interrupt vector ID */ uint16_t vec; /** Receive queue bitmap */ uint16_t rxmap; /** Transmit queue bitmap */ uint16_t txmap; /** Receive interrupt throttling index */ uint16_t rxitr; /** Transmit interrupt throttling index */ uint16_t txitr; /** Reserved * * This field exists only due to a bug in the PF driver's * message validation logic, which causes it to miscalculate * the expected message length. */ uint8_t reserved[12]; } __attribute__ (( packed )); /** Admin Queue VF Enable Queues opcode */ #define INTELXL_ADMIN_VF_ENABLE 0x00000008 /** Admin Queue VF Disable Queues opcode */ #define INTELXL_ADMIN_VF_DISABLE 0x00000009 /** Admin Queue VF Enable/Disable Queues data buffer */ struct intelxl_admin_vf_queues_buffer { /** VSI switching element ID */ uint16_t vsi; /** Reserved */ uint8_t reserved[2]; /** Receive queue bitmask */ uint32_t rx; /** Transmit queue bitmask */ uint32_t tx; } __attribute__ (( packed )); /** Admin Queue VF Configure Promiscuous Mode opcode */ #define INTELXL_ADMIN_VF_PROMISC 0x0000000e /** Admin Queue VF Configure Promiscuous Mode data buffer */ struct intelxl_admin_vf_promisc_buffer { /** VSI switching element ID */ uint16_t vsi; /** Flags */ uint16_t flags; } __attribute__ (( packed )); /** Admin queue command parameters */ union intelxl_admin_params { /** Additional data buffer command parameters */ struct intelxl_admin_buffer_params buffer; /** Get Version command parameters */ struct intelxl_admin_version_params version; /** Driver Version command parameters */ struct intelxl_admin_driver_params driver; /** Shutdown command parameters */ struct intelxl_admin_shutdown_params shutdown; /** Clear PXE Mode command parameters */ struct intelxl_admin_clear_pxe_params pxe; /** Get Switch Configuration command parameters */ struct intelxl_admin_switch_params sw; /** Get VSI Parameters command parameters */ struct intelxl_admin_vsi_params vsi; /** Set VSI Promiscuous Modes command parameters */ struct intelxl_admin_promisc_params promisc; /** Restart Autonegotiation command parameters */ struct intelxl_admin_autoneg_params autoneg; /** Get Link Status command parameters */ struct intelxl_admin_link_params link; } __attribute__ (( packed )); /** Admin queue data buffer */ union intelxl_admin_buffer { /** Driver Version data buffer */ struct intelxl_admin_driver_buffer driver; /** Get Switch Configuration data buffer */ struct intelxl_admin_switch_buffer sw; /** Get VSI Parameters data buffer */ struct intelxl_admin_vsi_buffer vsi; /** VF Get Resources data buffer */ struct intelxl_admin_vf_get_resources_buffer res; /** VF Status Change Event data buffer */ struct intelxl_admin_vf_status_buffer stat; /** VF Configure Queues data buffer */ struct intelxl_admin_vf_configure_buffer cfg; /** VF Enable/Disable Queues data buffer */ struct intelxl_admin_vf_queues_buffer queues; /** VF Configure Promiscuous Mode data buffer */ struct intelxl_admin_vf_promisc_buffer promisc; /*** VF IRQ Map data buffer */ struct intelxl_admin_vf_irq_map_buffer irq; /** Alignment padding */ uint8_t pad[INTELXL_ALIGN]; } __attribute__ (( packed )); /** Admin queue descriptor */ struct intelxl_admin_descriptor { /** Flags */ uint16_t flags; /** Opcode */ uint16_t opcode; /** Data length */ uint16_t len; /** Return value */ uint16_t ret; /** Opaque cookie / VF opcode */ union { /** Cookie */ uint32_t cookie; /** VF opcode */ uint32_t vopcode; }; /** VF return value */ int32_t vret; /** Parameters */ union intelxl_admin_params params; } __attribute__ (( packed )); /** Admin descriptor done */ #define INTELXL_ADMIN_FL_DD 0x0001 /** Admin descriptor contains a completion */ #define INTELXL_ADMIN_FL_CMP 0x0002 /** Admin descriptor completed in error */ #define INTELXL_ADMIN_FL_ERR 0x0004 /** Admin descriptor uses data buffer for command parameters */ #define INTELXL_ADMIN_FL_RD 0x0400 /** Admin descriptor uses data buffer */ #define INTELXL_ADMIN_FL_BUF 0x1000 /** Admin queue */ struct intelxl_admin { /** Descriptors */ struct intelxl_admin_descriptor *desc; /** Data buffers */ union intelxl_admin_buffer *buf; /** Queue index */ unsigned int index; /** Register block base */ unsigned int base; /** Register offsets */ const struct intelxl_admin_offsets *regs; }; /** * Initialise admin queue * * @v admin Admin queue * @v base Register block base * @v regs Register offsets */ static inline __attribute__ (( always_inline )) void intelxl_init_admin ( struct intelxl_admin *admin, unsigned int base, const struct intelxl_admin_offsets *regs ) { admin->base = base; admin->regs = regs; } /** Number of admin queue descriptors */ #define INTELXL_ADMIN_NUM_DESC 4 /** Maximum time to wait for an admin request to complete */ #define INTELXL_ADMIN_MAX_WAIT_MS 100 /** Admin queue API major version */ #define INTELXL_ADMIN_API_MAJOR 1 /****************************************************************************** * * Transmit and receive queue context * ****************************************************************************** */ /** CMLAN Context Data Register */ #define INTELXL_PFCM_LANCTXDATA(x) ( 0x10c100 + ( 0x80 * (x) ) ) /** CMLAN Context Control Register */ #define INTELXL_PFCM_LANCTXCTL 0x10c300 #define INTELXL_PFCM_LANCTXCTL_QUEUE_NUM(x) \ ( (x) << 0 ) /**< Queue number */ #define INTELXL_PFCM_LANCTXCTL_SUB_LINE(x) \ ( (x) << 12 ) /**< Sub-line */ #define INTELXL_PFCM_LANCTXCTL_TYPE(x) \ ( (x) << 15 ) /**< Queue type */ #define INTELXL_PFCM_LANCTXCTL_TYPE_RX \ INTELXL_PFCM_LANCTXCTL_TYPE ( 0x0 ) /**< RX queue type */ #define INTELXL_PFCM_LANCTXCTL_TYPE_TX \ INTELXL_PFCM_LANCTXCTL_TYPE ( 0x1 ) /**< TX queue type */ #define INTELXL_PFCM_LANCTXCTL_OP_CODE(x) \ ( (x) << 17 ) /**< Op code */ #define INTELXL_PFCM_LANCTXCTL_OP_CODE_READ \ INTELXL_PFCM_LANCTXCTL_OP_CODE ( 0x0 ) /**< Read context */ #define INTELXL_PFCM_LANCTXCTL_OP_CODE_WRITE \ INTELXL_PFCM_LANCTXCTL_OP_CODE ( 0x1 ) /**< Write context */ /** CMLAN Context Status Register */ #define INTELXL_PFCM_LANCTXSTAT 0x10c380 #define INTELXL_PFCM_LANCTXSTAT_DONE 0x00000001UL /**< Complete */ /** Queue context line */ struct intelxl_context_line { /** Raw data */ uint32_t raw[4]; } __attribute__ (( packed )); /** Transmit queue context */ struct intelxl_context_tx { /** Head pointer */ uint16_t head; /** Flags */ uint16_t flags; /** Base address */ uint64_t base; /** Reserved */ uint8_t reserved_a[8]; /** Queue count */ uint16_t count; /** Reserved */ uint8_t reserved_b[100]; /** Queue set */ uint16_t qset; /** Reserved */ uint8_t reserved_c[4]; } __attribute__ (( packed )); /** New transmit queue context */ #define INTELXL_CTX_TX_FL_NEW 0x4000 /** Transmit queue base address */ #define INTELXL_CTX_TX_BASE( base ) ( (base) >> 7 ) /** Transmit queue count */ #define INTELXL_CTX_TX_COUNT( count ) ( (count) << 1 ) /** Transmit queue set */ #define INTELXL_CTX_TX_QSET( qset) ( (qset) << 4 ) /** Receive queue context */ struct intelxl_context_rx { /** Head pointer */ uint16_t head; /** Reserved */ uint8_t reserved_a[2]; /** Base address and queue count */ uint64_t base_count; /** Data buffer length */ uint16_t len; /** Flags */ uint8_t flags; /** Reserved */ uint8_t reserved_b[7]; /** Maximum frame size */ uint16_t mfs; } __attribute__ (( packed )); /** Receive queue base address and queue count */ #define INTELXL_CTX_RX_BASE_COUNT( base, count ) \ ( ( (base) >> 7 ) | ( ( ( uint64_t ) (count) ) << 57 ) ) /** Receive queue data buffer length */ #define INTELXL_CTX_RX_LEN( len ) ( (len) >> 1 ) /** Use 32-byte receive descriptors */ #define INTELXL_CTX_RX_FL_DSIZE 0x10 /** Strip CRC from received packets */ #define INTELXL_CTX_RX_FL_CRCSTRIP 0x20 /** Receive queue maximum frame size */ #define INTELXL_CTX_RX_MFS( mfs ) ( (mfs) >> 2 ) /** Maximum time to wait for a context operation to complete */ #define INTELXL_CTX_MAX_WAIT_MS 100 /** Time to wait for a queue to become enabled */ #define INTELXL_QUEUE_ENABLE_DELAY_US 20 /** Time to wait for a transmit queue to become pre-disabled */ #define INTELXL_QUEUE_PRE_DISABLE_DELAY_US 400 /** Maximum time to wait for a queue to become disabled */ #define INTELXL_QUEUE_DISABLE_MAX_WAIT_MS 1000 /****************************************************************************** * * Transmit and receive descriptors * ****************************************************************************** */ /** Global Transmit Queue Head register */ #define INTELXL_QTX_HEAD(x) ( 0x0e4000 + ( 0x4 * (x) ) ) /** Global Transmit Pre Queue Disable register */ #define INTELXL_GLLAN_TXPRE_QDIS(x) ( 0x0e6500 + ( 0x4 * ( (x) / 0x80 ) ) ) #define INTELXL_GLLAN_TXPRE_QDIS_QINDX(x) \ ( (x) << 0 ) /**< Queue index */ #define INTELXL_GLLAN_TXPRE_QDIS_SET_QDIS \ 0x40000000UL /**< Set disable */ #define INTELXL_GLLAN_TXPRE_QDIS_CLEAR_QDIS \ 0x80000000UL /**< Clear disable */ /** Global Transmit Queue register block */ #define INTELXL_QTX(x) ( 0x100000 + ( 0x4 * (x) ) ) /** Global Receive Queue register block */ #define INTELXL_QRX(x) ( 0x120000 + ( 0x4 * (x) ) ) /** Queue Enable Register (offset) */ #define INTELXL_QXX_ENA 0x0000 #define INTELXL_QXX_ENA_REQ 0x00000001UL /**< Enable request */ #define INTELXL_QXX_ENA_STAT 0x00000004UL /**< Enabled status */ /** Queue Control Register (offset) */ #define INTELXL_QXX_CTL 0x4000 #define INTELXL_QXX_CTL_PFVF_Q(x) ( (x) << 0 ) /**< PF/VF queue */ #define INTELXL_QXX_CTL_PFVF_Q_PF \ INTELXL_QXX_CTL_PFVF_Q ( 0x2 ) /**< PF queue */ #define INTELXL_QXX_CTL_PFVF_PF_INDX(x) ( (x) << 2 ) /**< PF index */ /** Queue Tail Pointer Register (offset) */ #define INTELXL_QXX_TAIL 0x8000 /** Global RLAN Control 0 register */ #define INTELXL_GLLAN_RCTL_0 0x12a500 #define INTELXL_GLLAN_RCTL_0_PXE_MODE 0x00000001UL /**< PXE mode */ /** Transmit data descriptor */ struct intelxl_tx_data_descriptor { /** Buffer address */ uint64_t address; /** Flags */ uint32_t flags; /** Length */ uint32_t len; } __attribute__ (( packed )); /** Transmit data descriptor type */ #define INTELXL_TX_DATA_DTYP 0x0 /** Transmit data descriptor end of packet */ #define INTELXL_TX_DATA_EOP 0x10 /** Transmit data descriptor report status */ #define INTELXL_TX_DATA_RS 0x20 /** Transmit data descriptor pretty please * * This bit is completely missing from older versions of the XL710 * datasheet. Later versions describe it innocuously as "reserved, * must be 1". Without this bit, everything will appear to work (up * to and including the port "transmit good octets" counter), but no * packet will actually be sent. */ #define INTELXL_TX_DATA_JFDI 0x40 /** Transmit data descriptor length */ #define INTELXL_TX_DATA_LEN( len ) ( (len) << 2 ) /** Transmit writeback descriptor */ struct intelxl_tx_writeback_descriptor { /** Reserved */ uint8_t reserved_a[8]; /** Flags */ uint8_t flags; /** Reserved */ uint8_t reserved_b[7]; } __attribute__ (( packed )); /** Transmit writeback descriptor complete */ #define INTELXL_TX_WB_FL_DD 0x01 /** Transmit descriptor */ union intelxl_tx_descriptor { /** Transmit data descriptor */ struct intelxl_tx_data_descriptor data; /** Transmit writeback descriptor */ struct intelxl_tx_writeback_descriptor wb; }; /** Receive data descriptor */ struct intelxl_rx_data_descriptor { /** Buffer address */ uint64_t address; /** Flags */ uint32_t flags; /** Reserved */ uint8_t reserved[20]; } __attribute__ (( packed )); /** Receive writeback descriptor */ struct intelxl_rx_writeback_descriptor { /** Reserved */ uint8_t reserved_a[2]; /** VLAN tag */ uint16_t vlan; /** Reserved */ uint8_t reserved_b[4]; /** Flags */ uint32_t flags; /** Length */ uint32_t len; /** Reserved */ uint8_t reserved_c[16]; } __attribute__ (( packed )); /** Receive writeback descriptor complete */ #define INTELXL_RX_WB_FL_DD 0x00000001UL /** Receive writeback descriptor VLAN tag present */ #define INTELXL_RX_WB_FL_VLAN 0x00000004UL /** Receive writeback descriptor error */ #define INTELXL_RX_WB_FL_RXE 0x00080000UL /** Receive writeback descriptor length */ #define INTELXL_RX_WB_LEN(len) ( ( (len) >> 6 ) & 0x3fff ) /** Packet descriptor */ union intelxl_rx_descriptor { /** Receive data descriptor */ struct intelxl_rx_data_descriptor data; /** Receive writeback descriptor */ struct intelxl_rx_writeback_descriptor wb; }; /** Descriptor ring */ struct intelxl_ring { /** Descriptors */ union { /** Transmit descriptors */ union intelxl_tx_descriptor *tx; /** Receive descriptors */ union intelxl_rx_descriptor *rx; /** Raw data */ void *raw; } desc; /** Producer index */ unsigned int prod; /** Consumer index */ unsigned int cons; /** Register block */ unsigned int reg; /** Tail register */ unsigned int tail; /** Length (in bytes) */ size_t len; /** Program queue context * * @v intelxl Intel device * @v address Descriptor ring base address */ int ( * context ) ( struct intelxl_nic *intelxl, physaddr_t address ); }; /** * Initialise descriptor ring * * @v ring Descriptor ring * @v count Number of descriptors * @v len Length of a single descriptor * @v context Method to program queue context */ static inline __attribute__ (( always_inline)) void intelxl_init_ring ( struct intelxl_ring *ring, unsigned int count, size_t len, int ( * context ) ( struct intelxl_nic *intelxl, physaddr_t address ) ) { ring->len = ( count * len ); ring->context = context; } /** Number of transmit descriptors * * Chosen to exceed the receive ring fill level, in order to avoid * running out of transmit descriptors when sending TCP ACKs. */ #define INTELXL_TX_NUM_DESC 64 /** Transmit descriptor ring maximum fill level */ #define INTELXL_TX_FILL ( INTELXL_TX_NUM_DESC - 1 ) /** Number of receive descriptors * * Must be a multiple of 32. */ #define INTELXL_RX_NUM_DESC 32 /** Receive descriptor ring fill level * * Must be a multiple of 8 and greater than 8. */ #define INTELXL_RX_FILL 16 /****************************************************************************** * * Top level * ****************************************************************************** */ /** PF Interrupt Zero Dynamic Control Register */ #define INTELXL_PFINT_DYN_CTL0 0x038480 #define INTELXL_INT_DYN_CTL_INTENA 0x00000001UL /**< Enable */ #define INTELXL_INT_DYN_CTL_CLEARPBA 0x00000002UL /**< Acknowledge */ #define INTELXL_INT_DYN_CTL_INTENA_MASK 0x80000000UL /**< Ignore enable */ /** PF Interrupt Zero Linked List Register */ #define INTELXL_PFINT_LNKLST0 0x038500 #define INTELXL_PFINT_LNKLST0_FIRSTQ_INDX(x) \ ( (x) << 0 ) /**< Queue index */ #define INTELXL_PFINT_LNKLST0_FIRSTQ_INDX_NONE \ INTELXL_PFINT_LNKLST0_FIRSTQ_INDX ( 0x7ff ) /**< End of list */ #define INTELXL_PFINT_LNKLST0_FIRSTQ_TYPE(x) \ ( (x) << 11 ) /**< Queue type */ #define INTELXL_PFINT_LNKLST0_FIRSTQ_TYPE_RX \ INTELXL_PFINT_LNKLST0_FIRSTQ_TYPE ( 0x0 ) /**< Receive queue */ #define INTELXL_PFINT_LNKLST0_FIRSTQ_TYPE_TX \ INTELXL_PFINT_LNKLST0_FIRSTQ_TYPE ( 0x1 ) /**< Transmit queue */ /** PF Interrupt Zero Cause Enablement Register */ #define INTELXL_PFINT_ICR0_ENA 0x038800 #define INTELXL_PFINT_ICR0_ENA_ADMINQ 0x40000000UL /**< Admin event */ /** Receive Queue Interrupt Cause Control Register */ #define INTELXL_QINT_RQCTL(x) ( 0x03a000 + ( 0x4 * (x) ) ) #define INTELXL_QINT_RQCTL_NEXTQ_INDX(x) ( (x) << 16 ) /**< Queue index */ #define INTELXL_QINT_RQCTL_NEXTQ_INDX_NONE \ INTELXL_QINT_RQCTL_NEXTQ_INDX ( 0x7ff ) /**< End of list */ #define INTELXL_QINT_RQCTL_NEXTQ_TYPE(x) ( (x) << 27 ) /**< Queue type */ #define INTELXL_QINT_RQCTL_NEXTQ_TYPE_RX \ INTELXL_QINT_RQCTL_NEXTQ_TYPE ( 0x0 ) /**< Receive queue */ #define INTELXL_QINT_RQCTL_NEXTQ_TYPE_TX \ INTELXL_QINT_RQCTL_NEXTQ_TYPE ( 0x1 ) /**< Transmit queue */ #define INTELXL_QINT_RQCTL_CAUSE_ENA 0x40000000UL /**< Enable */ /** Transmit Queue Interrupt Cause Control Register */ #define INTELXL_QINT_TQCTL(x) ( 0x03c000 + ( 0x4 * (x) ) ) #define INTELXL_QINT_TQCTL_NEXTQ_INDX(x) ( (x) << 16 ) /**< Queue index */ #define INTELXL_QINT_TQCTL_NEXTQ_INDX_NONE \ INTELXL_QINT_TQCTL_NEXTQ_INDX ( 0x7ff ) /**< End of list */ #define INTELXL_QINT_TQCTL_NEXTQ_TYPE(x) ( (x) << 27 ) /**< Queue type */ #define INTELXL_QINT_TQCTL_NEXTQ_TYPE_RX \ INTELXL_QINT_TQCTL_NEXTQ_TYPE ( 0x0 ) /**< Receive queue */ #define INTELXL_QINT_TQCTL_NEXTQ_TYPE_TX \ INTELXL_QINT_TQCTL_NEXTQ_TYPE ( 0x1 ) /**< Transmit queue */ #define INTELXL_QINT_TQCTL_CAUSE_ENA 0x40000000UL /**< Enable */ /** PF Control Register */ #define INTELXL_PFGEN_CTRL 0x092400 #define INTELXL_PFGEN_CTRL_PFSWR 0x00000001UL /**< Software Reset */ /** Time to delay for device reset, in milliseconds */ #define INTELXL_RESET_DELAY_MS 100 /** PF Queue Allocation Register */ #define INTELXL_PFLAN_QALLOC 0x1c0400 #define INTELXL_PFLAN_QALLOC_FIRSTQ(x) \ ( ( (x) >> 0 ) & 0x7ff ) /**< First queue */ #define INTELXL_PFLAN_QALLOC_LASTQ(x) \ ( ( (x) >> 16 ) & 0x7ff ) /**< Last queue */ /** PF LAN Port Number Register */ #define INTELXL_PFGEN_PORTNUM 0x1c0480 #define INTELXL_PFGEN_PORTNUM_PORT_NUM(x) \ ( ( (x) >> 0 ) & 0x3 ) /**< Port number */ /** Port MAC Address Low Register */ #define INTELXL_PRTGL_SAL 0x1e2120 /** Port MAC Address High Register */ #define INTELXL_PRTGL_SAH 0x1e2140 #define INTELXL_PRTGL_SAH_MFS_GET(x) ( (x) >> 16 ) /**< Max frame size */ #define INTELXL_PRTGL_SAH_MFS_SET(x) ( (x) << 16 ) /**< Max frame size */ /** Receive address */ union intelxl_receive_address { struct { uint32_t low; uint32_t high; } __attribute__ (( packed )) reg; uint8_t raw[ETH_ALEN]; }; /** An Intel 40Gigabit network card */ struct intelxl_nic { /** Registers */ void *regs; /** Maximum frame size */ size_t mfs; /** Physical function number */ unsigned int pf; /** Absolute queue number base */ unsigned int base; /** Port number */ unsigned int port; /** Queue number */ unsigned int queue; /** Virtual Station Interface switching element ID */ unsigned int vsi; /** Queue set handle */ unsigned int qset; /** Interrupt control register */ unsigned int intr; /** MSI-X capability */ struct pci_msix msix; /** MSI-X dummy interrupt target */ uint32_t msg; /** PCI Express capability offset */ unsigned int exp; /** Admin command queue */ struct intelxl_admin command; /** Admin event queue */ struct intelxl_admin event; /** Current VF opcode */ unsigned int vopcode; /** Current VF return value */ int vret; /** Current VF event data buffer */ union intelxl_admin_buffer vbuf; /** Transmit descriptor ring */ struct intelxl_ring tx; /** Receive descriptor ring */ struct intelxl_ring rx; /** Receive I/O buffers */ struct io_buffer *rx_iobuf[INTELXL_RX_NUM_DESC]; }; extern int intelxl_msix_enable ( struct intelxl_nic *intelxl, struct pci_device *pci ); extern void intelxl_msix_disable ( struct intelxl_nic *intelxl, struct pci_device *pci ); extern struct intelxl_admin_descriptor * intelxl_admin_command_descriptor ( struct intelxl_nic *intelxl ); extern union intelxl_admin_buffer * intelxl_admin_command_buffer ( struct intelxl_nic *intelxl ); extern int intelxl_admin_command ( struct intelxl_nic *intelxl ); extern void intelxl_poll_admin ( struct net_device *netdev ); extern int intelxl_open_admin ( struct intelxl_nic *intelxl ); extern void intelxl_reopen_admin ( struct intelxl_nic *intelxl ); extern void intelxl_close_admin ( struct intelxl_nic *intelxl ); extern int intelxl_alloc_ring ( struct intelxl_nic *intelxl, struct intelxl_ring *ring ); extern void intelxl_free_ring ( struct intelxl_nic *intelxl, struct intelxl_ring *ring ); extern void intelxl_empty_rx ( struct intelxl_nic *intelxl ); extern int intelxl_transmit ( struct net_device *netdev, struct io_buffer *iobuf ); extern void intelxl_poll ( struct net_device *netdev ); extern void intelxlvf_admin_event ( struct net_device *netdev, struct intelxl_admin_descriptor *evt, union intelxl_admin_buffer *buf ); #endif /* _INTELXL_H */
28.127289
79
0.705974
[ "vector" ]
8058bf8edebc0aba631469275a1c24d380c10eba
21,990
c
C
lowapp/lowapp_core/lowapp_msg.c
wyres/lowapp
b466f6dd536394a7ffc9bc01e4ce9e08420be7f0
[ "Apache-2.0" ]
11
2017-01-05T23:29:50.000Z
2019-10-30T19:38:33.000Z
lowapp/lowapp_core/lowapp_msg.c
wyres/lowapp
b466f6dd536394a7ffc9bc01e4ce9e08420be7f0
[ "Apache-2.0" ]
null
null
null
lowapp/lowapp_core/lowapp_msg.c
wyres/lowapp
b466f6dd536394a7ffc9bc01e4ce9e08420be7f0
[ "Apache-2.0" ]
8
2017-01-17T18:36:57.000Z
2020-08-05T03:18:43.000Z
/** * @file lowapp_msg.c * @brief LoWAPP Message and frame related functions * * Defines functions used to build and parse frame from message structures. * * @author Nathan Olff * @date August 22, 2016 */ #include "lowapp_inc.h" #include "lowapp_utils_crc.h" #include "utilities.h" #include <math.h> extern QFIXED_T _rx_pkt_list; extern const uint32_t bandwidthValues[]; /* Static function prototypes */ static void encodeInPlace(uint8_t _appKey[], uint16_t nonce, uint8_t* startEncode, uint16_t sizeToEncode); static void decodeInPlace(uint8_t _appKey[], uint16_t nonce, uint8_t* encBuf, uint16_t sizeToEncode); static uint16_t buildJson(uint8_t **frameBuffer, MSG_RX_APP_T *msg_rx); /** * @name LoWAPP JSON response string literals * @brief Strings used to return received messages to the application * @{ */ /** Source id string for the json field */ const uint8_t jsonSrcId[] = "\"srcId\":"; /** Destination id string for json field */ const uint8_t jsonDestId[] = "\"destId\":"; /** Duplicate flag string for json field */ const uint8_t jsonDuplicate[] = "\"duplicateFrames\":"; /** Missing frame string for json field */ const uint8_t jsonMissingFrame[] = "\"missingFrames\":"; /** RSSI string for json field */ const uint8_t jsonRssi[] = "\"rssi\":"; /** Payload string for json field */ const uint8_t jsonPayload[] = "\"payload\":\""; /** Hex prefix string for json field */ const uint8_t jsonHexPrefix[] = "0x"; /** End of string characters for json field */ const uint8_t jsonEndPayload[] = "\"}"; /** Missing Ack string for json field */ const uint8_t jsonMissingAck[] = "OK TX {\"missingAck\":"; /** Prefix for OK json response */ const uint8_t jsonPrefixOk[] = "OK {\""; /** Prefix for OK TX json response */ const uint8_t jsonPrefixOkTx[] = "OK TX {\""; /** Suffix for json object */ const uint8_t jsonSuffix[] = "\"}"; /** Delimiter for json string field */ const uint8_t jsonKeyValDelimiter[] = "\":\""; /** Delimiter between json elements */ const uint8_t jsonFieldDelimiter[] = "\",\""; /** Prefix for NOK error json */ const uint8_t jsonPrefixError[] = "NOK {\"errno\":\""; /** Delimiter between error code and error string for json */ const uint8_t jsonDelimiterErrorCodeString[] = "\", \"errstr\":\""; /** Invalid configuration error message */ const uint8_t errorMsgMissingConfiguration[] = "\", \"errstr\":\"Missing or incomplete configuration\"}"; /** AT command invalid size error message */ const uint8_t errorMsgAtCmdInvalidSize[] = "AT COMMAND TOO LONG"; /** Prefix for NOK TX retry json */ const uint8_t jsonPrefixNokTxRetry[] = "NOK TX {\"retry\":\""; /** Max retry reached error message */ const uint8_t jsonErrorMaxRetry[] = "NOK TX {\"retry\":\"MAX\"}"; /** TX Faile error message json */ const uint8_t jsonErrorTxFail[] = "NOK TX {\"status\":\"FAILED\"}"; /** NOK TX json response */ const uint8_t jsonNokTx[] = "NOK TX"; /** NOK for RXERROR json response */ const uint8_t jsonNokTxRxError[] = "NOK TX {\"status\":\"RXERROR\"}"; /** NOK for RXTIMEOUT json response */ const uint8_t jsonNokTxRxTimeout[] = "NOK TX {\"status\":\"RXTIMEOUT\"}"; /** Statistics for AT+WHO command prefix for json response */ const uint8_t jsonWhoPrefix[] = "OK {\"wholist\":["; /** Device id for WHO statistics json response */ const uint8_t jsonWhoDevice[] = "{\"deviceId\":"; /** Last RSSI for WHO statistics json response */ const uint8_t jsonWhoLastRssi[] = ",\"lastRssi\":"; /** Last seen time for WHO statistics json response */ const uint8_t jsonWhoLastSeen[] = ",\"lastSeen\":\""; /** Suffix for WHO statistics json response */ const uint8_t jsonWhoSuffix[] = "]}"; /** @} */ /** * Generate a 2-bytes random number for encryption * @return A random number */ uint16_t makeNonce() { return (uint16_t)randr(0, 65535); } /** * @addtogroup lowapp_core LoWAPP Core * @{ */ /** * @addtogroup lowapp_core_messages LoWAPP Core Messages * @brief Message structures and processing functions * @{ */ /** * Encode the message directly inside the buffer * @param _appKey Encryption key * @param randomValueForNonce Nonce used for encryption * @param startEncode Pointer to the start of the buffer to encode * @param sizeToEncode Size of the data to encode */ static void encodeInPlace(uint8_t _appKey[], uint16_t randomValueForNonce, uint8_t* startEncode, uint16_t sizeToEncode) { /* Temporary encryption buffer */ uint8_t encryptedBuffer[256] = {0}; /* Actual key used for AES encryption (currently on 128 bits) */ uint8_t actualKey[ENCKEY_SIZE] = {0}; uint32_t actualNonce; /* Set nonce as concatenation of groupId and randomValue from the frame */ actualNonce = (_groupId << 16) | randomValueForNonce; /* Compute actual key using both _encryptionKey and nonce */ uint8_t i; for(i = 0; i < ENCKEY_SIZE; ++i) { /* XOR between _encryptionKey and the actualNonce variable */ actualKey[i] |= _encryptionKey[i] ^ ((actualNonce >> (4*(i/4))) & 0xFF); } /* Encode into a buffer */ LoRaMacPayloadEncrypt(startEncode, sizeToEncode, _appKey, 0, 0, 0, encryptedBuffer); memcpy(startEncode, encryptedBuffer, sizeToEncode); } /** * Decode the message directly inside the buffer * @param _appKey Encryption key * @param randomValueForNonce Nonce used for encryption * @param encBuf Pointer to the start of the buffer to decode * @param sizeToEncode Size of the data to decode */ static void decodeInPlace(uint8_t _appKey[], uint16_t randomValueForNonce, uint8_t* encBuf, uint16_t sizeToEncode) { uint8_t decBuffer[256] = {0}; /* Actual key used for AES encryption (currently on 128 bits) */ uint8_t actualKey[ENCKEY_SIZE] = {0}; uint32_t actualNonce; /* Set nonce as concatenation of groupId and randomValue from the frame */ actualNonce = (_groupId << 16) | randomValueForNonce; /* Compute actual key using both _encryptionKey and nonce */ uint8_t i; for(i = 0; i < ENCKEY_SIZE; ++i) { /* XOR between a pair of bytes from the 32-bytes _encryptionKey and the actualNonce variable */ actualKey[i] |= _encryptionKey[i] ^ ((actualNonce >> (4*(i/4))) & 0xFF); } /* Decode into a buffer */ LoRaMacPayloadDecrypt(encBuf, sizeToEncode, _appKey, 0, 0, 0, decBuffer); memcpy(encBuf, decBuffer, sizeToEncode); } /** * Get the size of the frame in bytes * @param msg Message to transmit * @return Number of bytes of the frame */ uint8_t frameSize(MSG_T *msg) { uint16_t packetSize; /* Check frame type */ switch(msg->hdr.type) { case TYPE_STDMSG: packetSize = sizeof(LORA_HDR_T) + 2 // Nonce + 3 // Standard type + msg->hdr.payloadLength + 2; // CRC break; case TYPE_ACK: packetSize = sizeof(LORA_HDR_T) + 2 // Nonce + sizeof(ACKMSG_T) + 2; // CRC break; default: packetSize = 0; break; } return packetSize; } /** * Build frame from the message structure * @param[out] frameBuffer Output frame buffer * @param[in] msg Message to transform into frame * @return The total size of the frame */ uint16_t buildFrame(uint8_t *frameBuffer, MSG_T *msg) { uint8_t* ptrBuf; uint16_t packetSize; uint16_t crc; /* Check frame type */ switch(msg->hdr.type) { case TYPE_STDMSG: ptrBuf = frameBuffer; *ptrBuf = (msg->hdr.version << 4) | (msg->hdr.type); ptrBuf++; wrap_byte(&ptrBuf, msg->hdr.payloadLength); wrap_short(&ptrBuf, msg->hdr.rfu); wrap_short(&ptrBuf, makeNonce()); wrap_byte(&ptrBuf, msg->content.std.destId); wrap_byte(&ptrBuf, msg->content.std.srcId); wrap_byte(&ptrBuf, msg->content.std.txSeq); memcpy(ptrBuf, msg->content.std.payload, msg->hdr.payloadLength); ptrBuf += msg->hdr.payloadLength; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverflow" /* Compute CRC on full frame and add it to the end */ crc = PacketComputeCrc(frameBuffer, ptrBuf-frameBuffer, POLYNOMIAL_IBM); #pragma GCC diagnostic pop wrap_short(&ptrBuf, crc); /* Encode */ encodeInPlace(_encryptionKey, *((uint16_t*)(frameBuffer+4)), frameBuffer+6, msg->hdr.payloadLength+8); return ptrBuf-frameBuffer; case TYPE_ACK: packetSize = 0; packetSize += sizeof(LORA_HDR_T); packetSize += 2; // Nonce packetSize += sizeof(ACKMSG_T); packetSize += 2; // CRC ptrBuf = frameBuffer; *ptrBuf = (msg->hdr.version << 4) | (msg->hdr.type); ptrBuf++; wrap_byte(&ptrBuf, msg->hdr.payloadLength); wrap_short(&ptrBuf, msg->hdr.rfu); wrap_short(&ptrBuf, makeNonce()); wrap_byte(&ptrBuf, msg->content.ack.destId); wrap_byte(&ptrBuf, msg->content.ack.srcId); wrap_byte(&ptrBuf, msg->content.ack.rxdSeq); wrap_byte(&ptrBuf, msg->content.ack.expectedSeq); /* Compute CRC on full frame and add it to the end */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverflow" crc = PacketComputeCrc(frameBuffer, ptrBuf-frameBuffer, POLYNOMIAL_IBM); #pragma GCC diagnostic pop LOG(LOG_DBG, "CRC ACK = %u", crc); wrap_short(&ptrBuf, crc); /* Encode */ encodeInPlace(_encryptionKey, *((uint16_t*)(frameBuffer+4)), frameBuffer+6, 6); return ptrBuf-frameBuffer; default: return 0; } } /** * Retrieve a message structure from a frame * @param[out] msg Message to be filled from the buffer * @param[in] frameBuffer Input frame buffer * @retval 0 If the message was filled successfully * @retval -1 If the message type was unknown * @retval -2 If the packet was not destined to me * @retval -3 If the CRC check failed * @retval -4 If the version of the protocol is not the current version */ int8_t retrieveMessage(MSG_T *msg, uint8_t *frameBuffer) { uint8_t* ptrBuf = frameBuffer; uint16_t nonce; uint16_t crcComputed, crcRetrieved; /* Copy header from the frame buffer */ msg->hdr.version = *ptrBuf >> 4; msg->hdr.type = *ptrBuf & 0xF; ptrBuf++; msg->hdr.payloadLength = parse_byte(&ptrBuf); msg->hdr.rfu = parse_short(&ptrBuf); nonce = parse_short(&ptrBuf); /* Check protocol version */ if(msg->hdr.version != LOWAPP_CURRENT_VERSION) { return -4; } /* Check message type from header */ switch(msg->hdr.type) { case TYPE_STDMSG: /* Decode message */ decodeInPlace(_encryptionKey, nonce, ptrBuf, msg->hdr.payloadLength+8); /* Copy message content */ msg->content.std.destId = parse_byte(&ptrBuf); msg->content.std.srcId = parse_byte(&ptrBuf); /* Check CRC */ crcRetrieved = get_short(ptrBuf+1+msg->hdr.payloadLength); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverflow" crcComputed = PacketComputeCrc(frameBuffer, ptrBuf+1+msg->hdr.payloadLength-frameBuffer, POLYNOMIAL_IBM); #pragma GCC diagnostic pop if(crcComputed != crcRetrieved) { /* Wrong AES key assumed */ return -3; } /* Check destination */ if(msg->content.std.destId == _deviceId || msg->content.std.destId == LOWAPP_ID_BROADCAST) { msg->content.std.txSeq = parse_byte(&ptrBuf); memcpy(msg->content.std.payload, ptrBuf, msg->hdr.payloadLength); ptrBuf += msg->hdr.payloadLength; return 0; } else { return -2; } case TYPE_ACK: /* Decode message */ decodeInPlace(_encryptionKey, nonce, ptrBuf, 6); /* Copy message content */ msg->content.ack.destId = parse_byte(&ptrBuf); msg->content.ack.srcId = parse_byte(&ptrBuf); /* Check CRC */ crcRetrieved = get_short(ptrBuf+2); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverflow" crcComputed = PacketComputeCrc(frameBuffer, ptrBuf+2-frameBuffer, POLYNOMIAL_IBM); #pragma GCC diagnostic pop if(crcComputed != crcRetrieved) { /* Wrong AES key assumed */ return -3; } /* Check destination */ if(msg->content.ack.destId == _deviceId) { msg->content.ack.rxdSeq = parse_byte(&ptrBuf); msg->content.ack.expectedSeq = parse_byte(&ptrBuf); return 0; } else { return -2; } default: return -1; } } /** * Build JSON object from the message structure * @param[out] frameBuffer Output JSON buffer * @param[in] msg_rx Message to transform into JSON * @return The total size of the JSON buffer */ static uint16_t buildJson(uint8_t **frameBuffer, MSG_RX_APP_T *msg_rx) { uint8_t* ptrBuf; uint16_t bufferSize; MSG_T *msg = msg_rx->msg; /* Check frame type */ switch(msg->hdr.type) { case TYPE_STDMSG: bufferSize = 2+ +sizeof(jsonSrcId)-1+4 +sizeof(jsonDestId)-1+4 +sizeof(jsonRssi)-1+3 /* Add memory for rssi value (3 characters) */ +sizeof(jsonDuplicate)-1+4 /* Add memory for duplicate even though we might not need it */ +sizeof(jsonMissingFrame)-1+4 /* Add memory for missing frames even though we might not need it */ +sizeof(jsonPayload)-1+msg->hdr.payloadLength+sizeof(jsonEndPayload)-1; *frameBuffer = (uint8_t*) malloc(bufferSize*sizeof(uint8_t)); ptrBuf = *frameBuffer; if(*frameBuffer == NULL) { LOG(LOG_ERR, "Memory allocation error"); return 0; } memset(ptrBuf, 0, bufferSize*sizeof(uint8_t)); *ptrBuf = '{'; ptrBuf++; /* Add source id */ memcpy(ptrBuf, jsonSrcId, sizeof(jsonSrcId)-1); ptrBuf += sizeof(jsonSrcId)-1; ptrBuf += FillBuffer8_t(ptrBuf, 0, &(msg->content.std.srcId), 1, false); *ptrBuf = ','; ptrBuf++; /* Add destination id */ memcpy(ptrBuf, jsonDestId, sizeof(jsonDestId)-1); ptrBuf += sizeof(jsonDestId)-1; ptrBuf += FillBuffer8_t(ptrBuf, 0, &(msg->content.std.destId), 1, false); *ptrBuf = ','; ptrBuf++; /* Add RSSI value */ memcpy(ptrBuf, jsonRssi, sizeof(jsonRssi)-1); ptrBuf += sizeof(jsonRssi)-1; uint8_t rssiReversed = -msg_rx->rssi; ptrBuf += FillBuffer8_t(ptrBuf, 0, &rssiReversed, 1, false); *ptrBuf = ','; ptrBuf++; /* Look for state and add if necessary */ /* Look for duplicate state */ if(msg_rx->state.duplicate_flag) { memcpy(ptrBuf, jsonDuplicate, sizeof(jsonDuplicate)-1); ptrBuf += sizeof(jsonDuplicate)-1; ptrBuf += FillBuffer8_t(ptrBuf, 0, &(msg_rx->state.duplicate_flag), 1, false); *ptrBuf = ','; ptrBuf++; } /* Look for missing frame */ if(msg_rx->state.missing_frames) { memcpy(ptrBuf, jsonMissingFrame, sizeof(jsonMissingFrame)-1); ptrBuf += sizeof(jsonMissingFrame)-1; ptrBuf += FillBuffer8_t(ptrBuf, 0, &(msg_rx->state.missing_frames), 1, false); *ptrBuf = ','; ptrBuf++; } /* Add payload */ memcpy(ptrBuf, jsonPayload, sizeof(jsonPayload)-1); ptrBuf += sizeof(jsonPayload)-1; memcpy(ptrBuf, msg->content.std.payload, msg->hdr.payloadLength); ptrBuf += msg->hdr.payloadLength; memcpy(ptrBuf, jsonEndPayload, sizeof(jsonEndPayload)-1); ptrBuf += sizeof(jsonEndPayload)-1; return ptrBuf-*frameBuffer; } return 0; } /** * Display received packets as JSON * * Returns all received packets since last check as JSON formatted string through SYS_cmdResponse */ void response_rx_packets() { uint8_t* buffer = NULL; uint8_t* totalBuffer = NULL; void* bufMsgRx = NULL; uint16_t length; uint16_t totalLength; #ifdef LOWAPP_MSG_FORMAT_CLASSIC /* Check the rx queue is not empty */ if(queue_size(&_rx_pkt_list) > 0) { totalLength = 14; totalBuffer = (uint8_t*) malloc(sizeof(uint8_t)*totalLength); strncpy((char*)totalBuffer, "OK {\"rxpkts\":[", totalLength); MSG_T* msg; MSG_RX_APP_T *msg_rx_app; while(queue_size(&_rx_pkt_list) > 0) { /* Retrieve element of the RX queue */ get_from_queue(&_rx_pkt_list, &bufMsgRx, &length); msg_rx_app = (MSG_RX_APP_T*) bufMsgRx; msg = msg_rx_app->msg; /* Build JSON object for each message */ length = buildJson(&buffer, msg_rx_app); /* Realloc enough memory to store ]}\0 */ totalBuffer = realloc(totalBuffer, totalLength + length + 3); /* Copy JSON formatted message to the final buffer */ strncpy((char*)(totalBuffer+totalLength), (char*)buffer, length); totalLength += length; /* Add seperator for next message */ strncpy((char*)(totalBuffer+totalLength), ",", 1); totalLength++; /* Free JSON temporary buffer */ free(buffer); buffer = NULL; /* Free MSG retrieved from queue */ free(msg); msg = NULL; free(bufMsgRx); bufMsgRx = NULL; msg = NULL; } totalLength--; /* Remove trailing ',' */ strncpy((char*)(totalBuffer+totalLength), "]}\0", 3); totalLength += 2; _sys->SYS_cmdResponse(totalBuffer, totalLength); /* Free allocation buffer */ free(totalBuffer); totalBuffer = NULL; } else { _sys->SYS_cmdResponse((uint8_t*)"OK {\"rxpkts\":[]}", 16); } #elif (defined(LOWAPP_MSG_FORMAT_GPSAPP) || defined(LOWAPP_MSG_FORMAT_GPSAPP_RSSI)) /* * When using the special GPSAPP format, messages are forwarded to the application * using the following binary format : * B0-B1: 45 02 * B2: Number of GPS elements following * For each received message : * B(2+nx): Device Id of the source device * B(2+nx+1)-B(2+nx+4): GPS latitude * B(2+nx+5)-B(2+nx+8): GPS longitude * Then, again for each received message: * B(2+9n): Length of the message, including length byte and source id byte * B(2+9n+1): deviceId of the source of the message * B(2+9n+2)-BN…: Text message received * Example of received messages : * 4502 * 02 * 03 34352E31 352E3730 * 01 00000001 00000002 * 06 01 41424344 (ABCD) * 07 03 3132333435 (12345) */ uint8_t rxSize = queue_size(&_rx_pkt_list); uint8_t offset = 0; uint8_t offsetTxtMessage = 0; uint8_t i; uint8_t messageLength; totalLength = 3+9*rxSize; totalBuffer = (uint8_t*) malloc(sizeof(uint8_t)*totalLength); /* Set prefix for GPS format response */ *(totalBuffer+(offset++)) = 0x45; *(totalBuffer+(offset++)) = 0x02; *(totalBuffer+(offset++)) = rxSize; /* Offset used to set text messages */ offsetTxtMessage = offset + rxSize*9; MSG_T* msg; MSG_RX_APP_T *msg_rx_app; for(i = 0; i < rxSize; ++i) { /* Retrieve element of the RX queue */ get_from_queue(&_rx_pkt_list, &bufMsgRx, &length); msg_rx_app = (MSG_RX_APP_T*) bufMsgRx; msg = msg_rx_app->msg; /* Check duplicate flag */ // if(msg_rx_app->state.duplicate_flag == 0) { /* Copy text message */ #ifdef LOWAPP_MSG_FORMAT_GPSAPP_RSSI uint8_t bufferRssiString[5] = ","; uint8_t rssiReversed; uint8_t rssiStringLength; rssiReversed = -msg_rx_app->rssi; rssiStringLength = FillBuffer8_t(bufferRssiString, 1, &rssiReversed, 1, false); /* * Actual message length is 8 less than payloadLength * because of the GPS coordinates */ messageLength = msg->hdr.payloadLength-8; /* Realloc enough memory */ totalLength += 2 + messageLength + rssiStringLength; totalBuffer = realloc(totalBuffer, totalLength); /* Copy message source device id to the buffer */ *(totalBuffer+offset+(i*9)) = msg->content.std.srcId; /* Copy GPS coordinates to the buffer */ memcpy((char*)(totalBuffer+offset+(i*9)+1), (char*)msg->content.std.payload, 8); /* Length in the message format includes the length value itself and the source id (+2) */ *(totalBuffer+(offsetTxtMessage++)) = messageLength+2+rssiStringLength; *(totalBuffer+(offsetTxtMessage++)) = msg->content.std.srcId; memcpy((char*)(totalBuffer+offsetTxtMessage), (char*)msg->content.std.payload+8, messageLength); offsetTxtMessage += messageLength; memcpy((char*)(totalBuffer+offsetTxtMessage), bufferRssiString, rssiStringLength); offsetTxtMessage += rssiStringLength; #else /* * Actual message length is 8 less than payloadLength * because of the GPS coordinates */ messageLength = msg->hdr.payloadLength-8; /* Realloc enough memory */ totalLength += 2 + messageLength; totalBuffer = realloc(totalBuffer, totalLength); /* Copy message source device id to the buffer */ *(totalBuffer+offset+(i*9)) = msg->content.std.srcId; /* Copy GPS coordinates to the buffer */ memcpy((char*)(totalBuffer+offset+(i*9)+1), (char*)msg->content.std.payload, 8); /* Length in the message format includes the length value itself and the source id (+2) */ *(totalBuffer+(offsetTxtMessage++)) = messageLength+2; *(totalBuffer+(offsetTxtMessage++)) = msg->content.std.srcId; memcpy((char*)(totalBuffer+offsetTxtMessage), (char*)msg->content.std.payload+8, messageLength); offsetTxtMessage += messageLength; #endif // } /* Free MSG retrieved from queue */ free(msg); msg = NULL; free(bufMsgRx); bufMsgRx = NULL; msg = NULL; } totalBuffer = realloc(totalBuffer, totalLength+2); _sys->SYS_cmdResponse(totalBuffer, totalLength); /* Free allocation buffer */ free(totalBuffer); totalBuffer = NULL; #endif } /** * Get the symbol time for current SF and bandwidth * @return The duration of a single symbol in seconds */ double get_symbol_time() { /* Compute duration of one symbol in seconds */ return ((1 << _rsf)/((double)bandwidthValues[_bandwidth])); } /** * Convert preamble time from us to symbols * @param preambleTime Duration of the preamble in us * @return The number of corresponding symbols */ uint16_t preamble_timeus_to_symbols(uint32_t preambleTime) { uint16_t pLen; /* Get number of symbols for the whole preambleTime */ pLen = floor(preambleTime/get_symbol_time() - 4.25); return pLen; } /** * Convert preamble time from ms to symbols * @param preambleTime Duration of the preamble in ms * @return The number of corresponding symbols */ uint16_t preamble_timems_to_symbols(uint16_t preambleTime) { uint16_t pLen; /* Get number of symbols for the whole preambleTime */ pLen = floor((preambleTime/1000.0)/get_symbol_time() - 4.25); return pLen; } /** * Convert preamble from number of symbols to ms * @param preambleLen Preamble in number of symbols * @return The preamble duration in us */ uint32_t preamble_symbols_to_timeus(uint16_t preambleLen) { double pTime; /* Get number of symbols for the whole preambleTime */ pTime = (preambleLen+4.25)*get_symbol_time(); return floor(pTime * 1e6); } /** * Convert preamble from number of symbols to ms * @param preambleLen Preamble in number of symbols * @return The preamble duration in ms */ uint32_t preamble_symbols_to_timems(uint16_t preambleLen) { double pTime; /* Get number of symbols for the whole preambleTime */ pTime = (preambleLen+4.25)*get_symbol_time(); return floor(pTime * 1e3); } /** @} */ /** @} */
32.968516
121
0.696726
[ "object", "transform" ]
805d46f3b8089d0f4842cdf3e988532d3f190c0d
31,897
c
C
Script/ffmpeg-4.1/libavcodec/atrac9dec.c
wenmobo/WBFFmpeg
28dda64ccbde715b9290684ca5b55300cbf54851
[ "MIT" ]
3
2019-08-08T04:18:38.000Z
2019-08-20T01:41:06.000Z
Script/ffmpeg-4.1/libavcodec/atrac9dec.c
wenmobo/WBFFmpeg
28dda64ccbde715b9290684ca5b55300cbf54851
[ "MIT" ]
null
null
null
Script/ffmpeg-4.1/libavcodec/atrac9dec.c
wenmobo/WBFFmpeg
28dda64ccbde715b9290684ca5b55300cbf54851
[ "MIT" ]
null
null
null
/* * ATRAC9 decoder * Copyright (c) 2018 Rostislav Pehlivanov <atomnuker@gmail.com> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "internal.h" #include "get_bits.h" #include "fft.h" #include "atrac9tab.h" #include "libavutil/lfg.h" #include "libavutil/float_dsp.h" typedef struct ATRAC9ChannelData { int band_ext; int q_unit_cnt; int band_ext_data[4]; int32_t scalefactors[31]; int32_t scalefactors_prev[31]; int precision_coarse[30]; int precision_fine[30]; int precision_mask[30]; int codebookset[30]; int32_t q_coeffs_coarse[256]; int32_t q_coeffs_fine[256]; DECLARE_ALIGNED(32, float, coeffs )[256]; DECLARE_ALIGNED(32, float, prev_win)[128]; } ATRAC9ChannelData; typedef struct ATRAC9BlockData { ATRAC9ChannelData channel[2]; /* Base */ int band_count; int q_unit_cnt; int q_unit_cnt_prev; /* Stereo block only */ int stereo_q_unit; /* Band extension only */ int has_band_ext; int has_band_ext_data; int band_ext_q_unit; /* Gradient */ int grad_mode; int grad_boundary; int gradient[31]; /* Stereo */ int cpe_base_channel; int is_signs[30]; } ATRAC9BlockData; typedef struct ATRAC9Context { AVCodecContext *avctx; AVFloatDSPContext *fdsp; FFTContext imdct; ATRAC9BlockData block[5]; AVLFG lfg; /* Set on init */ int frame_log2; int avg_frame_size; int frame_count; int samplerate_idx; const ATRAC9BlockConfig *block_config; /* Generated on init */ VLC sf_vlc[2][8]; /* Signed/unsigned, length */ VLC coeff_vlc[2][8][4]; /* Cookbook, precision, cookbook index */ uint8_t alloc_curve[48][48]; DECLARE_ALIGNED(32, float, imdct_win)[256]; DECLARE_ALIGNED(32, float, temp)[256]; } ATRAC9Context; static inline int parse_gradient(ATRAC9Context *s, ATRAC9BlockData *b, GetBitContext *gb) { int grad_range[2]; int grad_value[2]; int values, sign, base; uint8_t *curve; float scale; b->grad_mode = get_bits(gb, 2); if (b->grad_mode) { grad_range[0] = get_bits(gb, 5); grad_range[1] = 31; grad_value[0] = get_bits(gb, 5); grad_value[1] = 31; } else { grad_range[0] = get_bits(gb, 6); grad_range[1] = get_bits(gb, 6) + 1; grad_value[0] = get_bits(gb, 5); grad_value[1] = get_bits(gb, 5); } b->grad_boundary = get_bits(gb, 4); if (grad_range[0] >= grad_range[1] || grad_range[1] > 47) return AVERROR_INVALIDDATA; if (grad_value[0] > 31 || grad_value[1] > 31) return AVERROR_INVALIDDATA; if (b->grad_boundary > b->q_unit_cnt) return AVERROR_INVALIDDATA; values = grad_value[1] - grad_value[0]; sign = 1 - 2*(values < 0); base = grad_value[0] + sign; scale = (FFABS(values) - 1) / 31.0f; curve = s->alloc_curve[grad_range[1] - grad_range[0] - 1]; for (int i = 0; i <= b->q_unit_cnt; i++) b->gradient[i] = grad_value[i >= grad_range[0]]; for (int i = grad_range[0]; i < grad_range[1]; i++) b->gradient[i] = base + sign*((int)(scale*curve[i - grad_range[0]])); return 0; } static inline void calc_precision(ATRAC9Context *s, ATRAC9BlockData *b, ATRAC9ChannelData *c) { memset(c->precision_mask, 0, sizeof(c->precision_mask)); for (int i = 1; i < b->q_unit_cnt; i++) { const int delta = FFABS(c->scalefactors[i] - c->scalefactors[i - 1]) - 1; if (delta > 0) { const int neg = c->scalefactors[i - 1] > c->scalefactors[i]; c->precision_mask[i - neg] += FFMIN(delta, 5); } } if (b->grad_mode) { for (int i = 0; i < b->q_unit_cnt; i++) { c->precision_coarse[i] = c->scalefactors[i]; c->precision_coarse[i] += c->precision_mask[i] - b->gradient[i]; if (c->precision_coarse[i] < 0) continue; switch (b->grad_mode) { case 1: c->precision_coarse[i] >>= 1; break; case 2: c->precision_coarse[i] = (3 * c->precision_coarse[i]) >> 3; break; case 3: c->precision_coarse[i] >>= 2; break; } } } else { for (int i = 0; i < b->q_unit_cnt; i++) c->precision_coarse[i] = c->scalefactors[i] - b->gradient[i]; } for (int i = 0; i < b->q_unit_cnt; i++) c->precision_coarse[i] = FFMAX(c->precision_coarse[i], 1); for (int i = 0; i < b->grad_boundary; i++) c->precision_coarse[i]++; for (int i = 0; i < b->q_unit_cnt; i++) { c->precision_fine[i] = 0; if (c->precision_coarse[i] > 15) { c->precision_fine[i] = c->precision_coarse[i] - 15; c->precision_coarse[i] = 15; } } } static inline int parse_band_ext(ATRAC9Context *s, ATRAC9BlockData *b, GetBitContext *gb, int stereo) { int ext_band = 0; if (b->has_band_ext) { ext_band = at9_tab_band_ext_group[b->q_unit_cnt - 13][2]; if (stereo) { b->channel[1].band_ext = get_bits(gb, 2); b->channel[1].band_ext = ext_band > 2 ? b->channel[1].band_ext : 4; } else { skip_bits1(gb); } } b->has_band_ext_data = get_bits1(gb); if (!b->has_band_ext_data) return 0; if (!b->has_band_ext) { skip_bits(gb, 2); skip_bits_long(gb, get_bits(gb, 5)); return 0; } b->channel[0].band_ext = get_bits(gb, 2); b->channel[0].band_ext = ext_band > 2 ? b->channel[0].band_ext : 4; if (!get_bits(gb, 5)) return 0; for (int i = 0; i <= stereo; i++) { ATRAC9ChannelData *c = &b->channel[i]; const int count = at9_tab_band_ext_cnt[c->band_ext][ext_band]; for (int j = 0; j < count; j++) { int len = at9_tab_band_ext_lengths[c->band_ext][ext_band][j]; c->band_ext_data[j] = get_bits(gb, len); } } return 0; } static inline int read_scalefactors(ATRAC9Context *s, ATRAC9BlockData *b, ATRAC9ChannelData *c, GetBitContext *gb, int channel_idx, int first_in_pkt) { static const int mode_map[2][4] = { { 0, 1, 2, 3 }, { 0, 2, 3, 4 } }; const int mode = mode_map[channel_idx][get_bits(gb, 2)]; memset(c->scalefactors, 0, sizeof(c->scalefactors)); if (first_in_pkt && (mode == 4 || ((mode == 3) && !channel_idx))) { av_log(s->avctx, AV_LOG_ERROR, "Invalid scalefactor coding mode!\n"); return AVERROR_INVALIDDATA; } switch (mode) { case 0: { /* VLC delta offset */ const uint8_t *sf_weights = at9_tab_sf_weights[get_bits(gb, 3)]; const int base = get_bits(gb, 5); const int len = get_bits(gb, 2) + 3; const VLC *tab = &s->sf_vlc[0][len]; c->scalefactors[0] = get_bits(gb, len); for (int i = 1; i < b->band_ext_q_unit; i++) { int val = c->scalefactors[i - 1] + get_vlc2(gb, tab->table, 9, 2); c->scalefactors[i] = val & ((1 << len) - 1); } for (int i = 0; i < b->band_ext_q_unit; i++) c->scalefactors[i] += base - sf_weights[i]; break; } case 1: { /* CLC offset */ const int len = get_bits(gb, 2) + 2; const int base = len < 5 ? get_bits(gb, 5) : 0; for (int i = 0; i < b->band_ext_q_unit; i++) c->scalefactors[i] = base + get_bits(gb, len); break; } case 2: case 4: { /* VLC dist to baseline */ const int *baseline = mode == 4 ? c->scalefactors_prev : channel_idx ? b->channel[0].scalefactors : c->scalefactors_prev; const int baseline_len = mode == 4 ? b->q_unit_cnt_prev : channel_idx ? b->band_ext_q_unit : b->q_unit_cnt_prev; const int len = get_bits(gb, 2) + 2; const int unit_cnt = FFMIN(b->band_ext_q_unit, baseline_len); const VLC *tab = &s->sf_vlc[1][len]; for (int i = 0; i < unit_cnt; i++) { int dist = get_vlc2(gb, tab->table, 9, 2); c->scalefactors[i] = baseline[i] + dist; } for (int i = unit_cnt; i < b->band_ext_q_unit; i++) c->scalefactors[i] = get_bits(gb, 5); break; } case 3: { /* VLC offset with baseline */ const int *baseline = channel_idx ? b->channel[0].scalefactors : c->scalefactors_prev; const int baseline_len = channel_idx ? b->band_ext_q_unit : b->q_unit_cnt_prev; const int base = get_bits(gb, 5) - (1 << (5 - 1)); const int len = get_bits(gb, 2) + 1; const int unit_cnt = FFMIN(b->band_ext_q_unit, baseline_len); const VLC *tab = &s->sf_vlc[0][len]; c->scalefactors[0] = get_bits(gb, len); for (int i = 1; i < unit_cnt; i++) { int val = c->scalefactors[i - 1] + get_vlc2(gb, tab->table, 9, 2); c->scalefactors[i] = val & ((1 << len) - 1); } for (int i = 0; i < unit_cnt; i++) c->scalefactors[i] += base + baseline[i]; for (int i = unit_cnt; i < b->band_ext_q_unit; i++) c->scalefactors[i] = get_bits(gb, 5); break; } } for (int i = 0; i < b->band_ext_q_unit; i++) if (c->scalefactors[i] < 0 || c->scalefactors[i] > 31) return AVERROR_INVALIDDATA; memcpy(c->scalefactors_prev, c->scalefactors, sizeof(c->scalefactors)); return 0; } static inline void calc_codebook_idx(ATRAC9Context *s, ATRAC9BlockData *b, ATRAC9ChannelData *c) { int avg = 0; const int last_sf = c->scalefactors[c->q_unit_cnt]; memset(c->codebookset, 0, sizeof(c->codebookset)); if (c->q_unit_cnt <= 1) return; if (s->samplerate_idx > 7) return; c->scalefactors[c->q_unit_cnt] = c->scalefactors[c->q_unit_cnt - 1]; if (c->q_unit_cnt > 12) { for (int i = 0; i < 12; i++) avg += c->scalefactors[i]; avg = (avg + 6) / 12; } for (int i = 8; i < c->q_unit_cnt; i++) { const int prev = c->scalefactors[i - 1]; const int cur = c->scalefactors[i ]; const int next = c->scalefactors[i + 1]; const int min = FFMIN(prev, next); if ((cur - min >= 3 || 2*cur - prev - next >= 3)) c->codebookset[i] = 1; } for (int i = 12; i < c->q_unit_cnt; i++) { const int cur = c->scalefactors[i]; const int cnd = at9_q_unit_to_coeff_cnt[i] == 16; const int min = FFMIN(c->scalefactors[i + 1], c->scalefactors[i - 1]); if (c->codebookset[i]) continue; c->codebookset[i] = (((cur - min) >= 2) && (cur >= (avg - cnd))); } c->scalefactors[c->q_unit_cnt] = last_sf; } static inline void read_coeffs_coarse(ATRAC9Context *s, ATRAC9BlockData *b, ATRAC9ChannelData *c, GetBitContext *gb) { const int max_prec = s->samplerate_idx > 7 ? 1 : 7; memset(c->q_coeffs_coarse, 0, sizeof(c->q_coeffs_coarse)); for (int i = 0; i < c->q_unit_cnt; i++) { int *coeffs = &c->q_coeffs_coarse[at9_q_unit_to_coeff_idx[i]]; const int bands = at9_q_unit_to_coeff_cnt[i]; const int prec = c->precision_coarse[i] + 1; if (prec <= max_prec) { const int cb = c->codebookset[i]; const int cbi = at9_q_unit_to_codebookidx[i]; const VLC *tab = &s->coeff_vlc[cb][prec][cbi]; const HuffmanCodebook *huff = &at9_huffman_coeffs[cb][prec][cbi]; const int groups = bands >> huff->value_cnt_pow; for (int j = 0; j < groups; j++) { uint16_t val = get_vlc2(gb, tab->table, 9, huff->max_bit_size); for (int k = 0; k < huff->value_cnt; k++) { coeffs[k] = sign_extend(val, huff->value_bits); val >>= huff->value_bits; } coeffs += huff->value_cnt; } } else { for (int j = 0; j < bands; j++) coeffs[j] = sign_extend(get_bits(gb, prec), prec); } } } static inline void read_coeffs_fine(ATRAC9Context *s, ATRAC9BlockData *b, ATRAC9ChannelData *c, GetBitContext *gb) { memset(c->q_coeffs_fine, 0, sizeof(c->q_coeffs_fine)); for (int i = 0; i < c->q_unit_cnt; i++) { const int start = at9_q_unit_to_coeff_idx[i + 0]; const int end = at9_q_unit_to_coeff_idx[i + 1]; const int len = c->precision_fine[i] + 1; if (c->precision_fine[i] <= 0) continue; for (int j = start; j < end; j++) c->q_coeffs_fine[j] = sign_extend(get_bits(gb, len), len); } } static inline void dequantize(ATRAC9Context *s, ATRAC9BlockData *b, ATRAC9ChannelData *c) { memset(c->coeffs, 0, sizeof(c->coeffs)); for (int i = 0; i < c->q_unit_cnt; i++) { const int start = at9_q_unit_to_coeff_idx[i + 0]; const int end = at9_q_unit_to_coeff_idx[i + 1]; const float coarse_c = at9_quant_step_coarse[c->precision_coarse[i]]; const float fine_c = at9_quant_step_fine[c->precision_fine[i]]; for (int j = start; j < end; j++) { const float vc = c->q_coeffs_coarse[j] * coarse_c; const float vf = c->q_coeffs_fine[j] * fine_c; c->coeffs[j] = vc + vf; } } } static inline void apply_intensity_stereo(ATRAC9Context *s, ATRAC9BlockData *b, const int stereo) { float *src = b->channel[ b->cpe_base_channel].coeffs; float *dst = b->channel[!b->cpe_base_channel].coeffs; if (!stereo) return; if (b->q_unit_cnt <= b->stereo_q_unit) return; for (int i = b->stereo_q_unit; i < b->q_unit_cnt; i++) { const int sign = b->is_signs[i]; const int start = at9_q_unit_to_coeff_idx[i + 0]; const int end = at9_q_unit_to_coeff_idx[i + 1]; for (int j = start; j < end; j++) dst[j] = sign*src[j]; } } static inline void apply_scalefactors(ATRAC9Context *s, ATRAC9BlockData *b, const int stereo) { for (int i = 0; i <= stereo; i++) { float *coeffs = b->channel[i].coeffs; for (int j = 0; j < b->q_unit_cnt; j++) { const int start = at9_q_unit_to_coeff_idx[j + 0]; const int end = at9_q_unit_to_coeff_idx[j + 1]; const int scalefactor = b->channel[i].scalefactors[j]; const float scale = at9_scalefactor_c[scalefactor]; for (int k = start; k < end; k++) coeffs[k] *= scale; } } } static inline void fill_with_noise(ATRAC9Context *s, ATRAC9ChannelData *c, int start, int count) { float maxval = 0.0f; for (int i = 0; i < count; i += 2) { double tmp[2]; av_bmg_get(&s->lfg, tmp); c->coeffs[start + i + 0] = tmp[0]; c->coeffs[start + i + 1] = tmp[1]; maxval = FFMAX(FFMAX(FFABS(tmp[0]), FFABS(tmp[1])), maxval); } /* Normalize */ for (int i = 0; i < count; i++) c->coeffs[start + i] /= maxval; } static inline void scale_band_ext_coeffs(ATRAC9ChannelData *c, float sf[6], const int s_unit, const int e_unit) { for (int i = s_unit; i < e_unit; i++) { const int start = at9_q_unit_to_coeff_idx[i + 0]; const int end = at9_q_unit_to_coeff_idx[i + 1]; for (int j = start; j < end; j++) c->coeffs[j] *= sf[i - s_unit]; } } static inline void apply_band_extension(ATRAC9Context *s, ATRAC9BlockData *b, const int stereo) { const int g_units[4] = { /* A, B, C, total units */ b->q_unit_cnt, at9_tab_band_ext_group[b->q_unit_cnt - 13][0], at9_tab_band_ext_group[b->q_unit_cnt - 13][1], FFMAX(g_units[2], 22), }; const int g_bins[4] = { /* A, B, C, total bins */ at9_q_unit_to_coeff_idx[g_units[0]], at9_q_unit_to_coeff_idx[g_units[1]], at9_q_unit_to_coeff_idx[g_units[2]], at9_q_unit_to_coeff_idx[g_units[3]], }; if (!b->has_band_ext || !b->has_band_ext_data) return; for (int ch = 0; ch <= stereo; ch++) { ATRAC9ChannelData *c = &b->channel[ch]; /* Mirror the spectrum */ for (int i = 0; i < 3; i++) for (int j = 0; j < (g_bins[i + 1] - g_bins[i + 0]); j++) c->coeffs[g_bins[i] + j] = c->coeffs[g_bins[i] - j - 1]; switch (c->band_ext) { case 0: { float sf[6] = { 0.0f }; const int l = g_units[3] - g_units[0] - 1; const int n_start = at9_q_unit_to_coeff_idx[g_units[3] - 1]; const int n_cnt = at9_q_unit_to_coeff_cnt[g_units[3] - 1]; switch (at9_tab_band_ext_group[b->q_unit_cnt - 13][2]) { case 3: sf[0] = at9_band_ext_scales_m0[0][0][c->band_ext_data[0]]; sf[1] = at9_band_ext_scales_m0[0][1][c->band_ext_data[0]]; sf[2] = at9_band_ext_scales_m0[0][2][c->band_ext_data[1]]; sf[3] = at9_band_ext_scales_m0[0][3][c->band_ext_data[2]]; sf[4] = at9_band_ext_scales_m0[0][4][c->band_ext_data[3]]; break; case 4: sf[0] = at9_band_ext_scales_m0[1][0][c->band_ext_data[0]]; sf[1] = at9_band_ext_scales_m0[1][1][c->band_ext_data[0]]; sf[2] = at9_band_ext_scales_m0[1][2][c->band_ext_data[1]]; sf[3] = at9_band_ext_scales_m0[1][3][c->band_ext_data[2]]; sf[4] = at9_band_ext_scales_m0[1][4][c->band_ext_data[3]]; break; case 5: sf[0] = at9_band_ext_scales_m0[2][0][c->band_ext_data[0]]; sf[1] = at9_band_ext_scales_m0[2][1][c->band_ext_data[1]]; sf[2] = at9_band_ext_scales_m0[2][2][c->band_ext_data[1]]; break; } sf[l] = at9_scalefactor_c[c->scalefactors[g_units[0]]]; fill_with_noise(s, c, n_start, n_cnt); scale_band_ext_coeffs(c, sf, g_units[0], g_units[3]); break; } case 1: { float sf[6]; for (int i = g_units[0]; i < g_units[3]; i++) sf[i - g_units[0]] = at9_scalefactor_c[c->scalefactors[i]]; fill_with_noise(s, c, g_bins[0], g_bins[3] - g_bins[0]); scale_band_ext_coeffs(c, sf, g_units[0], g_units[3]); break; } case 2: { const float g_sf[2] = { at9_band_ext_scales_m2[c->band_ext_data[0]], at9_band_ext_scales_m2[c->band_ext_data[1]], }; for (int i = 0; i < 2; i++) for (int j = g_bins[i + 0]; j < g_bins[i + 1]; j++) c->coeffs[j] *= g_sf[i]; break; } case 3: { float scale = at9_band_ext_scales_m3[c->band_ext_data[0]][0]; float rate = at9_band_ext_scales_m3[c->band_ext_data[1]][1]; rate = pow(2, rate); for (int i = g_bins[0]; i < g_bins[3]; i++) { scale *= rate; c->coeffs[i] *= scale; } break; } case 4: { const float m = at9_band_ext_scales_m4[c->band_ext_data[0]]; const float g_sf[3] = { 0.7079468f*m, 0.5011902f*m, 0.3548279f*m }; for (int i = 0; i < 3; i++) for (int j = g_bins[i + 0]; j < g_bins[i + 1]; j++) c->coeffs[j] *= g_sf[i]; break; } } } } static int atrac9_decode_block(ATRAC9Context *s, GetBitContext *gb, ATRAC9BlockData *b, AVFrame *frame, int frame_idx, int block_idx) { const int first_in_pkt = !get_bits1(gb); const int reuse_params = get_bits1(gb); const int stereo = s->block_config->type[block_idx] == ATRAC9_BLOCK_TYPE_CPE; if (s->block_config->type[block_idx] == ATRAC9_BLOCK_TYPE_LFE) { ATRAC9ChannelData *c = &b->channel[0]; const int precision = reuse_params ? 8 : 4; c->q_unit_cnt = b->q_unit_cnt = 2; memset(c->scalefactors, 0, sizeof(c->scalefactors)); memset(c->q_coeffs_fine, 0, sizeof(c->q_coeffs_fine)); memset(c->q_coeffs_coarse, 0, sizeof(c->q_coeffs_coarse)); for (int i = 0; i < b->q_unit_cnt; i++) { c->scalefactors[i] = get_bits(gb, 5); c->precision_coarse[i] = precision; c->precision_fine[i] = 0; } for (int i = 0; i < c->q_unit_cnt; i++) { const int start = at9_q_unit_to_coeff_idx[i + 0]; const int end = at9_q_unit_to_coeff_idx[i + 1]; for (int j = start; j < end; j++) c->q_coeffs_coarse[j] = get_bits(gb, c->precision_coarse[i] + 1); } dequantize (s, b, c); apply_scalefactors(s, b, 0); goto imdct; } if (first_in_pkt && reuse_params) { av_log(s->avctx, AV_LOG_ERROR, "Invalid block flags!\n"); return AVERROR_INVALIDDATA; } /* Band parameters */ if (!reuse_params) { int stereo_band, ext_band; const int min_band_count = s->samplerate_idx > 7 ? 1 : 3; b->band_count = get_bits(gb, 4) + min_band_count; b->q_unit_cnt = at9_tab_band_q_unit_map[b->band_count]; b->band_ext_q_unit = b->stereo_q_unit = b->q_unit_cnt; if (b->band_count > at9_tab_sri_max_bands[s->samplerate_idx]) { av_log(s->avctx, AV_LOG_ERROR, "Invalid band count %i!\n", b->band_count); return AVERROR_INVALIDDATA; } if (stereo) { stereo_band = get_bits(gb, 4) + min_band_count; if (stereo_band > b->band_count) { av_log(s->avctx, AV_LOG_ERROR, "Invalid stereo band %i!\n", stereo_band); return AVERROR_INVALIDDATA; } b->stereo_q_unit = at9_tab_band_q_unit_map[stereo_band]; } b->has_band_ext = get_bits1(gb); if (b->has_band_ext) { ext_band = get_bits(gb, 4) + min_band_count; if (ext_band < b->band_count) { av_log(s->avctx, AV_LOG_ERROR, "Invalid extension band %i!\n", ext_band); return AVERROR_INVALIDDATA; } b->band_ext_q_unit = at9_tab_band_q_unit_map[ext_band]; } } /* Calculate bit alloc gradient */ if (parse_gradient(s, b, gb)) return AVERROR_INVALIDDATA; /* IS data */ b->cpe_base_channel = 0; if (stereo) { b->cpe_base_channel = get_bits1(gb); if (get_bits1(gb)) { for (int i = b->stereo_q_unit; i < b->q_unit_cnt; i++) b->is_signs[i] = 1 - 2*get_bits1(gb); } else { for (int i = 0; i < FF_ARRAY_ELEMS(b->is_signs); i++) b->is_signs[i] = 1; } } /* Band extension */ if (parse_band_ext(s, b, gb, stereo)) return AVERROR_INVALIDDATA; /* Scalefactors */ for (int i = 0; i <= stereo; i++) { ATRAC9ChannelData *c = &b->channel[i]; c->q_unit_cnt = i == b->cpe_base_channel ? b->q_unit_cnt : b->stereo_q_unit; if (read_scalefactors(s, b, c, gb, i, first_in_pkt)) return AVERROR_INVALIDDATA; calc_precision (s, b, c); calc_codebook_idx (s, b, c); read_coeffs_coarse(s, b, c, gb); read_coeffs_fine (s, b, c, gb); dequantize (s, b, c); } b->q_unit_cnt_prev = b->has_band_ext ? b->band_ext_q_unit : b->q_unit_cnt; apply_intensity_stereo(s, b, stereo); apply_scalefactors (s, b, stereo); apply_band_extension (s, b, stereo); imdct: for (int i = 0; i <= stereo; i++) { ATRAC9ChannelData *c = &b->channel[i]; const int dst_idx = s->block_config->plane_map[block_idx][i]; const int wsize = 1 << s->frame_log2; const ptrdiff_t offset = wsize*frame_idx*sizeof(float); float *dst = (float *)(frame->extended_data[dst_idx] + offset); s->imdct.imdct_half(&s->imdct, s->temp, c->coeffs); s->fdsp->vector_fmul_window(dst, c->prev_win, s->temp, s->imdct_win, wsize >> 1); memcpy(c->prev_win, s->temp + (wsize >> 1), sizeof(float)*wsize >> 1); } return 0; } static int atrac9_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { int ret; GetBitContext gb; AVFrame *frame = data; ATRAC9Context *s = avctx->priv_data; const int frames = FFMIN(avpkt->size / s->avg_frame_size, s->frame_count); frame->nb_samples = (1 << s->frame_log2) * frames; ret = ff_get_buffer(avctx, frame, 0); if (ret < 0) return ret; init_get_bits8(&gb, avpkt->data, avpkt->size); for (int i = 0; i < frames; i++) { for (int j = 0; j < s->block_config->count; j++) { ret = atrac9_decode_block(s, &gb, &s->block[j], frame, i, j); if (ret) return ret; align_get_bits(&gb); } } *got_frame_ptr = 1; return avctx->block_align; } static void atrac9_decode_flush(AVCodecContext *avctx) { ATRAC9Context *s = avctx->priv_data; for (int j = 0; j < s->block_config->count; j++) { ATRAC9BlockData *b = &s->block[j]; const int stereo = s->block_config->type[j] == ATRAC9_BLOCK_TYPE_CPE; for (int i = 0; i <= stereo; i++) { ATRAC9ChannelData *c = &b->channel[i]; memset(c->prev_win, 0, sizeof(c->prev_win)); } } } static av_cold int atrac9_decode_close(AVCodecContext *avctx) { ATRAC9Context *s = avctx->priv_data; for (int i = 1; i < 7; i++) ff_free_vlc(&s->sf_vlc[0][i]); for (int i = 2; i < 6; i++) ff_free_vlc(&s->sf_vlc[1][i]); for (int i = 0; i < 2; i++) for (int j = 0; j < 8; j++) for (int k = 0; k < 4; k++) ff_free_vlc(&s->coeff_vlc[i][j][k]); ff_mdct_end(&s->imdct); av_free(s->fdsp); return 0; } static av_cold int atrac9_decode_init(AVCodecContext *avctx) { GetBitContext gb; ATRAC9Context *s = avctx->priv_data; int version, block_config_idx, superframe_idx, alloc_c_len; s->avctx = avctx; av_lfg_init(&s->lfg, 0xFBADF00D); if (avctx->extradata_size != 12) { av_log(avctx, AV_LOG_ERROR, "Invalid extradata length!\n"); return AVERROR_INVALIDDATA; } version = AV_RL32(avctx->extradata); if (version > 2) { av_log(avctx, AV_LOG_ERROR, "Unsupported version (%i)!\n", version); return AVERROR_INVALIDDATA; } init_get_bits8(&gb, avctx->extradata + 4, avctx->extradata_size); if (get_bits(&gb, 8) != 0xFE) { av_log(avctx, AV_LOG_ERROR, "Incorrect magic byte!\n"); return AVERROR_INVALIDDATA; } s->samplerate_idx = get_bits(&gb, 4); avctx->sample_rate = at9_tab_samplerates[s->samplerate_idx]; block_config_idx = get_bits(&gb, 3); if (block_config_idx > 5) { av_log(avctx, AV_LOG_ERROR, "Incorrect block config!\n"); return AVERROR_INVALIDDATA; } s->block_config = &at9_block_layout[block_config_idx]; avctx->channel_layout = s->block_config->channel_layout; avctx->sample_fmt = AV_SAMPLE_FMT_FLTP; if (get_bits1(&gb)) { av_log(avctx, AV_LOG_ERROR, "Incorrect verification bit!\n"); return AVERROR_INVALIDDATA; } /* Average frame size in bytes */ s->avg_frame_size = get_bits(&gb, 11) + 1; superframe_idx = get_bits(&gb, 2); if (superframe_idx & 1) { av_log(avctx, AV_LOG_ERROR, "Invalid superframe index!\n"); return AVERROR_INVALIDDATA; } s->frame_count = 1 << superframe_idx; s->frame_log2 = at9_tab_sri_frame_log2[s->samplerate_idx]; if (ff_mdct_init(&s->imdct, s->frame_log2 + 1, 1, 1.0f / 32768.0f)) return AVERROR(ENOMEM); s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT); if (!s->fdsp) return AVERROR(ENOMEM); /* iMDCT window */ for (int i = 0; i < (1 << s->frame_log2); i++) { const int len = 1 << s->frame_log2; const float sidx = ( i + 0.5f) / len; const float eidx = (len - i - 0.5f) / len; const float s_c = sinf(sidx*M_PI - M_PI_2)*0.5f + 0.5f; const float e_c = sinf(eidx*M_PI - M_PI_2)*0.5f + 0.5f; s->imdct_win[i] = s_c / ((s_c * s_c) + (e_c * e_c)); } /* Allocation curve */ alloc_c_len = FF_ARRAY_ELEMS(at9_tab_b_dist); for (int i = 1; i <= alloc_c_len; i++) for (int j = 0; j < i; j++) s->alloc_curve[i - 1][j] = at9_tab_b_dist[(j * alloc_c_len) / i]; /* Unsigned scalefactor VLCs */ for (int i = 1; i < 7; i++) { const HuffmanCodebook *hf = &at9_huffman_sf_unsigned[i]; init_vlc(&s->sf_vlc[0][i], 9, hf->size, hf->bits, 1, 1, hf->codes, 2, 2, 0); } /* Signed scalefactor VLCs */ for (int i = 2; i < 6; i++) { const HuffmanCodebook *hf = &at9_huffman_sf_signed[i]; int nums = hf->size; int16_t sym[32]; for (int j = 0; j < nums; j++) sym[j] = sign_extend(j, hf->value_bits); ff_init_vlc_sparse(&s->sf_vlc[1][i], 9, hf->size, hf->bits, 1, 1, hf->codes, 2, 2, sym, sizeof(*sym), sizeof(*sym), 0); } /* Coefficient VLCs */ for (int i = 0; i < 2; i++) { for (int j = 0; j < 8; j++) { for (int k = 0; k < 4; k++) { const HuffmanCodebook *hf = &at9_huffman_coeffs[i][j][k]; init_vlc(&s->coeff_vlc[i][j][k], 9, hf->size, hf->bits, 1, 1, hf->codes, 2, 2, 0); } } } return 0; } AVCodec ff_atrac9_decoder = { .name = "atrac9", .long_name = NULL_IF_CONFIG_SMALL("ATRAC9 (Adaptive TRansform Acoustic Coding 9)"), .type = AVMEDIA_TYPE_AUDIO, .id = AV_CODEC_ID_ATRAC9, .priv_data_size = sizeof(ATRAC9Context), .init = atrac9_decode_init, .close = atrac9_decode_close, .decode = atrac9_decode_frame, .flush = atrac9_decode_flush, .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP, .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1, };
33.4
92
0.545161
[ "transform" ]
8061c0b7997183b4cae05d68f932f1ad0a11123e
1,164
h
C
src/search/successor_generator.h
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
4
2019-04-23T10:41:35.000Z
2019-10-27T05:14:42.000Z
src/search/successor_generator.h
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
null
null
null
src/search/successor_generator.h
nitinkaveriappa/downward
5c9a1b5111d667bb96f94da61ca2a45b1b70bb83
[ "MIT" ]
4
2018-01-16T00:00:22.000Z
2019-11-01T23:35:01.000Z
#ifndef SUCCESSOR_GENERATOR_H #define SUCCESSOR_GENERATOR_H #include "task_proxy.h" #include <list> #include <memory> #include <vector> class AbstractTask; class GeneratorBase; class GlobalOperator; class GlobalState; class OperatorProxy; class State; class SuccessorGenerator { const std::shared_ptr<AbstractTask> task; TaskProxy task_proxy; std::unique_ptr<GeneratorBase> root; typedef std::vector<FactProxy> Condition; GeneratorBase *construct_recursive( int switch_var_id, std::list<OperatorProxy> &operator_queue); std::vector<Condition> conditions; std::vector<Condition::const_iterator> next_condition_by_op; SuccessorGenerator(const SuccessorGenerator &) = delete; public: SuccessorGenerator(const std::shared_ptr<AbstractTask> task); ~SuccessorGenerator(); void generate_applicable_ops( const State &state, std::vector<OperatorProxy> &applicable_ops) const; // Transitional method, used until the search is switched to the new task interface. void generate_applicable_ops( const GlobalState &state, std::vector<const GlobalOperator *> &applicable_ops) const; }; #endif
27.069767
93
0.757732
[ "vector" ]
80626379bb38aa486824231c2c92cb47a01fee6e
384
h
C
Userland/Libraries/LibCore/DeferredInvocationContext.h
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
2
2022-02-16T02:12:38.000Z
2022-02-20T18:40:41.000Z
Userland/Libraries/LibCore/DeferredInvocationContext.h
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibCore/DeferredInvocationContext.h
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2018-2020, sin-ack <sin-ack@protonmail.com> * Copyright (c) 2022, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibCore/Object.h> namespace Core { class DeferredInvocationContext final : public Core::Object { C_OBJECT(DeferredInvocationContext) private: DeferredInvocationContext() = default; }; }
18.285714
61
0.723958
[ "object" ]
45f0e5f5112328c7fc353150003149862706d177
11,572
h
C
middleware/legato/library/src/gfx/legato/common/legato_common.h
automaate/gfx3.8
55bf94302f00c8d513c84d910185cef2ca6b5be2
[ "0BSD" ]
4
2021-07-23T18:37:34.000Z
2022-01-09T17:31:40.000Z
middleware/legato/library/src/gfx/legato/common/legato_common.h
automaate/gfx3.8
55bf94302f00c8d513c84d910185cef2ca6b5be2
[ "0BSD" ]
1
2020-12-31T22:40:10.000Z
2020-12-31T22:40:10.000Z
middleware/legato/library/src/gfx/legato/common/legato_common.h
automaate/gfx3.8
55bf94302f00c8d513c84d910185cef2ca6b5be2
[ "0BSD" ]
3
2021-01-20T19:16:00.000Z
2021-07-27T08:06:14.000Z
/******************************************************************************* * Copyright (C) 2020 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *******************************************************************************/ /******************************************************************************* Module for Microchip Graphics Library - Legato User Interface Library Company: Microchip Technology Inc. File Name: legato_common.h Summary: This file defines the common macros and definitions used by the gfx definition and implementation headers. Description: This file defines the common macros and definitions used by the gfx definition and the implementation header. Remarks: The directory in which this file resides should be added to the compiler's search path for header files. *******************************************************************************/ /** \file legato_common.h * @brief Common macros and definitions used by Legato. * * @details This file defines the common macros and definitions used * by the legato library definition and implementation files. * * @remark The directory in which this file resides should be added to the * compiler's search path for header files. */ #ifndef LEGATO_COMMON_H #define LEGATO_COMMON_H #include "gfx/legato/legato_config.h" #include <stddef.h> #include <assert.h> #include <string.h> #ifdef _WIN32 #ifndef int8_t typedef signed __int8 int8_t; typedef signed __int16 int16_t; typedef signed __int32 int32_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #endif #else #include <stdint.h> #endif #ifndef WIN32 //#include "osal/osal.h" FIXME for H3 #endif /** * @brief Defines the default color of mode for all schemes. * @details In Legato there is a need to identify the default * color mode for schemes. */ #ifndef LE_DEFAULT_SCHEME_COLOR_MODE #define LE_DEFAULT_SCHEME_COLOR_MODE LE_COLOR_MODE_RGB_565 #endif #ifdef __cplusplus extern "C" { #endif // ***************************************************************************** // ***************************************************************************** // Section: Data Types and Constants // ***************************************************************************** // ***************************************************************************** // ***************************************************************************** /* Enumeration: leResult Summary: legato results (success and failure codes). Description: Various definitions for success and failure codes. Remarks: None. */ /** * @brief This enum represents function call results. * @details Results are used to report success and failure conditions. These * are the various success and failure codes. */ typedef enum leResult { LE_FAILURE = -1, LE_SUCCESS = 0 } leResult; // ***************************************************************************** /* Enumeration: leBool Summary: legato bool values Description: legato bool values Remarks: None. */ /** * @brief This enum represents booleans. * @details Boolean are used to communicate true and false conditions. */ typedef enum leBool { LE_FALSE = 0, /**< Logic false =0. */ LE_TRUE /**< Logic true = 1. */ } leBool; // ***************************************************************************** /* Enumeration: leVAlignment Summary: legato vertical alignment values Description: legato vertical alignment values Remarks: None. */ /** * @brief This enum represents the vertical alignment mode of objects. * @details The vertical alignment mode controls how objects are positioned * vertically. */ typedef enum { LE_VALIGN_TOP, /**< Aligns with the top. */ LE_VALIGN_MIDDLE, /**< Aligns with the middle. */ LE_VALIGN_BOTTOM /**< Aligns with the bottom. */ } leVAlignment; // ***************************************************************************** /* Enumeration: leHAlignment Summary: legato horizontal alignment values Description: legato horizontal alignment values Remarks: None. */ /** * @brief This enum represents the horizontal alignment mode of objects. * @details The horizontal alignment mode controls how objects are positioned * horizontally. */ typedef enum { LE_HALIGN_LEFT, /**< Aligns with the left edge. */ LE_HALIGN_CENTER, /**< Aligns with the center. */ LE_HALIGN_RIGHT /**< Aligns with the right edge. */ } leHAlignment; // ***************************************************************************** /* Enumeration: leMargin Summary: legato margin values Description: legato margin values Remarks: None. */ /** * @brief This struct represents the four margin settings for objects. * @details The four margin: left, top, right, bottom controls * the size of the borders around objects. */ typedef struct leMargin { uint8_t left; /**< Aligns with the left margin. */ uint8_t top; /**< Aligns with the top margin. */ uint8_t right; /**< Aligns with the right margin. */ uint8_t bottom; /**< Aligns with the bottom margin. */ } leMargin; /** * @brief This const represents zero margin settings for objects. * @details . */ static const leMargin leMargin_Zero = {0, 0, 0, 0}; // ***************************************************************************** /* Enumeration: leDirection Summary: legato direction values Description: legato direction values Remarks: None. */ /** * @brief This enum represents the four directions modes for objects. * @details The four directions: right, down, left, up controls * the direction of objects. */ typedef enum leDirection { LE_DIRECTION_RIGHT, /**< Specifies right direction. */ LE_DIRECTION_DOWN, /**< Specifies down direction. */ LE_DIRECTION_LEFT, /**< Specifies left direction. */ LE_DIRECTION_UP /**< Specifies up direction. */ } leDirection; // ***************************************************************************** /* Structure: leRotationDirection Summary: Describes rotational direction Description: Describes rotational direction Remarks: None. */ /** * @brief This enum represents the two rotation direction modes for objects. * @details The two directions: counter clockwise, clockwise controls * the rotation direction of objects. */ typedef enum leRotationDirection { LE_COUNTER_CLOCKWISE, /**< Specifies counter clockwise rotation. */ LE_CLOCKWISE, /**< Specifies clockwise rotation. */ } leRotationDirection; // ***************************************************************************** /* Enumeration: leRelativePosition Summary: legato relative position values Description: legato relative position values Remarks: None. */ /** * @brief This enum represents the relative position modes for objects. * @details The relative position modes controls * the relative position of objects to other objects. */ typedef enum leRelativePosition { LE_RELATIVE_POSITION_LEFTOF, /**< Position to the left of object. */ LE_RELATIVE_POSITION_ABOVE, /**< Positive to the right of object. */ LE_RELATIVE_POSITION_BELOW, /**< Positive to the top of object. */ LE_RELATIVE_POSITION_RIGHTOF, /**< Positive to the bottom of object. */ LE_RELATIVE_POSITION_BEHIND /**< Positive to the top of object. */ } leRelativePosition; // ***************************************************************************** /* Enumeration: leOrientation Summary: legato orientation values Description: legato orientation values Remarks: None. */ /** * @brief This enum represents the orientation modes for objects. * @details The orientation modes controls the horizontal and vertical of * objects to other objects. */ typedef enum leOrientation { LE_ORIENTATION_HORIZONTAL, LE_ORIENTATION_VERTICAL, } leOrientation; // ***************************************************************************** /* Structure: lePoint Summary: A two dimensional Cartesian point. */ /** * @brief This structure represents a integer Cartesian point. * @details A point is specified by an x and y coordinate. */ typedef struct lePoint { int32_t x; int32_t y; } lePoint; /** * @brief This const represents zero point setting for a coordinate . * @details . */ static const lePoint lePoint_Zero = {0, 0}; // ***************************************************************************** /* Structure: leSize Summary: A two dimensional indication of size. Values are signed but should never be negative. */ /** * @brief This structure is used represents the size of an item. * @details A size is specified by a width and height. */ typedef struct leSize { int32_t width; /**< width of an item. */ int32_t height; /**< height of an item. */ } leSize; /** * @brief This const represents zero size setting for an object . * @details . */ static const leSize leSize_Zero = {0, 0}; // ***************************************************************************** /* Structure: leRect Summary: A rectangle definition. */ /** * @brief This struct represents a rectangle. * @details A rectangle is specified by x and y top-left position and a width and height * bottom-right position. */ typedef struct leRect { int16_t x; int16_t y; int16_t width; int16_t height; } leRect; /** * @brief This typedef represents general-purpose buffer. * @details The address of any variable of any data type (char, int, * float etc.) can be assigned to a void pointer variable. */ typedef void* leBuffer; /* library configuration flags */ /** * @brief This typedef represents Legato character. * @details A Legato character is a 16-bit character. */ typedef uint16_t leChar; #define LE_UNKNOWN_GLYPH 0xFFFF #ifdef __cplusplus } #endif #define ASSIGN_VIRTUAL_FUNCTION(name) .name = name #define ASSIGN_VTABLE_FUNCTION(vtable, name) vtable.name = name #endif // LEGATO_COMMON_H /******************************************************************************* End of File */
27.037383
88
0.60655
[ "object" ]
34075f687afb17fd7bcc9fd469519f96adeb0dfe
33,962
c
C
src/gallium/drivers/r600/r600_blit.c
thermasol/mesa3d
6f1bc4e7edfface197ef281cffdf399b5389e24a
[ "MIT" ]
null
null
null
src/gallium/drivers/r600/r600_blit.c
thermasol/mesa3d
6f1bc4e7edfface197ef281cffdf399b5389e24a
[ "MIT" ]
null
null
null
src/gallium/drivers/r600/r600_blit.c
thermasol/mesa3d
6f1bc4e7edfface197ef281cffdf399b5389e24a
[ "MIT" ]
null
null
null
/* * Copyright 2010 Jerome Glisse <glisse@freedesktop.org> * * 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 * on the rights to use, copy, modify, merge, publish, distribute, sub * license, 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE AUTHOR(S) AND/OR THEIR SUPPLIERS 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 "r600_pipe.h" #include "compute_memory_pool.h" #include "evergreen_compute.h" #include "util/u_surface.h" #include "util/u_format.h" #include "evergreend.h" enum r600_blitter_op /* bitmask */ { R600_SAVE_FRAGMENT_STATE = 1, R600_SAVE_TEXTURES = 2, R600_SAVE_FRAMEBUFFER = 4, R600_DISABLE_RENDER_COND = 8, R600_CLEAR = R600_SAVE_FRAGMENT_STATE, R600_CLEAR_SURFACE = R600_SAVE_FRAGMENT_STATE | R600_SAVE_FRAMEBUFFER, R600_COPY_BUFFER = R600_DISABLE_RENDER_COND, R600_COPY_TEXTURE = R600_SAVE_FRAGMENT_STATE | R600_SAVE_FRAMEBUFFER | R600_SAVE_TEXTURES | R600_DISABLE_RENDER_COND, R600_BLIT = R600_SAVE_FRAGMENT_STATE | R600_SAVE_FRAMEBUFFER | R600_SAVE_TEXTURES, R600_DECOMPRESS = R600_SAVE_FRAGMENT_STATE | R600_SAVE_FRAMEBUFFER | R600_DISABLE_RENDER_COND, R600_COLOR_RESOLVE = R600_SAVE_FRAGMENT_STATE | R600_SAVE_FRAMEBUFFER }; static void r600_blitter_begin(struct pipe_context *ctx, enum r600_blitter_op op) { struct r600_context *rctx = (struct r600_context *)ctx; if (rctx->cmd_buf_is_compute) { rctx->b.gfx.flush(rctx, PIPE_FLUSH_ASYNC, NULL); rctx->cmd_buf_is_compute = false; } util_blitter_save_vertex_buffer_slot(rctx->blitter, rctx->vertex_buffer_state.vb); util_blitter_save_vertex_elements(rctx->blitter, rctx->vertex_fetch_shader.cso); util_blitter_save_vertex_shader(rctx->blitter, rctx->vs_shader); util_blitter_save_geometry_shader(rctx->blitter, rctx->gs_shader); util_blitter_save_tessctrl_shader(rctx->blitter, rctx->tcs_shader); util_blitter_save_tesseval_shader(rctx->blitter, rctx->tes_shader); util_blitter_save_so_targets(rctx->blitter, rctx->b.streamout.num_targets, (struct pipe_stream_output_target**)rctx->b.streamout.targets); util_blitter_save_rasterizer(rctx->blitter, rctx->rasterizer_state.cso); if (op & R600_SAVE_FRAGMENT_STATE) { util_blitter_save_viewport(rctx->blitter, &rctx->b.viewports.states[0]); util_blitter_save_scissor(rctx->blitter, &rctx->b.scissors.states[0]); util_blitter_save_fragment_shader(rctx->blitter, rctx->ps_shader); util_blitter_save_blend(rctx->blitter, rctx->blend_state.cso); util_blitter_save_depth_stencil_alpha(rctx->blitter, rctx->dsa_state.cso); util_blitter_save_stencil_ref(rctx->blitter, &rctx->stencil_ref.pipe_state); util_blitter_save_sample_mask(rctx->blitter, rctx->sample_mask.sample_mask); } if (op & R600_SAVE_FRAMEBUFFER) util_blitter_save_framebuffer(rctx->blitter, &rctx->framebuffer.state); if (op & R600_SAVE_TEXTURES) { util_blitter_save_fragment_sampler_states( rctx->blitter, util_last_bit(rctx->samplers[PIPE_SHADER_FRAGMENT].states.enabled_mask), (void**)rctx->samplers[PIPE_SHADER_FRAGMENT].states.states); util_blitter_save_fragment_sampler_views( rctx->blitter, util_last_bit(rctx->samplers[PIPE_SHADER_FRAGMENT].views.enabled_mask), (struct pipe_sampler_view**)rctx->samplers[PIPE_SHADER_FRAGMENT].views.views); } if (op & R600_DISABLE_RENDER_COND) rctx->b.render_cond_force_off = true; } static void r600_blitter_end(struct pipe_context *ctx) { struct r600_context *rctx = (struct r600_context *)ctx; rctx->b.render_cond_force_off = false; } static unsigned u_max_sample(struct pipe_resource *r) { return r->nr_samples ? r->nr_samples - 1 : 0; } static void r600_blit_decompress_depth(struct pipe_context *ctx, struct r600_texture *texture, struct r600_texture *staging, unsigned first_level, unsigned last_level, unsigned first_layer, unsigned last_layer, unsigned first_sample, unsigned last_sample) { struct r600_context *rctx = (struct r600_context *)ctx; unsigned layer, level, sample, checked_last_layer, max_layer, max_sample; struct r600_texture *flushed_depth_texture = staging ? staging : texture->flushed_depth_texture; const struct util_format_description *desc = util_format_description(texture->resource.b.b.format); float depth; if (!staging && !texture->dirty_level_mask) return; max_sample = u_max_sample(&texture->resource.b.b); /* XXX Decompressing MSAA depth textures is broken on R6xx. * There is also a hardlock if CMASK and FMASK are not present. * Just skip this until we find out how to fix it. */ if (rctx->b.chip_class == R600 && max_sample > 0) { texture->dirty_level_mask = 0; return; } if (rctx->b.family == CHIP_RV610 || rctx->b.family == CHIP_RV630 || rctx->b.family == CHIP_RV620 || rctx->b.family == CHIP_RV635) depth = 0.0f; else depth = 1.0f; /* Enable decompression in DB_RENDER_CONTROL */ rctx->db_misc_state.flush_depthstencil_through_cb = true; rctx->db_misc_state.copy_depth = util_format_has_depth(desc); rctx->db_misc_state.copy_stencil = util_format_has_stencil(desc); rctx->db_misc_state.copy_sample = first_sample; r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); for (level = first_level; level <= last_level; level++) { if (!staging && !(texture->dirty_level_mask & (1 << level))) continue; /* The smaller the mipmap level, the less layers there are * as far as 3D textures are concerned. */ max_layer = util_max_layer(&texture->resource.b.b, level); checked_last_layer = last_layer < max_layer ? last_layer : max_layer; for (layer = first_layer; layer <= checked_last_layer; layer++) { for (sample = first_sample; sample <= last_sample; sample++) { struct pipe_surface *zsurf, *cbsurf, surf_tmpl; if (sample != rctx->db_misc_state.copy_sample) { rctx->db_misc_state.copy_sample = sample; r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); } surf_tmpl.format = texture->resource.b.b.format; surf_tmpl.u.tex.level = level; surf_tmpl.u.tex.first_layer = layer; surf_tmpl.u.tex.last_layer = layer; zsurf = ctx->create_surface(ctx, &texture->resource.b.b, &surf_tmpl); surf_tmpl.format = flushed_depth_texture->resource.b.b.format; cbsurf = ctx->create_surface(ctx, &flushed_depth_texture->resource.b.b, &surf_tmpl); r600_blitter_begin(ctx, R600_DECOMPRESS); util_blitter_custom_depth_stencil(rctx->blitter, zsurf, cbsurf, 1 << sample, rctx->custom_dsa_flush, depth); r600_blitter_end(ctx); pipe_surface_reference(&zsurf, NULL); pipe_surface_reference(&cbsurf, NULL); } } /* The texture will always be dirty if some layers or samples aren't flushed. * I don't think this case occurs often though. */ if (!staging && first_layer == 0 && last_layer == max_layer && first_sample == 0 && last_sample == max_sample) { texture->dirty_level_mask &= ~(1 << level); } } /* reenable compression in DB_RENDER_CONTROL */ rctx->db_misc_state.flush_depthstencil_through_cb = false; r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); } static void r600_blit_decompress_depth_in_place(struct r600_context *rctx, struct r600_texture *texture, bool is_stencil_sampler, unsigned first_level, unsigned last_level, unsigned first_layer, unsigned last_layer) { struct pipe_surface *zsurf, surf_tmpl = {{0}}; unsigned layer, max_layer, checked_last_layer, level; unsigned *dirty_level_mask; /* Enable decompression in DB_RENDER_CONTROL */ if (is_stencil_sampler) { rctx->db_misc_state.flush_stencil_inplace = true; dirty_level_mask = &texture->stencil_dirty_level_mask; } else { rctx->db_misc_state.flush_depth_inplace = true; dirty_level_mask = &texture->dirty_level_mask; } r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); surf_tmpl.format = texture->resource.b.b.format; for (level = first_level; level <= last_level; level++) { if (!(*dirty_level_mask & (1 << level))) continue; surf_tmpl.u.tex.level = level; /* The smaller the mipmap level, the less layers there are * as far as 3D textures are concerned. */ max_layer = util_max_layer(&texture->resource.b.b, level); checked_last_layer = last_layer < max_layer ? last_layer : max_layer; for (layer = first_layer; layer <= checked_last_layer; layer++) { surf_tmpl.u.tex.first_layer = layer; surf_tmpl.u.tex.last_layer = layer; zsurf = rctx->b.b.create_surface(&rctx->b.b, &texture->resource.b.b, &surf_tmpl); r600_blitter_begin(&rctx->b.b, R600_DECOMPRESS); util_blitter_custom_depth_stencil(rctx->blitter, zsurf, NULL, ~0, rctx->custom_dsa_flush, 1.0f); r600_blitter_end(&rctx->b.b); pipe_surface_reference(&zsurf, NULL); } /* The texture will always be dirty if some layers or samples aren't flushed. * I don't think this case occurs often though. */ if (first_layer == 0 && last_layer == max_layer) { *dirty_level_mask &= ~(1 << level); } } /* Disable decompression in DB_RENDER_CONTROL */ rctx->db_misc_state.flush_depth_inplace = false; rctx->db_misc_state.flush_stencil_inplace = false; r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); } void r600_decompress_depth_textures(struct r600_context *rctx, struct r600_samplerview_state *textures) { unsigned i; unsigned depth_texture_mask = textures->compressed_depthtex_mask; while (depth_texture_mask) { struct pipe_sampler_view *view; struct r600_pipe_sampler_view *rview; struct r600_texture *tex; i = u_bit_scan(&depth_texture_mask); view = &textures->views[i]->base; assert(view); rview = (struct r600_pipe_sampler_view*)view; tex = (struct r600_texture *)view->texture; assert(tex->db_compatible); if (r600_can_sample_zs(tex, rview->is_stencil_sampler)) { r600_blit_decompress_depth_in_place(rctx, tex, rview->is_stencil_sampler, view->u.tex.first_level, view->u.tex.last_level, 0, util_max_layer(&tex->resource.b.b, view->u.tex.first_level)); } else { r600_blit_decompress_depth(&rctx->b.b, tex, NULL, view->u.tex.first_level, view->u.tex.last_level, 0, util_max_layer(&tex->resource.b.b, view->u.tex.first_level), 0, u_max_sample(&tex->resource.b.b)); } } } void r600_decompress_depth_images(struct r600_context *rctx, struct r600_image_state *images) { unsigned i; unsigned depth_texture_mask = images->compressed_depthtex_mask; while (depth_texture_mask) { struct r600_image_view *view; struct r600_texture *tex; i = u_bit_scan(&depth_texture_mask); view = &images->views[i]; assert(view); tex = (struct r600_texture *)view->base.resource; assert(tex->db_compatible); if (r600_can_sample_zs(tex, false)) { r600_blit_decompress_depth_in_place(rctx, tex, false, view->base.u.tex.level, view->base.u.tex.level, 0, util_max_layer(&tex->resource.b.b, view->base.u.tex.level)); } else { r600_blit_decompress_depth(&rctx->b.b, tex, NULL, view->base.u.tex.level, view->base.u.tex.level, 0, util_max_layer(&tex->resource.b.b, view->base.u.tex.level), 0, u_max_sample(&tex->resource.b.b)); } } } static void r600_blit_decompress_color(struct pipe_context *ctx, struct r600_texture *rtex, unsigned first_level, unsigned last_level, unsigned first_layer, unsigned last_layer) { struct r600_context *rctx = (struct r600_context *)ctx; unsigned layer, level, checked_last_layer, max_layer; if (!rtex->dirty_level_mask) return; for (level = first_level; level <= last_level; level++) { if (!(rtex->dirty_level_mask & (1 << level))) continue; /* The smaller the mipmap level, the less layers there are * as far as 3D textures are concerned. */ max_layer = util_max_layer(&rtex->resource.b.b, level); checked_last_layer = last_layer < max_layer ? last_layer : max_layer; for (layer = first_layer; layer <= checked_last_layer; layer++) { struct pipe_surface *cbsurf, surf_tmpl; surf_tmpl.format = rtex->resource.b.b.format; surf_tmpl.u.tex.level = level; surf_tmpl.u.tex.first_layer = layer; surf_tmpl.u.tex.last_layer = layer; cbsurf = ctx->create_surface(ctx, &rtex->resource.b.b, &surf_tmpl); r600_blitter_begin(ctx, R600_DECOMPRESS); util_blitter_custom_color(rctx->blitter, cbsurf, rtex->fmask.size ? rctx->custom_blend_decompress : rctx->custom_blend_fastclear); r600_blitter_end(ctx); pipe_surface_reference(&cbsurf, NULL); } /* The texture will always be dirty if some layers aren't flushed. * I don't think this case occurs often though. */ if (first_layer == 0 && last_layer == max_layer) { rtex->dirty_level_mask &= ~(1 << level); } } } void r600_decompress_color_textures(struct r600_context *rctx, struct r600_samplerview_state *textures) { unsigned i; unsigned mask = textures->compressed_colortex_mask; while (mask) { struct pipe_sampler_view *view; struct r600_texture *tex; i = u_bit_scan(&mask); view = &textures->views[i]->base; assert(view); tex = (struct r600_texture *)view->texture; assert(tex->cmask.size); r600_blit_decompress_color(&rctx->b.b, tex, view->u.tex.first_level, view->u.tex.last_level, 0, util_max_layer(&tex->resource.b.b, view->u.tex.first_level)); } } void r600_decompress_color_images(struct r600_context *rctx, struct r600_image_state *images) { unsigned i; unsigned mask = images->compressed_colortex_mask; while (mask) { struct r600_image_view *view; struct r600_texture *tex; i = u_bit_scan(&mask); view = &images->views[i]; assert(view); tex = (struct r600_texture *)view->base.resource; assert(tex->cmask.size); r600_blit_decompress_color(&rctx->b.b, tex, view->base.u.tex.level, view->base.u.tex.level, view->base.u.tex.first_layer, view->base.u.tex.last_layer); } } /* Helper for decompressing a portion of a color or depth resource before * blitting if any decompression is needed. * The driver doesn't decompress resources automatically while u_blitter is * rendering. */ static bool r600_decompress_subresource(struct pipe_context *ctx, struct pipe_resource *tex, unsigned level, unsigned first_layer, unsigned last_layer) { struct r600_context *rctx = (struct r600_context *)ctx; struct r600_texture *rtex = (struct r600_texture*)tex; if (rtex->db_compatible) { if (r600_can_sample_zs(rtex, false)) { r600_blit_decompress_depth_in_place(rctx, rtex, false, level, level, first_layer, last_layer); if (rtex->surface.has_stencil) { r600_blit_decompress_depth_in_place(rctx, rtex, true, level, level, first_layer, last_layer); } } else { if (!r600_init_flushed_depth_texture(ctx, tex, NULL)) return false; /* error */ r600_blit_decompress_depth(ctx, rtex, NULL, level, level, first_layer, last_layer, 0, u_max_sample(tex)); } } else if (rtex->cmask.size) { r600_blit_decompress_color(ctx, rtex, level, level, first_layer, last_layer); } return true; } static void r600_clear(struct pipe_context *ctx, unsigned buffers, const union pipe_color_union *color, double depth, unsigned stencil) { struct r600_context *rctx = (struct r600_context *)ctx; struct pipe_framebuffer_state *fb = &rctx->framebuffer.state; if (buffers & PIPE_CLEAR_COLOR && rctx->b.chip_class >= EVERGREEN) { evergreen_do_fast_color_clear(&rctx->b, fb, &rctx->framebuffer.atom, &buffers, NULL, color); if (!buffers) return; /* all buffers have been fast cleared */ } if (buffers & PIPE_CLEAR_COLOR) { int i; /* These buffers cannot use fast clear, make sure to disable expansion. */ for (i = 0; i < fb->nr_cbufs; i++) { struct r600_texture *tex; /* If not clearing this buffer, skip. */ if (!(buffers & (PIPE_CLEAR_COLOR0 << i))) continue; if (!fb->cbufs[i]) continue; tex = (struct r600_texture *)fb->cbufs[i]->texture; if (tex->fmask.size == 0) tex->dirty_level_mask &= ~(1 << fb->cbufs[i]->u.tex.level); } } /* if hyperz enabled just clear hyperz */ if (fb->zsbuf && (buffers & PIPE_CLEAR_DEPTH)) { struct r600_texture *rtex; unsigned level = fb->zsbuf->u.tex.level; rtex = (struct r600_texture*)fb->zsbuf->texture; /* We can't use hyperz fast clear if each slice of a texture * array are clear to different value. To simplify code just * disable fast clear for texture array. */ if (r600_htile_enabled(rtex, level) && fb->zsbuf->u.tex.first_layer == 0 && fb->zsbuf->u.tex.last_layer == util_max_layer(&rtex->resource.b.b, level)) { if (rtex->depth_clear_value != depth) { rtex->depth_clear_value = depth; r600_mark_atom_dirty(rctx, &rctx->db_state.atom); } rctx->db_misc_state.htile_clear = true; r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); } } r600_blitter_begin(ctx, R600_CLEAR); util_blitter_clear(rctx->blitter, fb->width, fb->height, util_framebuffer_get_num_layers(fb), buffers, color, depth, stencil); r600_blitter_end(ctx); /* disable fast clear */ if (rctx->db_misc_state.htile_clear) { rctx->db_misc_state.htile_clear = false; r600_mark_atom_dirty(rctx, &rctx->db_misc_state.atom); } } static void r600_clear_render_target(struct pipe_context *ctx, struct pipe_surface *dst, const union pipe_color_union *color, unsigned dstx, unsigned dsty, unsigned width, unsigned height, bool render_condition_enabled) { struct r600_context *rctx = (struct r600_context *)ctx; r600_blitter_begin(ctx, R600_CLEAR_SURFACE | (render_condition_enabled ? 0 : R600_DISABLE_RENDER_COND)); util_blitter_clear_render_target(rctx->blitter, dst, color, dstx, dsty, width, height); r600_blitter_end(ctx); } static void r600_clear_depth_stencil(struct pipe_context *ctx, struct pipe_surface *dst, unsigned clear_flags, double depth, unsigned stencil, unsigned dstx, unsigned dsty, unsigned width, unsigned height, bool render_condition_enabled) { struct r600_context *rctx = (struct r600_context *)ctx; r600_blitter_begin(ctx, R600_CLEAR_SURFACE | (render_condition_enabled ? 0 : R600_DISABLE_RENDER_COND)); util_blitter_clear_depth_stencil(rctx->blitter, dst, clear_flags, depth, stencil, dstx, dsty, width, height); r600_blitter_end(ctx); } static void r600_copy_buffer(struct pipe_context *ctx, struct pipe_resource *dst, unsigned dstx, struct pipe_resource *src, const struct pipe_box *src_box) { struct r600_context *rctx = (struct r600_context*)ctx; if (rctx->screen->b.has_cp_dma) { r600_cp_dma_copy_buffer(rctx, dst, dstx, src, src_box->x, src_box->width); } else if (rctx->screen->b.has_streamout && /* Require 4-byte alignment. */ dstx % 4 == 0 && src_box->x % 4 == 0 && src_box->width % 4 == 0) { r600_blitter_begin(ctx, R600_COPY_BUFFER); util_blitter_copy_buffer(rctx->blitter, dst, dstx, src, src_box->x, src_box->width); r600_blitter_end(ctx); } else { util_resource_copy_region(ctx, dst, 0, dstx, 0, 0, src, 0, src_box); } } /** * Global buffers are not really resources, they are are actually offsets * into a single global resource (r600_screen::global_pool). The means * they don't have their own buf handle, so they cannot be passed * to r600_copy_buffer() and must be handled separately. */ static void r600_copy_global_buffer(struct pipe_context *ctx, struct pipe_resource *dst, unsigned dstx, struct pipe_resource *src, const struct pipe_box *src_box) { struct r600_context *rctx = (struct r600_context*)ctx; struct compute_memory_pool *pool = rctx->screen->global_pool; struct pipe_box new_src_box = *src_box; if (src->bind & PIPE_BIND_GLOBAL) { struct r600_resource_global *rsrc = (struct r600_resource_global *)src; struct compute_memory_item *item = rsrc->chunk; if (is_item_in_pool(item)) { new_src_box.x += 4 * item->start_in_dw; src = (struct pipe_resource *)pool->bo; } else { if (item->real_buffer == NULL) { item->real_buffer = r600_compute_buffer_alloc_vram(pool->screen, item->size_in_dw * 4); } src = (struct pipe_resource*)item->real_buffer; } } if (dst->bind & PIPE_BIND_GLOBAL) { struct r600_resource_global *rdst = (struct r600_resource_global *)dst; struct compute_memory_item *item = rdst->chunk; if (is_item_in_pool(item)) { dstx += 4 * item->start_in_dw; dst = (struct pipe_resource *)pool->bo; } else { if (item->real_buffer == NULL) { item->real_buffer = r600_compute_buffer_alloc_vram(pool->screen, item->size_in_dw * 4); } dst = (struct pipe_resource*)item->real_buffer; } } r600_copy_buffer(ctx, dst, dstx, src, &new_src_box); } static void r600_clear_buffer(struct pipe_context *ctx, struct pipe_resource *dst, uint64_t offset, uint64_t size, unsigned value, enum r600_coherency coher) { struct r600_context *rctx = (struct r600_context*)ctx; if (rctx->screen->b.has_cp_dma && rctx->b.chip_class >= EVERGREEN && offset % 4 == 0 && size % 4 == 0) { evergreen_cp_dma_clear_buffer(rctx, dst, offset, size, value, coher); } else if (rctx->screen->b.has_streamout && offset % 4 == 0 && size % 4 == 0) { union pipe_color_union clear_value; clear_value.ui[0] = value; r600_blitter_begin(ctx, R600_DISABLE_RENDER_COND); util_blitter_clear_buffer(rctx->blitter, dst, offset, size, 1, &clear_value); r600_blitter_end(ctx); } else { uint32_t *map = r600_buffer_map_sync_with_rings(&rctx->b, r600_resource(dst), PIPE_TRANSFER_WRITE); map += offset / 4; size /= 4; for (unsigned i = 0; i < size; i++) *map++ = value; } } void r600_resource_copy_region(struct pipe_context *ctx, struct pipe_resource *dst, unsigned dst_level, unsigned dstx, unsigned dsty, unsigned dstz, struct pipe_resource *src, unsigned src_level, const struct pipe_box *src_box) { struct r600_context *rctx = (struct r600_context *)ctx; struct pipe_surface *dst_view, dst_templ; struct pipe_sampler_view src_templ, *src_view; unsigned dst_width, dst_height, src_width0, src_height0, src_widthFL, src_heightFL; unsigned src_force_level = 0; struct pipe_box sbox, dstbox; /* Handle buffers first. */ if (dst->target == PIPE_BUFFER && src->target == PIPE_BUFFER) { if ((src->bind & PIPE_BIND_GLOBAL) || (dst->bind & PIPE_BIND_GLOBAL)) { r600_copy_global_buffer(ctx, dst, dstx, src, src_box); } else { r600_copy_buffer(ctx, dst, dstx, src, src_box); } return; } assert(u_max_sample(dst) == u_max_sample(src)); /* The driver doesn't decompress resources automatically while * u_blitter is rendering. */ if (!r600_decompress_subresource(ctx, src, src_level, src_box->z, src_box->z + src_box->depth - 1)) { return; /* error */ } dst_width = u_minify(dst->width0, dst_level); dst_height = u_minify(dst->height0, dst_level); src_width0 = src->width0; src_height0 = src->height0; src_widthFL = u_minify(src->width0, src_level); src_heightFL = u_minify(src->height0, src_level); util_blitter_default_dst_texture(&dst_templ, dst, dst_level, dstz); util_blitter_default_src_texture(rctx->blitter, &src_templ, src, src_level); if (util_format_is_compressed(src->format) || util_format_is_compressed(dst->format)) { unsigned blocksize = util_format_get_blocksize(src->format); if (blocksize == 8) src_templ.format = PIPE_FORMAT_R16G16B16A16_UINT; /* 64-bit block */ else src_templ.format = PIPE_FORMAT_R32G32B32A32_UINT; /* 128-bit block */ dst_templ.format = src_templ.format; dst_width = util_format_get_nblocksx(dst->format, dst_width); dst_height = util_format_get_nblocksy(dst->format, dst_height); src_width0 = util_format_get_nblocksx(src->format, src_width0); src_height0 = util_format_get_nblocksy(src->format, src_height0); src_widthFL = util_format_get_nblocksx(src->format, src_widthFL); src_heightFL = util_format_get_nblocksy(src->format, src_heightFL); dstx = util_format_get_nblocksx(dst->format, dstx); dsty = util_format_get_nblocksy(dst->format, dsty); sbox.x = util_format_get_nblocksx(src->format, src_box->x); sbox.y = util_format_get_nblocksy(src->format, src_box->y); sbox.z = src_box->z; sbox.width = util_format_get_nblocksx(src->format, src_box->width); sbox.height = util_format_get_nblocksy(src->format, src_box->height); sbox.depth = src_box->depth; src_box = &sbox; src_force_level = src_level; } else if (!util_blitter_is_copy_supported(rctx->blitter, dst, src)) { if (util_format_is_subsampled_422(src->format)) { src_templ.format = PIPE_FORMAT_R8G8B8A8_UINT; dst_templ.format = PIPE_FORMAT_R8G8B8A8_UINT; dst_width = util_format_get_nblocksx(dst->format, dst_width); src_width0 = util_format_get_nblocksx(src->format, src_width0); src_widthFL = util_format_get_nblocksx(src->format, src_widthFL); dstx = util_format_get_nblocksx(dst->format, dstx); sbox = *src_box; sbox.x = util_format_get_nblocksx(src->format, src_box->x); sbox.width = util_format_get_nblocksx(src->format, src_box->width); src_box = &sbox; } else { unsigned blocksize = util_format_get_blocksize(src->format); switch (blocksize) { case 1: dst_templ.format = PIPE_FORMAT_R8_UNORM; src_templ.format = PIPE_FORMAT_R8_UNORM; break; case 2: dst_templ.format = PIPE_FORMAT_R8G8_UNORM; src_templ.format = PIPE_FORMAT_R8G8_UNORM; break; case 4: dst_templ.format = PIPE_FORMAT_R8G8B8A8_UNORM; src_templ.format = PIPE_FORMAT_R8G8B8A8_UNORM; break; case 8: dst_templ.format = PIPE_FORMAT_R16G16B16A16_UINT; src_templ.format = PIPE_FORMAT_R16G16B16A16_UINT; break; case 16: dst_templ.format = PIPE_FORMAT_R32G32B32A32_UINT; src_templ.format = PIPE_FORMAT_R32G32B32A32_UINT; break; default: fprintf(stderr, "Unhandled format %s with blocksize %u\n", util_format_short_name(src->format), blocksize); assert(0); } } } dst_view = r600_create_surface_custom(ctx, dst, &dst_templ, /* we don't care about these two for r600g */ dst->width0, dst->height0, dst_width, dst_height); if (rctx->b.chip_class >= EVERGREEN) { src_view = evergreen_create_sampler_view_custom(ctx, src, &src_templ, src_width0, src_height0, src_force_level); } else { src_view = r600_create_sampler_view_custom(ctx, src, &src_templ, src_widthFL, src_heightFL); } u_box_3d(dstx, dsty, dstz, abs(src_box->width), abs(src_box->height), abs(src_box->depth), &dstbox); /* Copy. */ r600_blitter_begin(ctx, R600_COPY_TEXTURE); util_blitter_blit_generic(rctx->blitter, dst_view, &dstbox, src_view, src_box, src_width0, src_height0, PIPE_MASK_RGBAZS, PIPE_TEX_FILTER_NEAREST, NULL, FALSE); r600_blitter_end(ctx); pipe_surface_reference(&dst_view, NULL); pipe_sampler_view_reference(&src_view, NULL); } static bool do_hardware_msaa_resolve(struct pipe_context *ctx, const struct pipe_blit_info *info) { struct r600_context *rctx = (struct r600_context*)ctx; struct r600_texture *dst = (struct r600_texture*)info->dst.resource; unsigned dst_width = u_minify(info->dst.resource->width0, info->dst.level); unsigned dst_height = u_minify(info->dst.resource->height0, info->dst.level); enum pipe_format format = info->src.format; unsigned sample_mask = rctx->b.chip_class == CAYMAN ? ~0 : ((1ull << MAX2(1, info->src.resource->nr_samples)) - 1); struct pipe_resource *tmp, templ; struct pipe_blit_info blit; /* Check basic requirements for hw resolve. */ if (!(info->src.resource->nr_samples > 1 && info->dst.resource->nr_samples <= 1 && !util_format_is_pure_integer(format) && !util_format_is_depth_or_stencil(format) && util_max_layer(info->src.resource, 0) == 0)) return false; /* Check the remaining requirements for hw resolve. */ if (util_max_layer(info->dst.resource, info->dst.level) == 0 && util_is_format_compatible(util_format_description(info->src.format), util_format_description(info->dst.format)) && !info->scissor_enable && (info->mask & PIPE_MASK_RGBA) == PIPE_MASK_RGBA && dst_width == info->src.resource->width0 && dst_height == info->src.resource->height0 && info->dst.box.x == 0 && info->dst.box.y == 0 && info->dst.box.width == dst_width && info->dst.box.height == dst_height && info->dst.box.depth == 1 && info->src.box.x == 0 && info->src.box.y == 0 && info->src.box.width == dst_width && info->src.box.height == dst_height && info->src.box.depth == 1 && dst->surface.u.legacy.level[info->dst.level].mode >= RADEON_SURF_MODE_1D && (!dst->cmask.size || !dst->dirty_level_mask) /* dst cannot be fast-cleared */) { r600_blitter_begin(ctx, R600_COLOR_RESOLVE | (info->render_condition_enable ? 0 : R600_DISABLE_RENDER_COND)); util_blitter_custom_resolve_color(rctx->blitter, info->dst.resource, info->dst.level, info->dst.box.z, info->src.resource, info->src.box.z, sample_mask, rctx->custom_blend_resolve, format); r600_blitter_end(ctx); return true; } /* Shader-based resolve is VERY SLOW. Instead, resolve into * a temporary texture and blit. */ memset(&templ, 0, sizeof(templ)); templ.target = PIPE_TEXTURE_2D; templ.format = info->src.resource->format; templ.width0 = info->src.resource->width0; templ.height0 = info->src.resource->height0; templ.depth0 = 1; templ.array_size = 1; templ.usage = PIPE_USAGE_DEFAULT; templ.flags = R600_RESOURCE_FLAG_FORCE_TILING; tmp = ctx->screen->resource_create(ctx->screen, &templ); if (!tmp) return false; /* resolve */ r600_blitter_begin(ctx, R600_COLOR_RESOLVE | (info->render_condition_enable ? 0 : R600_DISABLE_RENDER_COND)); util_blitter_custom_resolve_color(rctx->blitter, tmp, 0, 0, info->src.resource, info->src.box.z, sample_mask, rctx->custom_blend_resolve, format); r600_blitter_end(ctx); /* blit */ blit = *info; blit.src.resource = tmp; blit.src.box.z = 0; r600_blitter_begin(ctx, R600_BLIT | (info->render_condition_enable ? 0 : R600_DISABLE_RENDER_COND)); util_blitter_blit(rctx->blitter, &blit); r600_blitter_end(ctx); pipe_resource_reference(&tmp, NULL); return true; } static void r600_blit(struct pipe_context *ctx, const struct pipe_blit_info *info) { struct r600_context *rctx = (struct r600_context*)ctx; struct r600_texture *rdst = (struct r600_texture *)info->dst.resource; if (do_hardware_msaa_resolve(ctx, info)) { return; } /* Using SDMA for copying to a linear texture in GTT is much faster. * This improves DRI PRIME performance. * * resource_copy_region can't do this yet, because dma_copy calls it * on failure (recursion). */ if (rdst->surface.u.legacy.level[info->dst.level].mode == RADEON_SURF_MODE_LINEAR_ALIGNED && rctx->b.dma_copy && util_can_blit_via_copy_region(info, false)) { rctx->b.dma_copy(ctx, info->dst.resource, info->dst.level, info->dst.box.x, info->dst.box.y, info->dst.box.z, info->src.resource, info->src.level, &info->src.box); return; } assert(util_blitter_is_blit_supported(rctx->blitter, info)); /* The driver doesn't decompress resources automatically while * u_blitter is rendering. */ if (!r600_decompress_subresource(ctx, info->src.resource, info->src.level, info->src.box.z, info->src.box.z + info->src.box.depth - 1)) { return; /* error */ } if (rctx->screen->b.debug_flags & DBG_FORCE_DMA && util_try_blit_via_copy_region(ctx, info)) return; r600_blitter_begin(ctx, R600_BLIT | (info->render_condition_enable ? 0 : R600_DISABLE_RENDER_COND)); util_blitter_blit(rctx->blitter, info); r600_blitter_end(ctx); } static void r600_flush_resource(struct pipe_context *ctx, struct pipe_resource *res) { struct r600_texture *rtex = (struct r600_texture*)res; assert(res->target != PIPE_BUFFER); if (!rtex->is_depth && rtex->cmask.size) { r600_blit_decompress_color(ctx, rtex, 0, res->last_level, 0, util_max_layer(res, 0)); } } void r600_init_blit_functions(struct r600_context *rctx) { rctx->b.b.clear = r600_clear; rctx->b.b.clear_render_target = r600_clear_render_target; rctx->b.b.clear_depth_stencil = r600_clear_depth_stencil; rctx->b.b.resource_copy_region = r600_resource_copy_region; rctx->b.b.blit = r600_blit; rctx->b.b.flush_resource = r600_flush_resource; rctx->b.clear_buffer = r600_clear_buffer; rctx->b.blit_decompress_depth = r600_blit_decompress_depth; }
34.409321
98
0.710794
[ "3d" ]
340e86cbc327c697678365e430562f7cd4a84724
2,004
c
C
ConfProfile/jni/strongswan/src/libcharon/plugins/systime_fix/systime_fix_validator.c
Infoss/conf-profile-4-android
619bd63095bb0f5a67616436d5510d24a233a339
[ "MIT" ]
2
2017-10-16T07:51:18.000Z
2019-06-16T12:07:52.000Z
strongswan/strongswan-5.3.2/src/libcharon/plugins/systime_fix/systime_fix_validator.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
5
2016-01-25T18:04:42.000Z
2016-02-25T08:54:56.000Z
strongswan/strongswan-5.3.2/src/libcharon/plugins/systime_fix/systime_fix_validator.c
SECURED-FP7/secured-mobility-ned
36fdbfee58a31d42f7047f7a7eaa1b2b70246151
[ "Apache-2.0" ]
2
2016-01-25T17:14:17.000Z
2016-02-13T20:14:09.000Z
/* * Copyright (C) 2013 Martin Willi * Copyright (C) 2013 revosec AG * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. */ #include "systime_fix_validator.h" #include <errno.h> #include <time.h> #include <daemon.h> typedef struct private_systime_fix_validator_t private_systime_fix_validator_t; /** * Private data of an systime_fix_validator_t object. */ struct private_systime_fix_validator_t { /** * Public systime_fix_validator_t interface. */ systime_fix_validator_t public; /** * Timestamp where we start to consider system time valid */ time_t threshold; }; METHOD(cert_validator_t, check_lifetime, status_t, private_systime_fix_validator_t *this, certificate_t *cert, int pathlen, bool anchor, auth_cfg_t *auth) { if (time(NULL) < this->threshold) { /* our system time seems to be invalid, accept certificate */ if (pathlen) { /* report only once per validated chain */ DBG1(DBG_CFG, "system time out of sync, skipping certificate " "lifetime check"); } return SUCCESS; } /* validate this certificate normally */ return NEED_MORE; } METHOD(systime_fix_validator_t, destroy, void, private_systime_fix_validator_t *this) { free(this); } /** * See header */ systime_fix_validator_t *systime_fix_validator_create(time_t threshold) { private_systime_fix_validator_t *this; INIT(this, .public = { .validator = { .check_lifetime = _check_lifetime, }, .destroy = _destroy, }, .threshold = threshold, ); return &this->public; }
23.857143
79
0.732036
[ "object" ]
34115b95041aa3257d5a9fa7a6b6c9fdce310f43
14,784
h
C
aws-cpp-sdk-lightsail/include/aws/lightsail/model/CloudFormationStackRecord.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lightsail/include/aws/lightsail/model/CloudFormationStackRecord.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lightsail/include/aws/lightsail/model/CloudFormationStackRecord.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/lightsail/Lightsail_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/DateTime.h> #include <aws/lightsail/model/ResourceLocation.h> #include <aws/lightsail/model/ResourceType.h> #include <aws/lightsail/model/RecordState.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/lightsail/model/DestinationInfo.h> #include <aws/lightsail/model/CloudFormationStackRecordSourceInfo.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Lightsail { namespace Model { /** * <p>Describes a CloudFormation stack record created as a result of the * <code>create cloud formation stack</code> operation.</p> <p>A CloudFormation * stack record provides information about the AWS CloudFormation stack used to * create a new Amazon Elastic Compute Cloud instance from an exported Lightsail * instance snapshot.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloudFormationStackRecord">AWS * API Reference</a></p> */ class AWS_LIGHTSAIL_API CloudFormationStackRecord { public: CloudFormationStackRecord(); CloudFormationStackRecord(Aws::Utils::Json::JsonView jsonValue); CloudFormationStackRecord& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline CloudFormationStackRecord& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline CloudFormationStackRecord& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the CloudFormation stack record. It starts with * <code>CloudFormationStackRecord</code> followed by a GUID.</p> */ inline CloudFormationStackRecord& WithName(const char* value) { SetName(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline const Aws::String& GetArn() const{ return m_arn; } /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; } /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithArn(const Aws::String& value) { SetArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithArn(const char* value) { SetArn(value); return *this;} /** * <p>The date when the CloudFormation stack record was created.</p> */ inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; } /** * <p>The date when the CloudFormation stack record was created.</p> */ inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; } /** * <p>The date when the CloudFormation stack record was created.</p> */ inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; } /** * <p>The date when the CloudFormation stack record was created.</p> */ inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); } /** * <p>The date when the CloudFormation stack record was created.</p> */ inline CloudFormationStackRecord& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;} /** * <p>The date when the CloudFormation stack record was created.</p> */ inline CloudFormationStackRecord& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;} /** * <p>A list of objects describing the Availability Zone and AWS Region of the * CloudFormation stack record.</p> */ inline const ResourceLocation& GetLocation() const{ return m_location; } /** * <p>A list of objects describing the Availability Zone and AWS Region of the * CloudFormation stack record.</p> */ inline bool LocationHasBeenSet() const { return m_locationHasBeenSet; } /** * <p>A list of objects describing the Availability Zone and AWS Region of the * CloudFormation stack record.</p> */ inline void SetLocation(const ResourceLocation& value) { m_locationHasBeenSet = true; m_location = value; } /** * <p>A list of objects describing the Availability Zone and AWS Region of the * CloudFormation stack record.</p> */ inline void SetLocation(ResourceLocation&& value) { m_locationHasBeenSet = true; m_location = std::move(value); } /** * <p>A list of objects describing the Availability Zone and AWS Region of the * CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithLocation(const ResourceLocation& value) { SetLocation(value); return *this;} /** * <p>A list of objects describing the Availability Zone and AWS Region of the * CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithLocation(ResourceLocation&& value) { SetLocation(std::move(value)); return *this;} /** * <p>The Lightsail resource type (e.g., * <code>CloudFormationStackRecord</code>).</p> */ inline const ResourceType& GetResourceType() const{ return m_resourceType; } /** * <p>The Lightsail resource type (e.g., * <code>CloudFormationStackRecord</code>).</p> */ inline bool ResourceTypeHasBeenSet() const { return m_resourceTypeHasBeenSet; } /** * <p>The Lightsail resource type (e.g., * <code>CloudFormationStackRecord</code>).</p> */ inline void SetResourceType(const ResourceType& value) { m_resourceTypeHasBeenSet = true; m_resourceType = value; } /** * <p>The Lightsail resource type (e.g., * <code>CloudFormationStackRecord</code>).</p> */ inline void SetResourceType(ResourceType&& value) { m_resourceTypeHasBeenSet = true; m_resourceType = std::move(value); } /** * <p>The Lightsail resource type (e.g., * <code>CloudFormationStackRecord</code>).</p> */ inline CloudFormationStackRecord& WithResourceType(const ResourceType& value) { SetResourceType(value); return *this;} /** * <p>The Lightsail resource type (e.g., * <code>CloudFormationStackRecord</code>).</p> */ inline CloudFormationStackRecord& WithResourceType(ResourceType&& value) { SetResourceType(std::move(value)); return *this;} /** * <p>The current state of the CloudFormation stack record.</p> */ inline const RecordState& GetState() const{ return m_state; } /** * <p>The current state of the CloudFormation stack record.</p> */ inline bool StateHasBeenSet() const { return m_stateHasBeenSet; } /** * <p>The current state of the CloudFormation stack record.</p> */ inline void SetState(const RecordState& value) { m_stateHasBeenSet = true; m_state = value; } /** * <p>The current state of the CloudFormation stack record.</p> */ inline void SetState(RecordState&& value) { m_stateHasBeenSet = true; m_state = std::move(value); } /** * <p>The current state of the CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithState(const RecordState& value) { SetState(value); return *this;} /** * <p>The current state of the CloudFormation stack record.</p> */ inline CloudFormationStackRecord& WithState(RecordState&& value) { SetState(std::move(value)); return *this;} /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline const Aws::Vector<CloudFormationStackRecordSourceInfo>& GetSourceInfo() const{ return m_sourceInfo; } /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline bool SourceInfoHasBeenSet() const { return m_sourceInfoHasBeenSet; } /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline void SetSourceInfo(const Aws::Vector<CloudFormationStackRecordSourceInfo>& value) { m_sourceInfoHasBeenSet = true; m_sourceInfo = value; } /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline void SetSourceInfo(Aws::Vector<CloudFormationStackRecordSourceInfo>&& value) { m_sourceInfoHasBeenSet = true; m_sourceInfo = std::move(value); } /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline CloudFormationStackRecord& WithSourceInfo(const Aws::Vector<CloudFormationStackRecordSourceInfo>& value) { SetSourceInfo(value); return *this;} /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline CloudFormationStackRecord& WithSourceInfo(Aws::Vector<CloudFormationStackRecordSourceInfo>&& value) { SetSourceInfo(std::move(value)); return *this;} /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline CloudFormationStackRecord& AddSourceInfo(const CloudFormationStackRecordSourceInfo& value) { m_sourceInfoHasBeenSet = true; m_sourceInfo.push_back(value); return *this; } /** * <p>A list of objects describing the source of the CloudFormation stack * record.</p> */ inline CloudFormationStackRecord& AddSourceInfo(CloudFormationStackRecordSourceInfo&& value) { m_sourceInfoHasBeenSet = true; m_sourceInfo.push_back(std::move(value)); return *this; } /** * <p>A list of objects describing the destination service, which is AWS * CloudFormation, and the Amazon Resource Name (ARN) of the AWS CloudFormation * stack.</p> */ inline const DestinationInfo& GetDestinationInfo() const{ return m_destinationInfo; } /** * <p>A list of objects describing the destination service, which is AWS * CloudFormation, and the Amazon Resource Name (ARN) of the AWS CloudFormation * stack.</p> */ inline bool DestinationInfoHasBeenSet() const { return m_destinationInfoHasBeenSet; } /** * <p>A list of objects describing the destination service, which is AWS * CloudFormation, and the Amazon Resource Name (ARN) of the AWS CloudFormation * stack.</p> */ inline void SetDestinationInfo(const DestinationInfo& value) { m_destinationInfoHasBeenSet = true; m_destinationInfo = value; } /** * <p>A list of objects describing the destination service, which is AWS * CloudFormation, and the Amazon Resource Name (ARN) of the AWS CloudFormation * stack.</p> */ inline void SetDestinationInfo(DestinationInfo&& value) { m_destinationInfoHasBeenSet = true; m_destinationInfo = std::move(value); } /** * <p>A list of objects describing the destination service, which is AWS * CloudFormation, and the Amazon Resource Name (ARN) of the AWS CloudFormation * stack.</p> */ inline CloudFormationStackRecord& WithDestinationInfo(const DestinationInfo& value) { SetDestinationInfo(value); return *this;} /** * <p>A list of objects describing the destination service, which is AWS * CloudFormation, and the Amazon Resource Name (ARN) of the AWS CloudFormation * stack.</p> */ inline CloudFormationStackRecord& WithDestinationInfo(DestinationInfo&& value) { SetDestinationInfo(std::move(value)); return *this;} private: Aws::String m_name; bool m_nameHasBeenSet; Aws::String m_arn; bool m_arnHasBeenSet; Aws::Utils::DateTime m_createdAt; bool m_createdAtHasBeenSet; ResourceLocation m_location; bool m_locationHasBeenSet; ResourceType m_resourceType; bool m_resourceTypeHasBeenSet; RecordState m_state; bool m_stateHasBeenSet; Aws::Vector<CloudFormationStackRecordSourceInfo> m_sourceInfo; bool m_sourceInfoHasBeenSet; DestinationInfo m_destinationInfo; bool m_destinationInfoHasBeenSet; }; } // namespace Model } // namespace Lightsail } // namespace Aws
37.145729
187
0.685471
[ "vector", "model" ]
3411e49c4e09727b503ce831a2a89d216773c83a
4,066
h
C
3rdParties/src/libmng/libmng-2.0.3/config.h
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
3rdParties/src/libmng/libmng-2.0.3/config.h
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
3rdParties/src/libmng/libmng-2.0.3/config.h
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
/* config.h. Generated from config.h.in by configure. */ /* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ /* #undef AC_APPLE_UNIVERSAL_BUILD */ /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* define if you want JPEG support */ #define HAVE_LIBJPEG 1 /* define if you want lcms v1 support */ /* #undef HAVE_LIBLCMS1 */ /* define if you want lcms v2 support */ #define HAVE_LIBLCMS2 1 /* Define to 1 if you have the `z' library (-lz). */ #define HAVE_LIBZ 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ //#undef HAVE_UNISTD_H /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* define if you want chunk access support */ #define MNG_ACCESS_CHUNKS 1 /* enable building standard shared object */ #define MNG_BUILD_SO 1 /* enable verbose error text */ #define MNG_ERROR_TELLTALE 1 /* define if you want full lcms support */ #define MNG_FULL_CMS 1 /* enable support for accessing chunks */ #define MNG_STORE_CHUNKS 1 /* define if you want display support */ #define MNG_SUPPORT_DISPLAY 1 /* define if you want dynamic support */ #define MNG_SUPPORT_DYNAMICMNG 1 /* define if you want full mng support */ #define MNG_SUPPORT_FULL 1 /* define if you want read support */ #define MNG_SUPPORT_READ 1 /* enable support for debug tracing */ /* #undef MNG_SUPPORT_TRACE */ /* define if you want write support */ #define MNG_SUPPORT_WRITE 1 /* enable support for debug messages */ /* #undef MNG_TRACE_TELLTALE */ /* but: libmng.dll (!) */ #define MNG_VERSION_DLL 2 /* MAJOR number of version */ #define MNG_VERSION_MAJOR 2 /* MINOR number of version */ #define MNG_VERSION_MINOR 0 /* PATCH number of version */ #define MNG_VERSION_RELEASE 3 /* eg. libmng.so.1 */ #define MNG_VERSION_SO 2 /* Name of package */ #define PACKAGE "libmng-2.0.3" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "png-mng-implement@lists.sourceforge.net" /* Define to the full name of this package. */ #define PACKAGE_NAME "libmng" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "libmng 2.0.3" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libmng-2.0.3" /* Define to the home page for this package. */ #define PACKAGE_URL "http://www.libmng.com/" /* Define to the version of this package. */ #define PACKAGE_VERSION "2.0.3" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ #define VERSION "2.0.3" /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN /* # undef WORDS_BIGENDIAN */ # endif #endif /* Enable large inode numbers on Mac OS X 10.5. */ #ifndef _DARWIN_USE_64_BIT_INODE # define _DARWIN_USE_64_BIT_INODE 1 #endif /* Number of bits in a file offset, on hosts where this is settable. */ /* #undef _FILE_OFFSET_BITS */ /* Define for large files, on AIX-style hosts. */ /* #undef _LARGE_FILES */ /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */
26.064103
78
0.721348
[ "object" ]
3413403ed7e48c4742033940e92f6d18a1010b86
677
h
C
include/curve_fitting/curve_fitting.h
Taka-Kazu/curve_fitting
2bbf5a6e728906e19d2b73fcbfe1ec6f4ce142fb
[ "MIT" ]
null
null
null
include/curve_fitting/curve_fitting.h
Taka-Kazu/curve_fitting
2bbf5a6e728906e19d2b73fcbfe1ec6f4ce142fb
[ "MIT" ]
null
null
null
include/curve_fitting/curve_fitting.h
Taka-Kazu/curve_fitting
2bbf5a6e728906e19d2b73fcbfe1ec6f4ce142fb
[ "MIT" ]
null
null
null
#ifndef __CURVE_FITTING_H #define __CURVE_FITTING_H #include <iostream> #include <vector> #include <cassert> #include <Eigen/Dense> #include <boost/optional.hpp> namespace curve_fitting { /* * 2D curve (parabola) fitting * This class calculates coefficients of 2D-parabola approximating given points. * x^2 + axy + by^2 + cx + dy + e = 0 * return a, b, c, d, e */ class CurveFitting2D { public: CurveFitting2D(void); std::vector<double> calculate(const std::vector<Eigen::Vector2d>&); double square(double); double cube(double); std::vector<double> get_y_from_x(const std::vector<double>&, double); protected: }; }; #endif// __CURVE_FITTING_H
18.297297
80
0.703102
[ "vector" ]
341d648a1a4299ca4245559f06cd878af4444635
23,437
h
C
include/rpg.h
AdlanSADOU/BlindJump
621b93d820f870ecb11f17cf0183a76a0bef0682
[ "Unlicense" ]
1
2020-10-17T22:50:28.000Z
2020-10-17T22:50:28.000Z
include/rpg.h
AdlanSADOU/BlindJump
621b93d820f870ecb11f17cf0183a76a0bef0682
[ "Unlicense" ]
null
null
null
include/rpg.h
AdlanSADOU/BlindJump
621b93d820f870ecb11f17cf0183a76a0bef0682
[ "Unlicense" ]
null
null
null
/* ** EPITECH PROJECT, 2020 ** MUL_my_rpg_2019 ** File description: ** rpg */ #ifndef RPG_H_ #define RPG_H_ #include <stdio.h> #include <stdlib.h> #include <io.h> #include <SFML/Network.h> #include <SFML/Graphics.h> #include <SFML/Audio.h> #include <SFML/System.h> #include <SFML/Window/Export.h> #include <SFML/Window/Types.h> #include <SFML/Graphics/Color.h> #include <SFML/Graphics/Rect.h> #include <SFML/Graphics/Transform.h> #include <SFML/System/Vector2.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <math.h> #include <time.h> #include <string.h> #include <stddef.h> #include <limits.h> #include "utils.h" #ifndef DEBUG_MODE #define DEBUG_MODE (0) #endif #ifndef MY_PI #define MY_PI (3.14159265358979323846) #endif /* !MY_PI */ #ifndef MENU #define MENU (0) #endif #ifndef SPAWN #define SPAWN (1) #endif #ifndef MAP #define MAP (2) #endif #ifndef GAME_OVER #define GAME_OVER (3) #endif #ifndef CUSTOM #define CUSTOM (4) #endif #ifndef OPT #define OPT (5) #endif #ifndef LOAD #define LOAD (6) #endif typedef struct statbox { sfRectangleShape *bg; sfRectangleShape *bg1; sfSprite *player; sfFont *font; sfText *p_name; sfText *xp; sfText *dmg; sfText *hp; sfText *lvl; sfText *xp_tx; sfText *dmg_tx; sfText *hp_tx; sfText *lvl_tx; sfText *speed; sfText *speed_tx; sfText *sh_speed; sfText *sh_speed_tx; sfText *lvl_up; char *dmg_str; char *speed_str; char *sh_speed_str; char *hp_str; char *lvl_str; } statbox_t; typedef struct chatbox { sfRectangleShape *box; sfText *text; sfFont *font; sfClock *clock; sfTime time; sfSprite *eric; sfTexture *eric_tx; float sec, s; int fd, idx, car, op; char *buff; } chatbox_t; typedef struct check_box { sfRectangleShape *box; int checked; int id; sfFont *font; sfText *text; sfVector2f pos; } check_box_t; typedef struct volume { sfRectangleShape *bar1; sfRectangleShape *bar2; int vol; sfSprite *left; sfSprite *right; sfTexture *right_tx; sfTexture *left_tx; } volume_t; typedef struct options { sfSprite *bg; sfTexture *bg_tx; volume_t s_volume; check_box_t fps[3]; struct menu_buttons *buttons; } options_t; typedef struct sounds { sfClock *clock; sfTime time; float seconds; int d; int fat_bool; sfMusic *music; sfSound *laser; sfSoundBuffer *laser_b; sfSound *tp; sfSoundBuffer *heart_b; sfSound *heart; sfSoundBuffer *tp_b; sfSound *item; sfSoundBuffer *item_b; sfSound *blast; sfSoundBuffer *blast_b; sfSound *creak; sfSoundBuffer *creak_b; sfSound *hit; sfSoundBuffer *hit_b; sfSound *dead; sfSoundBuffer *dead_b; sfSound *player; sfSoundBuffer *player_b; sfSound *lvl; sfSoundBuffer *lvl_b; sfSound *step1; sfSoundBuffer *step1_b; sfSound *step2; sfSoundBuffer *step2_b; sfSound *step3; sfSoundBuffer *step3_b; sfSound *step4; sfSoundBuffer *step4_b; sfSound *step5; sfSoundBuffer *step5_b; } sound_t; typedef struct game { sfRenderWindow *window; sfFont *font; sfFont *monospaced; sfEvent event; sfView *camera; sfClock *clock; sfTime time; sfShader *shader; sfRenderStates state; sfSprite *black; sfTexture *black_tx; float seconds; sfClock *clock_button; sfText *the_stage; sfText *mob_left; sfTime time_button; float seconds_button; int scene; int debug_mode; int nb; sfText *quest; int display_inv; int pause; int level_up; sfClock *lvl_clk; sfTime lvl_time; float lvl_seconds; char key_press; sfSprite *menu; sfTexture *arrow; sfTexture *menu_tx; int fps; int stage_script; float volume; int tp_chat; int chat; sfTexture *hearth_tx; } game_t; typedef struct menu_buttons { sfSprite *sprite; sfTexture *button1; sfTexture *button2; sfVector2f position; int id; struct menu_buttons *next; } m_buttons_t; typedef struct rgb { sfRectangleShape *rect; int value; char id; sfSprite *right; sfSprite *left; sfSprite *cursor; sfTexture *right_tx; sfTexture *left_tx; sfTexture *cursor_tx; struct rgb *next; } rgb_t; typedef struct custom { sfText *select_name; sfText *title_hero; sfText *enter; sfRectangleShape *input; sfSprite *sprite; sfTexture *texture; sfSprite *hero; sfTexture *hero_tx; sfVector2f pos; sfClock *clock; sfTime time; sfColor p_color; int r, g, b; float seconds; int show; } custom_t; typedef struct direction { int up; int down; int left; int right; } direction_t; typedef struct movement { int up; int down; int left; int right; int wall_up; int wall_down; int wall_right; int wall_left; } movement_t; typedef struct bullet_mob { sfSprite *bullet; sfVector2f pos; int shoot; float bullet_speed; int check_shoot; float vx, vy; float normalize; int bullet_travel; int hit; sfClock *shoot_clock; sfTime shoot_time; float shoot_seconds; struct bullet_mob *next; } b_mob_t; typedef struct mob { sfSprite *mob; sfTexture *mob_txt; sfVector2f mob_pos; int speed; sfClock *clock, *refresh_clk; sfTime time, refresh_tm; float seconds, refresh_sec; sfClock *rect_clock; sfTime rect_time; float rect_seconds; sfIntRect rect; sfClock *shoot_clock; sfTime shoot_time; float shoot_seconds; sfText *text; char *name, *strlvl; sfSprite *shadow; sfTexture *shadow_tx; sfVector2f shadow_pos; int move, status; char type, prev; int x, y, hor, ver, xp; char **path; struct mob *next; int aggro, hp, lvl; sfSprite *bullet; int shoot; float bullet_speed; int check_shoot; float vx, vy; float normalize; int bullet_travel; int hit; b_mob_t *l_bullets; } mob_t; typedef struct p_infos { sfRectangleShape *xp; sfRectangleShape *xp_base; sfRectangleShape *hp; sfRectangleShape *hp_base; sfClock *clock; sfClock *hit_clk; sfTime time, hit_tm; int is_hit, is_color; float seconds, hit_sec; char *p_name; char *str_xp; char *str_current_xp; char *str_max_xp; char *str_hp; int current_xp, max_xp, level, dmg, max_hp, current_hp; int max_hp_save, save_dmg; char *str_level; float atk_speed; sfText *xp_txt; sfText *hp_txt; sfText *heath; sfText *lvl_txt; sfText *game_over; sfText *p_name_txt; } p_infos_t; typedef struct player { sfVector2f save_pos; sfRectangleShape *debug; sfRectangleShape *debug_shadow; sfSprite *hero, *hit_sprite; int up, down, left, right, range, hit; sfSprite *ver_shoot; sfSprite *hor_shoot; sfTexture *hit_txt; sfTexture *ver_shoot_txt; sfTexture *hor_shoot_txt; char *heal; sfTexture *hero_tx; sfVector2f hero_pos, shoot_pos, hor_pos, ver_pos, hit_pos; sfClock *heal_clk; sfTime heal_tim; float heal_sec; int shoot_speed; int save_speed; int space; int fast_shoot; int hero_speed, ver, hor, shooting; sfClock *hero_clock, *hit_clk, *reload_clk; sfTime hero_time, hit_tm, reload_tm; float hero_seconds, refresh_sec, shoot_sec, hit_sec, reload_sec; sfClock *rect_clock, *refresh_clk, *shoot_clk; sfTime rect_time, refresh_tm, shoot_tm; float rect_seconds; sfIntRect hero_rect, hit_rect; sfSprite *shadow; sfTexture *shadow_tx; sfVector2f shadow_pos; sfSprite *gun; int tp, x, y; } player_t; typedef struct stars { sfRenderTexture *render1; sfRenderTexture *render2; sfSprite *front; sfSprite *back; sfTexture *front_tx; sfTexture *back_tx; sfVector2f pos; sfVector2f pos2; } stars_t; typedef struct load { sfSprite *hero; sfSprite *button; sfTexture *hero_tx; sfTexture *hover; sfTexture *click; sfTexture *normal; sfColor color; int id, fion; sfText *level_tx; sfText *p_name_tx; sfVector2f pos; struct load *next; } load_t; typedef struct save { sfSprite *button; sfTexture *normal; sfTexture *hover; sfTexture *clicked; sfText *description; int id, fion; char *filepath; struct save *next; } save_t; typedef struct npc { sfSprite *computer; sfVector2f pos_pc; sfSprite *screen; sfText *talk_text; int talk; } npc_t; typedef struct spawn { sfSprite *ground; sfTexture *ground_tx; sfVector2f ground_pos; sfSprite *mask; sfTexture *mask_tx; sfVector2f mask_pos; sfSprite *door; sfTexture *door_tx; sfVector2f door_pos; sfSprite *ship; sfVector2f ship_pos; sfRectangleShape *background; int open; sfClock *door_clock; sfTime door_time; float door_seconds; } spawn_t; typedef struct dead { sfSprite *dead; sfTexture *dead_tx; sfText *respawn; sfVector2f pos; sfClock *clock; sfTime time; float seconds; int fuck; sfIntRect rect; } dead_t; typedef struct explode { sfSprite *sprite; sfTexture *texture; sfClock *clock; sfTime time; sfIntRect rect; sfVector2f pos; int show; float seconds; } explode_t; typedef struct tileset { sfRectangleShape *debug; sfSprite *tile; sfSprite *top; sfSprite *bottom; sfSprite *grass; } tileset_t; typedef struct map { sfSprite *background; sfTexture *background_tx; sfVector2f background_pos; sfVector2f tileset_pos; sfTexture *tileset_tx; sfTexture *grass_tx; sfTexture *grass2_tx; tileset_t **tileset; sfRenderTexture *render; const sfTexture *map_texture; sfSprite *map_sprite; char **map; char **grass; int x; int y; int stage; } map_t; typedef struct chest { sfSprite *sprite; sfSprite *shadow; sfTexture *texture; sfVector2f pos; sfIntRect rect; sfClock *clock; sfTime time; float seconds; int status; sfText *open_txt; struct chest *next; } chest_t; typedef struct mob_pos { sfClock *clock; sfTime time; float seconds; int x, y; } mob_pos_t; typedef struct effect { sfRenderStates *light_state; sfSprite *light; sfTexture *light_tx; sfVector2f light_pos; sfRenderStates *vignette_state; sfSprite *vignette1; // @vignette1 & @vignette2: screen overlays sfTexture *vignette1_tx; sfSprite *vignette2; sfTexture *vignette2_tx; sfVector2f vignette_pos; sfSprite *tp_glow; sfTexture *tp_glow_tx; sfClock *clock; sfTime time; float seconds; int anim; } effect_t; typedef struct minimap { sfSprite *sprite; sfRectangleShape *black; sfCircleShape *player; sfCircleShape *tp; int dispay_tp; } minimap_t; typedef struct teleporter { sfSprite *tp; sfVector2f tp_pos; sfSprite *tp_shadow; sfRectangleShape *debug; sfRectangleShape *beam; sfClock *tp_clock; sfTime tp_time; sfRectangleShape *black; float tp_seconds; int alpha; int height; int anim; int width; } tp_t; typedef struct slots { sfSprite *slot; int drag; int is_item; int id; int health; int dmg; int equip; int slot_nb; sfSprite *item; sfSprite *under; struct slots *next; } slots_t; typedef struct inventory { sfRectangleShape *inv_back; sfTexture *selected_tx; sfSprite *selected; sfSprite *trash; sfTexture *pistol; sfTexture *scarh; sfTexture *sniper; sfTexture *scorpion; sfTexture *trash_tx; sfTexture *armors_tx; sfTexture *slot_tx; slots_t *dragged; slots_t *head; sfText *infos_text; sfRectangleShape *infos; int swap; int drag; } inventory_t; typedef struct hearth { int life; int show; sfSprite *hearth; struct hearth *next; } hearth_t; typedef struct cinematic { int script; int cinematic; sfClock *clock; sfTime time; float seconds; int door; int tuto; int move; int count; } cinematic_t; typedef struct all { game_t s_game; npc_t s_npc; m_buttons_t *s_buttons; m_buttons_t *s_pause; tp_t s_tp; hearth_t *s_life; p_infos_t s_infos; explode_t s_explode; map_t s_map; effect_t s_effect; movement_t s_movement; player_t s_player; custom_t s_custom; cinematic_t s_cine; direction_t s_direction; spawn_t s_spawn; minimap_t s_minimap; mob_pos_t s_mob_pos; inventory_t s_inventory; dead_t s_dead; options_t s_options; chatbox_t s_chatbox; stars_t s_stars; sound_t s_sounds; struct save *s_save; struct rgb *s_rgb; struct mob *s_mob; struct chest *s_chest; struct load *s_load; statbox_t s_statbox; } all_t; void convert_mouse_coordinates(sfRenderWindow *window, sfVector2i *mouse_pos); void set_volume(all_t *s_all); void quest_display(all_t *s_all); void free_all_mobs(all_t *s_all); void stage_cinematic(all_t *s_all); int check_if_full(all_t *s_all); int check_chest_turret_overlap(all_t *s_all); void pop_front_chest(all_t *s_all); void free_load_slots(all_t *s_all); void free_chest(all_t *s_all); void free_inventory(all_t *s_all); void clean_game2(all_t *s_all); void clean_game(all_t *s_all); void load3(all_t *s_all); void init_buttons_pause(all_t *s_all); void dispay_buttons_pause(all_t *s_all, m_buttons_t *buttons); void cinematic1(all_t *s_all); void color_hp(all_t *s_all); void slow_heal_player(all_t *s_all); int drop_check(all_t *s_all, slots_t *tmp); void set_equip_stats(all_t *s_all); int move_stars3(all_t *s_all, sfSprite *sprite, float speed, sfVector2f *pos); int move_stars2(all_t *s_all, sfSprite *sprite, float speed, sfVector2f *pos); void display_inventory_inf(all_t *s_all, int check); void init_equip_slots(all_t *s_all); void swap_items(all_t *s_all, slots_t *tmp); void set_texture_items2(slots_t *tmp, int id); void init_sounds(all_t *s_all); void free_hearth(all_t *s_all); void heal_hp(all_t *s_all); void display_hearth2(all_t *s_all); void destroy_sounds(all_t *s_all); void display_hearth(all_t *s_all); void push_front_hearth(all_t *s_all, mob_t *tmp); void init_chatbox2(all_t *s_all); void computer_event(all_t *s_all); float calcul_sprite_magnitude(sfSprite *sprite1, sfSprite *sprite2); void slide_hover(m_buttons_t *tmp, sfVector2i mouse); void init_computer(all_t *s_all); void display_computer(all_t *s_all); void shoot3(all_t *s_all); void display_stars(all_t *s_all); void turret_aim(int i, mob_t *temp, b_mob_t *bullet); void init_stars(all_t *s_all); void turret_loop(all_t *s_all, mob_t *temp); void turret_init(mob_t *new, char type, all_t *s_all); void turret(all_t *s_all); void generate_random_mobs3(all_t *s_all); void display_mobs_death_under(all_t *s_all); void display_mobs_death_over(all_t *s_all); void display_mobs4(all_t *s_all); void move_mobs_rect(mob_t *mob, int max, int offset, int reset); void roballs_shoot(mob_t *tmp, all_t *s_all); void display_mobs3(mob_t *temp, all_t *s_all); void roballs(mob_t *new, char type, sfVector2f pos, all_t *s_all); void display_minimap(all_t *s_all); void dispay_buttons(all_t *s_all, m_buttons_t *buttons); void init_buttons(all_t *s_all); void init_inventory(all_t *s_all); void display_inventory(all_t *s_all); void init_all(all_t *s_all); void init_clocks(all_t *s_all); void game_clocks(all_t *s_all); void display(all_t *s_all); int game_loop(all_t *s_all); void init_mobs(all_t *s_all); void display_mobs(all_t *s_all); int my_ptrlen(char **str); void events_control(all_t *s_all); void create_sprite(sfSprite **sprite, sfTexture **texture, sfVector2f pos, const char *path); void display_hero(all_t *s_all); void init_hero(all_t *s_all); sfVector2f render_pos_center(all_t *s_all); void init_explosions(all_t *s_all); void player_movement(all_t *s_all); void init_rgb_selector(all_t *s_all); void display_rgb_selector(all_t *s_all); void init_load_slots(all_t *s_all); void display_load_slots(all_t *s_all); void init_movement(all_t *s_all); void display_infos(all_t *s_all); void generate_random_mobs(all_t *s_all); mob_t *fill_mob(mob_t *old, char type, sfVector2f pos, all_t *s_all); void get_movement(all_t *s_all); void info_clocks(all_t *s_all); void display_explosions(all_t *s_all); void init_mob_interface(mob_t *new, char type, all_t *s_all); void move_explosion(all_t *s_all); void movement_up_down(all_t *s_all); void init_dead(all_t *s_all); void display_dead(all_t *s_all); void display_chests_over(all_t *s_all, int y); void display_mobs2(mob_t *temp, all_t *s_all); void loosing_hp(all_t *s_all); int display_chests_under(all_t *s_all); void movement_left_right(all_t *s_all); void save_inventory(int fd, all_t *s_all); void load_inventory(int fd, all_t *s_all); void update_xp(all_t *s_all); void movement_diagonal_left_up(all_t *s_all); void movement_diagonal_left_down(all_t *s_all); void movement_diagonal_right_down(all_t *s_all); void play_random_sound(all_t *s_all); void movement_diagonal_right_up(all_t *s_all); void rect_hero(all_t *s_all); void init_infos(all_t *s_all); void player_immunity(all_t *s_all); void display_hit(all_t *s_all); sfRectangleShape *init_hitbox_debug(sfRectangleShape *rectangle, sfVector2f pos, sfSprite *sprite); void display_hitbox_debug(all_t *s_all, sfRectangleShape *rectangle, sfSprite *sprite); void set_position_debug(sfRectangleShape *rectangle, sfVector2f pos); void activate_debug_mode(all_t *s_all); void init_direction(all_t *s_all); void get_text_entered(all_t *s_all); void get_aim_direction(all_t *s_all); int rect_down(all_t *s_all, int *check, int *i); void gaining_hp(all_t *s_all, int hp); int rect_up(all_t *s_all, int *check, int *i); int rect_left(all_t *s_all, int *check, int *i); int rect_right(all_t *s_all, int *check, int *i); int rect_down_condition(all_t *s_all, int *check, int *i); int rect_up_condition(all_t *s_all, int *check, int *i); int rect_left_condition(all_t *s_all, int *check, int *i); int rect_right_condition(all_t *s_all, int *check, int *i); void init_spawn(all_t *s_all); void check_mob_hitboxes(all_t *s_all); void move_hit(all_t *s_all); void destroy_mobs(all_t *s_all); void display_spawn_under(all_t *s_all); void display_spawn_over(all_t *s_all); void move_camera(all_t *s_all); int check_borders(all_t *s_all); int check_middle_wall(all_t *s_all); void game_over_check(all_t *s_all); void save(all_t *s_all, char *filepath); void load(all_t *s_all, char *filepath); void init_save_screen(all_t *s_all); void display_save_slots(all_t *s_all); void display_debug(all_t *s_all); int check_ship(all_t *s_all); void init_effect(all_t *s_all); void display_light_spawn(all_t *s_all); void init_view(all_t *s_all); void init_tp(all_t *s_all); void tp_animation(all_t *s_all); void init_custom(all_t *s_all); void respawn(all_t *s_all); void display_custom(all_t *s_all); void door_animation(all_t *s_all); void set_iddle_rect(all_t *s_all); int hitbox_tp(all_t *s_all); void init_map(all_t *s_all); void reset_wall(all_t *s_all); void shoot(all_t *s_all); void shoot2(all_t *s_all); void shooting_control(all_t *s_all); void display_map(all_t *s_all); int loop_map_hitbox(all_t *s_all); char **init_new_random_map(all_t *s_all); void free_map(char **map); char **create_map(int x, int y); void moove_rgb_cursor_left(all_t *s_all, rgb_t *temp); void moove_rgb_cursor_right(all_t *s_all, rgb_t *temp); void enter_event(all_t *s_all); void display_tiles(all_t *s_all); void generate_random_map(all_t *s_all); void display_game_over(all_t *s_all); char **init_new_random_map(all_t *s_all); void fill_random_map(char **map); char **copy_map(char **old_map); void simulation_step(char **old_map, char **new_map); void set_rect_tile(tileset_t *tile, all_t *s_all, int i, int j); void put_tp(char **map); void set_tp_position(all_t *s_all); chest_t *fill_chests(chest_t *old, all_t *s_all, sfVector2f pos); sfVector2f find_tp_spawn(all_t *s_all); char **init_new_gass_map(all_t *s_all); void set_grass(tileset_t *tile, all_t *s_all, int i, int j); sfVector2i find_pos(all_t *s_all, char entity); void create_map_sprite(all_t *s_all); float calcul_mob_magnitude(mob_t *temp, sfSprite *sprite); float calcul_chest_magnitude(chest_t *temp, sfSprite *sprite); int loop_chest_hitbox(all_t *s_all); void chest_message(all_t *s_all); void init_minimap(all_t *s_all); sfBool is_key_released(sfEvent *e, sfKeyCode key); void put_item_in_slot(all_t *s_all, int id); void slot_click(all_t *s_all, slots_t *tmp); void drag_item(all_t *s_all); void set_texture_items(slots_t *tmp, int id, all_t *s_all); void init_options(all_t *s_all); void draw_options(all_t *s_all); check_box_t create_check_box(int id, sfVector2f pos); void init_fps(all_t *s_all); void draw_fps(all_t *s_all); int click_box(all_t *s_all, check_box_t box); void change_check(all_t *s_all, check_box_t fps[], int i); void init_volume1(all_t *s_all); void init_volume2(all_t *s_all); int check_right(all_t *s_all); int check_left(all_t *s_all); void adjust_volume(all_t *s_all); void draw_volume(all_t *s_all); void chatbox(all_t *s_all, char *filepath); int start_dialog(all_t *s_all, char *filepath); void init_chatbox(all_t *s_all); int add_letter(int fd, int idx, char *buf, all_t *s_all); void add_text(all_t *s_all, char *buf); void dialog_time(all_t *s_all); int quit_dialog(all_t *s_all); void open_file(all_t *s_all, char *filepath); int read_chat_file(all_t *s_all); int wait_close(all_t *s_all); void init_stat_box(all_t *s_all); void draw_stats(all_t *s_all); void update_statbox(all_t *s_all); void stat_create(all_t *s_all); void stat_text(all_t *s_all); void stat_text1(all_t *s_all); void stat_text2(all_t *s_all); void set_stat_text(all_t *s_all); void draw_stats1(all_t *s_all); /* ------------ !QUEUE ------------ */ typedef struct node_queue { int x; int y; struct node_queue *parent; struct node_queue *next; struct node_queue *back; } queue_node_t; typedef struct queue { int length; queue_node_t *last; queue_node_t *first; } queue_t; queue_t *new_queue(void); int is_empty_queue(queue_t *li); queue_node_t *new_queue_node(queue_node_t *parent, int x, int y); queue_t *push_back_queue(queue_t *li, queue_node_t *parent, int x, int y); queue_t *pop_front_queue(queue_t *li); queue_t *clear_queue(queue_t *li); queue_t *dequeue_front(queue_t *li, queue_t **dequeue); queue_t *push_new_generation(char **maze, queue_t *s_queue, queue_t **s_dequeue); int check_if_found(queue_t *s_queue, sfVector2i pos_end); /* ------------ !BREADTH_FIRST_SEARCH ------------ */ int breadth_first_search(char **maze, all_t *s_all, char start, char end); char **breadth_first_search_entity(char **maze, all_t *s_all, int x, int y); void format_map(char **map); /* ------------ !MOBS PATHFINDING ------------ */ void refresh_path(all_t *s_all); void move_mob_up(mob_t *node, all_t *s_a_ll); void move_mob_right(mob_t *node, all_t *s_all); void move_mob_down(mob_t *node, all_t *s_all); void move_mob_left(mob_t *node, all_t *s_all); void search_mob_path(mob_t *node, all_t *s_all); void refresh_path_to_player(all_t *s_all); #endif /* !RPG_H_ */
25.255388
83
0.709306
[ "render", "transform" ]
34220a8703e8d1bf20150889088a2fecf0f6134d
2,950
h
C
Data/MySQL/include/Poco/Data/MySQL/SessionHandle.h
flachesis/poco
5b911e4191f6f5a5cf18c1d2af3d51b0b678b219
[ "BSL-1.0" ]
1
2020-04-09T18:58:35.000Z
2020-04-09T18:58:35.000Z
Data/MySQL/include/Poco/Data/MySQL/SessionHandle.h
byteman/poco
f0f7f0fd3ce0ae3098de075a9c36bbd2f2ed0a13
[ "BSL-1.0" ]
null
null
null
Data/MySQL/include/Poco/Data/MySQL/SessionHandle.h
byteman/poco
f0f7f0fd3ce0ae3098de075a9c36bbd2f2ed0a13
[ "BSL-1.0" ]
null
null
null
// // SesssionHandle.h // // $Id: //poco/1.4/Data/MySQL/include/Poco/Data/MySQL/SessionHandle.h#1 $ // // Library: Data // Package: MySQL // Module: SessionHandle // // Definition of the SessionHandle class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_SessionHandle_INCLUDED #define Data_MySQL_SessionHandle_INCLUDED #include <mysql.h> #include "Poco/Data/MySQL/MySQLException.h" #include <vector> namespace Poco { namespace Data { namespace MySQL { class SessionHandle /// MySQL session handle { public: explicit SessionHandle(MYSQL* mysql); /// Creates session handle ~SessionHandle(); /// Destroy handle, close connection void init(MYSQL* mysql = 0); /// Initializes the handle iff not initialized. void options(mysql_option opt); /// Set connection options void options(mysql_option opt, bool b); /// Set connection options void options(mysql_option opt, unsigned int i); /// Set connection options void connect(const char* host, const char* user, const char* password, const char* db, unsigned int port); /// Connect to server void close(); /// Close connection void startTransaction(); /// Start transaction void commit(); /// Commit transaction void rollback(); /// Rollback trabsaction operator MYSQL* (); private: SessionHandle(const SessionHandle&); SessionHandle& operator=(const SessionHandle&); private: MYSQL* _pHandle; }; // // inlines // inline SessionHandle::operator MYSQL* () { return _pHandle; } }}} #endif // Data_MySQL_SessionHandle_INCLUDED
25.652174
107
0.741695
[ "object", "vector" ]
34369d8bb92e7140387e23de07052696f9cb1a6d
2,012
h
C
nau/src/nau/material/iBuffer.h
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
29
2015-09-16T22:28:30.000Z
2022-03-11T02:57:36.000Z
nau/src/nau/material/iBuffer.h
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
1
2017-03-29T13:32:58.000Z
2017-03-31T13:56:03.000Z
nau/src/nau/material/iBuffer.h
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
10
2015-10-15T14:20:15.000Z
2022-02-17T10:37:29.000Z
#include "nau/config.h" #ifndef IBUFFER_H #define IBUFFER_H #include "nau/attribute.h" #include "nau/attributeValues.h" #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include <cmath> #include <string> using namespace nau; namespace nau { namespace resource { class ResourceManager; }; namespace material { class IBuffer : public AttributeValues { friend class nau::resource::ResourceManager; public: INT_PROP(ID,0); UINT_PROP(SIZE, 0); UINT_PROP(STRUCT_SIZE, 1); ENUM_PROP(CLEAR, 0); UINT3_PROP(DIM, 0); typedef enum CV{ NEVER, BY_FRAME } ClearValues; static AttribSet Attribs; static nau_API AttribSet &GetAttribs(); // Note: no validation is performed! nau_API virtual void setPropui(UIntProperty prop, unsigned int value) = 0; nau_API virtual void setPropui3(UInt3Property prop, uivec3 &v) = 0; nau_API std::string& getLabel (void); nau_API virtual void setData(size_t size, void *data) = 0; nau_API virtual void setSubData(size_t offset, size_t size, void*data) = 0; nau_API virtual void setSubDataNoBinding(unsigned int bufferType, size_t offset, size_t size, void*data) = 0; // returns the number of bytes read nau_API virtual size_t getData(size_t offset, size_t size, void *data) = 0; virtual void bind(unsigned int type) = 0; virtual void unbind() =0; nau_API virtual void clear() = 0; nau_API virtual IBuffer * clone() = 0; // Only useful for GUIs nau_API void setStructure(std::vector<Enums::DataType>); nau_API std::vector<Enums::DataType> &getStructure(); virtual void refreshBufferParameters() = 0; nau_API void appendItemToStruct(Enums::DataType); ~IBuffer(void) {}; protected: static IBuffer* Create(std::string label); IBuffer() : m_Label("") { registerAndInitArrays(Attribs); }; static bool Init(); static bool Inited; std::string m_Label; std::vector<Enums::DataType> m_Structure; }; }; }; #endif // IBUFFER_H
20.742268
112
0.699304
[ "vector" ]
343a531e8aa06fb4892839a9ba9157a9838c302d
5,477
c
C
mapscript/php/labelleader.c
sbrunner/mapserver
dca4eb117f1673dc06a3386159e3ed640af8e007
[ "Unlicense" ]
2
2020-02-24T18:30:25.000Z
2021-06-02T14:55:09.000Z
mapscript/php/labelleader.c
sbrunner/mapserver
dca4eb117f1673dc06a3386159e3ed640af8e007
[ "Unlicense" ]
6
2018-08-17T13:03:30.000Z
2018-08-17T13:26:31.000Z
mapscript/php/labelleader.c
sbrunner/mapserver
dca4eb117f1673dc06a3386159e3ed640af8e007
[ "Unlicense" ]
1
2018-09-08T17:51:17.000Z
2018-09-08T17:51:17.000Z
/********************************************************************** * Project: MapServer * Purpose: PHP/MapScript extension for MapServer. External interface * functions * Author: Daniel Morissette, DM Solutions Group (dmorissette@dmsolutions.ca) * Alan Boudreault, Mapgears * ********************************************************************** * Copyright (c) 2000-2010, Daniel Morissette, DM Solutions Group Inc. * * 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 of this Software or works derived from this 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. **********************************************************************/ #include "php_mapscript.h" zend_class_entry *mapscript_ce_labelleader; ZEND_BEGIN_ARG_INFO_EX(labelleader___get_args, 0, 0, 1) ZEND_ARG_INFO(0, property) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(labelleader___set_args, 0, 0, 2) ZEND_ARG_INFO(0, property) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() /* {{{ proto labelleader __construct() labelLeaderObj CANNOT be instanciated, this will throw an exception on use */ PHP_METHOD(labelLeaderObj, __construct) { mapscript_throw_exception("labelLeaderObj cannot be constructed" TSRMLS_CC); } /* }}} */ PHP_METHOD(labelLeaderObj, __get) { char *property; long property_len = 0; zval *zobj = getThis(); php_labelleader_object *php_labelleader; PHP_MAPSCRIPT_ERROR_HANDLING(TRUE); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &property, &property_len) == FAILURE) { PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE); return; } PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE); php_labelleader = (php_labelleader_object *) zend_object_store_get_object(zobj TSRMLS_CC); IF_GET_LONG("maxdistance", php_labelleader->labelleader->maxdistance) else IF_GET_LONG("gridstep", php_labelleader->labelleader->gridstep) else { mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property); } } PHP_METHOD(labelLeaderObj, __set) { char *property; long property_len = 0; zval *value; PHP_MAPSCRIPT_ERROR_HANDLING(TRUE); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &property, &property_len, &value) == FAILURE) { PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE); return; } PHP_MAPSCRIPT_RESTORE_ERRORS(TRUE); if ( (STRING_EQUAL("maxdistance", property)) || (STRING_EQUAL("gridstep", property)) ) { mapscript_throw_exception("Property '%s' is read-only and cannot be set." TSRMLS_CC, property); } else { mapscript_throw_exception("Property '%s' does not exist in this object." TSRMLS_CC, property); } } zend_function_entry labelleader_functions[] = { PHP_ME(labelLeaderObj, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(labelLeaderObj, __get, labelleader___get_args, ZEND_ACC_PUBLIC) PHP_ME(labelLeaderObj, __set, labelleader___set_args, ZEND_ACC_PUBLIC) { NULL, NULL, NULL } }; void mapscript_create_labelleader(labelLeaderObj *labelleader, parent_object parent, zval *return_value TSRMLS_DC) { php_labelleader_object * php_labelleader; object_init_ex(return_value, mapscript_ce_labelleader); php_labelleader = (php_labelleader_object *)zend_object_store_get_object(return_value TSRMLS_CC); php_labelleader->labelleader = labelleader; php_labelleader->parent = parent; MAPSCRIPT_ADDREF(parent.val); } static void mapscript_labelleader_object_destroy(void *object TSRMLS_DC) { php_labelleader_object *php_labelleader = (php_labelleader_object *)object; MAPSCRIPT_FREE_OBJECT(php_labelleader); MAPSCRIPT_FREE_PARENT(php_labelleader->parent); /* We don't need to free the labelLeaderObj */ efree(object); } static zend_object_value mapscript_labelleader_object_new(zend_class_entry *ce TSRMLS_DC) { zend_object_value retval; php_labelleader_object *php_labelleader; MAPSCRIPT_ALLOC_OBJECT(php_labelleader, php_labelleader_object); retval = mapscript_object_new(&php_labelleader->std, ce, &mapscript_labelleader_object_destroy TSRMLS_CC); MAPSCRIPT_INIT_PARENT(php_labelleader->parent); return retval; } PHP_MINIT_FUNCTION(labelleader) { zend_class_entry ce; MAPSCRIPT_REGISTER_CLASS("labelLeaderObj", labelleader_functions, mapscript_ce_labelleader, mapscript_labelleader_object_new); mapscript_ce_labelleader->ce_flags |= ZEND_ACC_FINAL_CLASS; return SUCCESS; }
34.88535
114
0.72065
[ "object" ]
343c265691efc8de05aed303f50bff3da96c76ce
1,918
h
C
src/sitemapservice/robotstxtfilter.h
Valiklviv/googlesitemapgenerator
21fbda5bc97fa2725ed2618a26dc52407a8f2988
[ "Apache-2.0" ]
1
2015-05-06T22:10:36.000Z
2015-05-06T22:10:36.000Z
src/sitemapservice/robotstxtfilter.h
Valiklviv/googlesitemapgenerator
21fbda5bc97fa2725ed2618a26dc52407a8f2988
[ "Apache-2.0" ]
null
null
null
src/sitemapservice/robotstxtfilter.h
Valiklviv/googlesitemapgenerator
21fbda5bc97fa2725ed2618a26dc52407a8f2988
[ "Apache-2.0" ]
2
2020-10-03T03:23:40.000Z
2021-10-16T06:34:36.000Z
// Copyright 2009 Google Inc. // // 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. // This class filters URL according to robots.txt. // It follows http://www.robotstxt.org/norobots-rfc.txt, but not so strict. // 1) "User-agent", "Allow", "Disallow" is case insensitive. // 2) No special handling on robots.txt itself. // It is assumed that a valid robots.txt is given. The result in un-expected // if the robots.txt is malformed. // This class is thread-safe after it is initialized. #ifndef SITEMAPSERVICE_ROBOTSTXTFILTER_H__ #define SITEMAPSERVICE_ROBOTSTXTFILTER_H__ #include "sitemapservice/urlfilter.h" #include <string> #include <utility> #include <vector> class RobotsTxtFilter : public UrlFilter { public: RobotsTxtFilter() {} virtual ~RobotsTxtFilter() {} // Initialize with given path, like "/var/www/robots.txt" // Error is ignored and logged. void Initialize(const char* path); // Returns true if the url is allowed by robots.txt. bool Accept(const char* url) { return Accept(url, static_cast<int>(strlen(url))); } // Returns true if the url is allowed by robots.txt. virtual bool Accept(const char* url, int urllen); private: // "Allow" and "Disallow" rules. // rules_[i].first: the flag for Allow/Disallow. // rules_[i].second: the actual rule string. std::vector<std::pair<bool, std::string> > rules_; }; #endif // SITEMAPSERVICE_ROBOTSTXTFILTER_H__
31.966667
76
0.728884
[ "vector" ]
344506ff16c156b34b9bd79dc40e1597168805db
9,087
h
C
robotics/IKFunctions.h
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
57
2015-05-07T18:07:11.000Z
2022-03-18T18:44:39.000Z
robotics/IKFunctions.h
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
7
2018-12-10T21:46:52.000Z
2022-01-20T19:49:11.000Z
robotics/IKFunctions.h
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
36
2015-01-10T18:36:45.000Z
2022-01-20T19:49:24.000Z
#ifndef ROBOTICS_IK_FUNCTIONS_H #define ROBOTICS_IK_FUNCTIONS_H #include "RobotKinematics3D.h" #include "IK.h" #include <KrisLibrary/math/vectorfunction.h> #include <KrisLibrary/optimization/Newton.h> #include <KrisLibrary/utils/ArrayMapping.h> #include <KrisLibrary/utils/DirtyData.h> /** @file IKFunctions.h * @ingroup Kinematics * @brief Helper classes and functions for solving iterative inverse * kinematics problems. */ /** @addtogroup Kinematics */ /*@{*/ /** @brief A vector field function class defining C(q)=0 for IK. * * Composes several individual IK functions together using their * cartesian product. Add a function to C using the UseX() methods. * * Optionally, this can use only a subset of the dimensions of q * which might accelerate the computation of Jacobians in the IK iteration. * This is done using the activeDofs member, which provides a mapping from * q' (the reduced configuration) to q (the full configuration). * * Warning: the UseIK functions store POINTERS to IKGoal's, so you must maintain * the structures throughout the life of this struct. */ struct RobotIKFunction : public CompositeVectorFieldFunction { RobotIKFunction(RobotKinematics3D&); ~RobotIKFunction(); void UseIK(const std::vector<IKGoal>& g); void UseIK(const IKGoal& g); void UseCOM(const Vector2& comGoal); void Clear(); void SetState(const Vector& x) const; void GetState(Vector& x) const; virtual void PreEval(const Vector& x); RobotKinematics3D& robot; ArrayMapping activeDofs; //vector<Real> scaleDofs; TODO? enable scaling of dofs }; /** @brief A Newton-Raphson robot IK solver. * * Joint limits are optionally included if the UseJointLimits() functions * are called. Typically, the first version is called. * * A bias configuration can be explicitly set using the UseBiasConfiguration() * function. The solver will seek toward this configuration during the solve. * * Optionally, a Real parameter may specify a threshold t such that * a revolute joint's limits are included only if the angular range is less * than t. Specifying a value less than 2pi is useful to avoid local minima * for joints with wide ranges, because it allows the joint angle to pass from * -pi to pi, and vice versa. */ struct RobotIKSolver { RobotIKSolver(RobotIKFunction& function); void UseJointLimits(Real revJointThreshold = Inf); void UseJointLimits(const Vector& qmin,const Vector& qmax); void UseBiasConfiguration(const Vector& qdesired); void ClearJointLimits(); void RobotToState(); void StateToRobot(); bool Solve(Real tolerance,int& iters); void PrintStats(); Optimization::NewtonRoot solver; RobotIKFunction& function; RobotKinematics3D& robot; }; /// Computes the ArrayMapping that only includes ancestor links of the /// goals in ik. This reduces the size of a RobotIKFunction's Jacobian matrix void GetDefaultIKDofs(const RobotKinematics3D& robot,const std::vector<IKGoal>& ik,ArrayMapping& m); /// Computes the ArrayMapping that contains a nonredundant subset of links /// terminating in the link of ikGoal. void GetPassiveChainDOFs(const RobotKinematics3D& robot,const IKGoal& ikGoal,ArrayMapping& passiveDofs); /// The same as above, but the goal is specified only by the link index /// and the number of operational space dof's. void GetPassiveChainDOFs(const RobotKinematics3D& robot,int link,int numTerms,ArrayMapping& passiveDofs); /// Helper function that tries to solve the given ik function using the /// Newton-Raphson solver. Returns true if successful bool SolveIK(RobotIKFunction& f, Real tolerance,int& iters,int verbose=1); /// Same as above, constructing the ik function from an IK problem bool SolveIK(RobotKinematics3D&,const std::vector<IKGoal>& problem, Real tolerance,int& iters,int verbose=1); /// Same as above, constructing the ik function from an IK problem and a list of /// active dofs bool SolveIK(RobotKinematics3D&,const std::vector<IKGoal>& problem, const std::vector<int>& activeDofs, Real tolerance,int& iters,int verbose=1); /// Same as above, constructing the ik function from a single IK goal and only /// using the required number of degrees of freedom to solve for the given /// goal. bool SolvePassiveChainIK(RobotKinematics3D&,const IKGoal& goal, Real tolerance,int& iters,int verbose=0); /// For the goal link's transformation T, computes the error of the IK goal g void EvalIKError(const IKGoal& g,const RigidTransform& T,Real* poserr,Real* orierr); void EvalIKError(const IKGoal& g,const RigidTransform& T,Vector& err); Real RobotIKError(const RobotKinematics3D& robot,const IKGoal& goal); /// For the goal link's transformaiton T, with rotational velocity dw and /// linear velocity dv, computes the derivative of g's error void EvalIKGoalDeriv(const IKGoal& g,const RigidTransform& T,const Vector3& dw,const Vector3& dv,Vector& derr); /// Constructs a new goal c from the intersection of two goals a and b which are /// required to have the same link and destLink. False is returned if a and b are /// incompatible. bool IntersectGoals(const IKGoal& a,const IKGoal& b,IKGoal& c,Real tolerance=1e-5); /// Adds a new constraint to a goalSet while merging it in intelligently /// to minimize the number of resulting constraints. False is returned if goal is /// incompatible with the previous goals. bool AddGoalNonredundant(const IKGoal& goal,std::vector<IKGoal>& goalSet,Real tolerance=1e-5); /** @brief Function class that returns the world-space position of a * point on the robot. * * An individual component of a RobotIKFunction. * Requres robot.q to be set, and the chain updated before PreEval is called. */ struct WorldPositionFunction : public VectorFieldFunction { WorldPositionFunction(RobotKinematics3D&,const Vector3& pi,int i,const ArrayMapping& activeDofs); int GetDOF(int dim) const; virtual std::string Label() const { return "WorldPos"; } virtual int NumDimensions() const { return 3; } virtual void Eval(const Vector& x, Vector& v); virtual Real Eval_i(const Vector& x, int i); virtual void Jacobian(const Vector& x, Matrix& J); //virtual void Jacobian_i(const Vector& x, int i, Vector& Ji); //virtual void Hessian_i(const Vector& x,int i,Matrix& Hi); RobotKinematics3D& robot; Vector3 ploc; int link; const ArrayMapping& activeDofs; }; /** @brief Function class that returns the position/rotation errors * associated with a given IKGoal. * * An individual component of a RobotIKFunction. * Requres robot.q to be set, and the chain updated before PreEval is called. */ struct IKGoalFunction : public VectorFieldFunction { IKGoalFunction(RobotKinematics3D&,const IKGoal&,const ArrayMapping& activeDofs); int GetDOF(int dim) const; virtual std::string Label() const; virtual std::string Label(int i) const; virtual int NumDimensions() const; virtual void PreEval(const Vector& x); virtual void Eval(const Vector& x, Vector& r); virtual Real Eval_i(const Vector& x, int i); virtual void Jacobian(const Vector& x, Matrix& J); virtual void Jacobian_i(const Vector& x, int i, Vector& Ji); virtual void Hessian_i(const Vector& x,int i,Matrix& Hi); void UpdateEEPos(); void UpdateEERot(); RobotKinematics3D& robot; const IKGoal& goal; const ArrayMapping& activeDofs; Real positionScale, rotationScale; //position,rotation error of end effector DirtyData<Vector3> eepos; DirtyData<Matrix3> eerot; DirtyData<std::vector<Matrix> > H; Matrix Jptemp,Jptemp2,Jotemp,Jotemp2; }; /** @brief Function class that measures the difference between the robot's * center of mass and a desired COM. * * An individual component of a RobotIKFunction. * Requres robot.q to be set, and the chain updated before PreEval is called. */ struct RobotCOMFunction : public VectorFieldFunction { RobotCOMFunction(RobotKinematics3D&,const Vector2& com,const ArrayMapping& activeDofs); int GetDOF(int dim) const; virtual std::string Label() const; virtual std::string Label(int i) const; virtual int NumDimensions() const { return 2; } virtual void PreEval(const Vector& x); virtual void Eval(const Vector& x, Vector& r); virtual Real Eval_i(const Vector& x, int i); virtual void Jacobian(const Vector& x, Matrix& J); virtual void Jacobian_i(const Vector& x, int i, Vector& Ji); virtual void Hessian_i(const Vector& x,int i,Matrix& Hi); RobotKinematics3D& robot; Vector2 comGoal; const ArrayMapping& activeDofs; Real comScale; //temp Real mtotal; DirtyData<Matrix> Hx; DirtyData<Matrix> Hy; }; /// Returns false if the goals a and b cannot be mutually reached because /// of the length of the robot links. Joint limits do not factor into this /// computation. bool IsReachableGoal(const RobotKinematics3D&,const IKGoal& a,const IKGoal& b); /// Returns false if the goals a and b cannot be mutually reached because /// of the length of the robot links, whose maximum distance is given as /// jointDistance. bool IsReachableGoal(const IKGoal& a,const IKGoal& b,Real jointDistance); /*@}*/ #endif
38.341772
111
0.752614
[ "vector" ]
3446d128c061a70f6bd4c71f18a6dfdd6fff36be
6,154
h
C
modules/mapred/manifest.h
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
16
2021-07-14T23:32:31.000Z
2022-03-24T16:25:15.000Z
modules/mapred/manifest.h
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-20T20:39:47.000Z
2021-09-16T20:57:59.000Z
modules/mapred/manifest.h
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-15T19:38:35.000Z
2022-01-31T19:24:56.000Z
#pragma once #include "base/base.h" #include "modules/mapred/path.h" #include "modules/mapred/input_stream.h" #include "modules/mapred/multi_reader.h" #include "modules/mapred/metadata.h" #include "modules/io/keyvalue.h" #include "modules/io/transfer_object.h" #include <boost/iterator/iterator_facade.hpp> // Manifests are an abstract class that represents a group of paths which are logically // the same data set. If the data is sorted, the manifest will contain the sort function // along with first/last key for each part (which facilitates distributed merge sorts) // Manifests are futher divided into 'paritions' which each contain only records who's // key % num_paritions == parition number. In the case of unsorted data, there is only // one parition. class file_info { public: file_info() = default; file_info( const path& file, size_t size, size_t num_records, const std::string& first_key = "", const std::string& last_key = "") : file(file) , size(size) , num_records(num_records) , first_key(first_key) , last_key(last_key) {} TRANSFER_OBJECT { VERSION(0); FIELD(file, TF_STRICT); FIELD(size, TF_STRICT); FIELD(num_records, TF_STRICT); FIELD(first_key); FIELD(last_key); } operator path() const { return file; } path file; size_t size = 0; // total bytes if one were to read AND decode the entire file. The encoding used is saved in the manifest size_t num_records = 0; // Number of records in this part std::string first_key; // First key in file (empty if not sorted) std::string last_key; // Last key in file (empty if not sorted) }; class partition_info { public: partition_info() = default; TRANSFER_OBJECT { VERSION(0); FIELD(files, TF_STRICT); FIELD(num_records, TF_STRICT); FIELD(size, TF_STRICT); } void add(const file_info& fi); void add(const partition_info& other); size_t size = 0; // Precomputed accumulation of files size_t num_records = 0; // Precomputed accumulation of files std::vector<file_info> files; }; class splitter; class manifest { class manifest_iterator; friend class manifest_iterator; public: typedef std::function<void ()> notify_f; using is_manifest = std::true_type; TRANSFER_OBJECT { VERSION(0); FIELD(partitions, TF_STRICT); FIELD(size, TF_STRICT); FIELD(num_records, TF_STRICT); FIELD(sort); FIELD(meta); FIELD(tags); // it's pronounced 'tehgs' :) FIELD(all_metadata); } manifest(const std::string& sort_ = "", size_t num_partitions = 1) : size(0) , num_records(0) , sort(sort_) , partitions(num_partitions) {} void set_meta(const std::string& meta_) { meta = meta_; } void set_sort(const std::string& sort_) { sort = sort_; } void set_notify(notify_f fn) { m_notify = fn; } std::string get_encoding() const; void set_encoding(const std::string& enc); std::string get_sort() { return sort; } const std::string& get_meta() { return meta; } void add(const manifest& other, bool unsorted = false); void add(const file_info& fi, size_t partition); size_t get_size() const { return size; } size_t get_num_records() const { return num_records;} const std::string& get_sort() const { return sort; } size_t get_num_partitions() const { return partitions.size(); } size_t get_num_chunks() const; size_t count_file_infos() const; typedef manifest_iterator const_iterator; typedef path value_type; void split_by_partition(std::vector<input_stream_params>& out) const; void split_by_goal_size(std::vector<input_stream_params>& out, size_t goal_size) const; void split_mergepart(std::vector<input_stream_params>& out, size_t goal_size, size_t max_files) const; bool split_sort(manifest& done, std::vector<input_stream_params>& to_sort, size_t max_merge, bool clean_break = true); void split_sort_reduce(std::vector<input_stream_params>& out, size_t goal_size, bool clean_break = true); // Partition file_infos if they need splitting. Into to_split if yes, otherwise into target_manifest. void split_by_splitter(manifest& target_manifest, std::vector<input_stream_params>& to_split, const std::string& the_splitter) const; void sort_file_infos(); size_t max_files() const; // Returns the maximum number of files per partition const_iterator begin() const; const_iterator end() const; void merge_tags(const manifest& in); meta::data& metadata() { return all_metadata; } const meta::data& metadata() const { return all_metadata; } // Functions that take an arbitrary number of manifests and merge the metadata from the // second parameter and on into the manifest in the first parameter. // Call like this: update_metadate(dest_manifest, source_manifest1, source_manifest2, ..., source_manifest_n); template<typename T> void update_metadata(const T& in) { static_assert(T::is_manifest::value, "The update_metadata function takes only manifests. The input is not a manifest."); merge_tags(in); } template<typename T, typename... TInManifests> void update_metadata(const T& in, const TInManifests&... inputs) { static_assert(T::is_manifest::value, "The update_metadata function takes only manifests. One of the inputs is not a manifest."); merge_tags(in); update_metadata(inputs...); } private: class manifest_iterator : public boost::iterator_facade<manifest_iterator, file_info const, boost::forward_traversal_tag> { public: manifest_iterator(); manifest_iterator(const manifest& self); private: friend class boost::iterator_core_access; void skip_to_valid(); void increment(); bool equal(manifest_iterator const& other) const; const file_info& dereference() const; const manifest* m_self; size_t m_part; size_t m_file; }; size_t size; // Precomputed accumulation of partitions size_t num_records; // Precomputed accumulation of partitions std::string sort; // If non-empty, elements are sorted std::vector<partition_info> partitions; std::string meta; meta::data all_metadata; notify_f m_notify; public: std::map<std::string, std::string> tags; }; class manifest_reader : public multi_reader<manifest::const_iterator> { public: manifest_reader(const manifest& m); };
31.080808
134
0.740331
[ "vector" ]
e7341b05baf517c494264334fcf3723e50bca0a9
5,380
h
C
deps/lld/ELF/SymbolTable.h
harryeakins/zig
8503eff8c12697c35ab5c73d6651c4b996339706
[ "MIT" ]
14
2018-07-10T19:50:03.000Z
2021-11-18T05:04:39.000Z
deps/lld/ELF/SymbolTable.h
harryeakins/zig
8503eff8c12697c35ab5c73d6651c4b996339706
[ "MIT" ]
1
2018-09-27T09:33:10.000Z
2018-09-27T09:44:15.000Z
deps/lld/ELF/SymbolTable.h
harryeakins/zig
8503eff8c12697c35ab5c73d6651c4b996339706
[ "MIT" ]
6
2018-09-21T06:37:48.000Z
2022-01-27T13:40:25.000Z
//===- SymbolTable.h --------------------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_ELF_SYMBOL_TABLE_H #define LLD_ELF_SYMBOL_TABLE_H #include "InputFiles.h" #include "LTO.h" #include "Strings.h" #include "llvm/ADT/CachedHashString.h" #include "llvm/ADT/DenseMap.h" namespace lld { namespace elf { class Defined; class SectionBase; // SymbolTable is a bucket of all known symbols, including defined, // undefined, or lazy symbols (the last one is symbols in archive // files whose archive members are not yet loaded). // // We put all symbols of all files to a SymbolTable, and the // SymbolTable selects the "best" symbols if there are name // conflicts. For example, obviously, a defined symbol is better than // an undefined symbol. Or, if there's a conflict between a lazy and a // undefined, it'll read an archive member to read a real definition // to replace the lazy symbol. The logic is implemented in the // add*() functions, which are called by input files as they are parsed. There // is one add* function per symbol type. class SymbolTable { public: template <class ELFT> void addFile(InputFile *File); template <class ELFT> void addCombinedLTOObject(); template <class ELFT> void addSymbolWrap(StringRef Name); void applySymbolWrap(); ArrayRef<Symbol *> getSymbols() const { return SymVector; } Defined *addAbsolute(StringRef Name, uint8_t Visibility = llvm::ELF::STV_HIDDEN, uint8_t Binding = llvm::ELF::STB_GLOBAL); template <class ELFT> Symbol *addUndefined(StringRef Name); template <class ELFT> Symbol *addUndefined(StringRef Name, uint8_t Binding, uint8_t StOther, uint8_t Type, bool CanOmitFromDynSym, InputFile *File); Symbol *addRegular(StringRef Name, uint8_t StOther, uint8_t Type, uint64_t Value, uint64_t Size, uint8_t Binding, SectionBase *Section, InputFile *File); template <class ELFT> void addShared(StringRef Name, SharedFile<ELFT> &F, const typename ELFT::Sym &Sym, uint32_t Alignment, uint32_t VerdefIndex); template <class ELFT> Symbol *addLazyArchive(StringRef Name, ArchiveFile &F, const llvm::object::Archive::Symbol S); template <class ELFT> void addLazyObject(StringRef Name, LazyObjFile &Obj); Symbol *addBitcode(StringRef Name, uint8_t Binding, uint8_t StOther, uint8_t Type, bool CanOmitFromDynSym, BitcodeFile &File); Symbol *addCommon(StringRef Name, uint64_t Size, uint32_t Alignment, uint8_t Binding, uint8_t StOther, uint8_t Type, InputFile &File); std::pair<Symbol *, bool> insert(StringRef Name); std::pair<Symbol *, bool> insert(StringRef Name, uint8_t Type, uint8_t Visibility, bool CanOmitFromDynSym, InputFile *File); template <class ELFT> void fetchIfLazy(StringRef Name); template <class ELFT> void scanShlibUndefined(); void scanVersionScript(); Symbol *find(StringRef Name); void trace(StringRef Name); void handleDynamicList(); private: std::vector<Symbol *> findByVersion(SymbolVersion Ver); std::vector<Symbol *> findAllByVersion(SymbolVersion Ver); void defsym(Symbol *Dst, Symbol *Src); llvm::StringMap<std::vector<Symbol *>> &getDemangledSyms(); void handleAnonymousVersion(); void assignExactVersion(SymbolVersion Ver, uint16_t VersionId, StringRef VersionName); void assignWildcardVersion(SymbolVersion Ver, uint16_t VersionId); // The order the global symbols are in is not defined. We can use an arbitrary // order, but it has to be reproducible. That is true even when cross linking. // The default hashing of StringRef produces different results on 32 and 64 // bit systems so we use a map to a vector. That is arbitrary, deterministic // but a bit inefficient. // FIXME: Experiment with passing in a custom hashing or sorting the symbols // once symbol resolution is finished. llvm::DenseMap<llvm::CachedHashStringRef, int> SymMap; std::vector<Symbol *> SymVector; // Comdat groups define "link once" sections. If two comdat groups have the // same name, only one of them is linked, and the other is ignored. This set // is used to uniquify them. llvm::DenseSet<llvm::CachedHashStringRef> ComdatGroups; // Set of .so files to not link the same shared object file more than once. llvm::DenseSet<StringRef> SoNames; // A map from demangled symbol names to their symbol objects. // This mapping is 1:N because two symbols with different versions // can have the same name. We use this map to handle "extern C++ {}" // directive in version scripts. llvm::Optional<llvm::StringMap<std::vector<Symbol *>>> DemangledSyms; struct WrappedSymbol { Symbol *Sym; Symbol *Real; Symbol *Wrap; }; // For -wrap. std::vector<WrappedSymbol> WrappedSymbols; // For LTO. std::unique_ptr<BitcodeCompiler> LTO; }; extern SymbolTable *Symtab; } // namespace elf } // namespace lld #endif
37.622378
80
0.678625
[ "object", "vector" ]
e736774b6668d32f88dda3d7a7e167739cb7cc19
7,399
h
C
N64 Soundbank Tool/vgmtrans2009/DLSFile.h
Raspberryfloof/N64-Tools
96738d434ce3922dec0168cdd42f8e7ca131d0c5
[ "Unlicense" ]
160
2018-09-15T00:33:00.000Z
2022-03-28T23:39:46.000Z
N64 Soundbank Tool/vgmtrans2009/DLSFile.h
Raspberryfloof/N64-Tools
96738d434ce3922dec0168cdd42f8e7ca131d0c5
[ "Unlicense" ]
32
2018-09-15T17:49:01.000Z
2022-03-17T21:38:46.000Z
N64 Soundbank Tool/vgmtrans2009/DLSFile.h
Raspberryfloof/N64-Tools
96738d434ce3922dec0168cdd42f8e7ca131d0c5
[ "Unlicense" ]
132
2018-09-15T00:44:39.000Z
2022-03-26T01:46:36.000Z
// Taken from VGMTrans #pragma once #include "VGMExports.h" #include "common.h" struct Loop; class VGMSamp; /* Articulation connection graph definitions */ /* Generic Sources */ #define CONN_SRC_NONE 0x0000 #define CONN_SRC_LFO 0x0001 #define CONN_SRC_KEYONVELOCITY 0x0002 #define CONN_SRC_KEYNUMBER 0x0003 #define CONN_SRC_EG1 0x0004 #define CONN_SRC_EG2 0x0005 #define CONN_SRC_PITCHWHEEL 0x0006 /* Midi Controllers 0-127 */ #define CONN_SRC_CC1 0x0081 #define CONN_SRC_CC7 0x0087 #define CONN_SRC_CC10 0x008a #define CONN_SRC_CC11 0x008b /* Registered Parameter Numbers */ #define CONN_SRC_RPN0 0x0100 #define CONN_SRC_RPN1 0x0101 #define CONN_SRC_RPN2 0x0102 /* Generic Destinations */ #define CONN_DST_NONE 0x0000 #define CONN_DST_ATTENUATION 0x0001 #define CONN_DST_RESERVED 0x0002 #define CONN_DST_PITCH 0x0003 #define CONN_DST_PAN 0x0004 /* LFO Destinations */ #define CONN_DST_LFO_FREQUENCY 0x0104 #define CONN_DST_LFO_STARTDELAY 0x0105 /* EG1 Destinations */ #define CONN_DST_EG1_ATTACKTIME 0x0206 #define CONN_DST_EG1_DECAYTIME 0x0207 #define CONN_DST_EG1_RESERVED 0x0208 #define CONN_DST_EG1_RELEASETIME 0x0209 #define CONN_DST_EG1_SUSTAINLEVEL 0x020a /* EG2 Destinations */ #define CONN_DST_EG2_ATTACKTIME 0x030a #define CONN_DST_EG2_DECAYTIME 0x030b #define CONN_DST_EG2_RESERVED 0x030c #define CONN_DST_EG2_RELEASETIME 0x030d #define CONN_DST_EG2_SUSTAINLEVEL 0x030e #define CONN_TRN_NONE 0x0000 #define CONN_TRN_CONCAVE 0x0001 /* Level 2 */ #define CONN_DST_VIB_FREQUENCY 0x0114 #define CONN_DST_VIB_STARTDELAY 0x0115 #define F_INSTRUMENT_DRUMS 0x80000000 #define COLH_SIZE (4+8) #define INSH_SIZE (12+8) #define RGNH_SIZE (14+8)//(12+8) #define WLNK_SIZE (12+8) #define LIST_HDR_SIZE 12 class DLSInstr; class DLSRgn; class DLSArt; class connectionBlock; class DLSWsmp; class DLSWave; inline void WriteLIST(vector<BYTE> &buf, string listName, UINT listSize); inline void AlignName(string& name); class DLSFile { public: DLSFile(string dls_name = "Instrument Set"); ~DLSFile(void); DLSInstr* AddInstr(unsigned long bank, unsigned long instrNum); DLSInstr* AddInstr(unsigned long bank, unsigned long instrNum, string Name); void DeleteInstr(unsigned long bank, unsigned long instrNum); DLSWave* AddWave(USHORT formatTag, USHORT channels, int samplesPerSec, int aveBytesPerSec, USHORT blockAlign, USHORT bitsPerSample, ULONG waveDataSize, BYTE* waveData, string name = "Unnamed Wave"); void SetName(string dls_name); UINT GetSize(void); int WriteDLSToBuffer(vector<BYTE> &buf); bool SaveDLSFile(const TCHAR* filepath); bool UI_WriteBufferToFile(const TCHAR* filepath, unsigned char* buf, unsigned long size); public: vector<DLSInstr*> aInstrs; vector<DLSWave*> aWaves; private: string name; }; class DLSInstr { public: DLSInstr(void); DLSInstr(ULONG bank, ULONG instrument); DLSInstr(ULONG bank, ULONG instrument, string instrName); DLSInstr(ULONG bank, ULONG instrument, string instrName, vector<DLSRgn*> listRgns); ~DLSInstr(void); void AddRgnList(vector<DLSRgn>& RgnList); DLSRgn* AddRgn(void); DLSRgn* AddRgn(DLSRgn rgn); UINT GetSize(void); void Write(vector<BYTE> &buf); public: ULONG ulBank; ULONG ulInstrument; vector<DLSRgn*> aRgns; string name; }; class DLSRgn { public: DLSRgn(void): Wsmp(NULL), Art(NULL) {} DLSRgn(USHORT keyLow, USHORT keyHigh, USHORT velLow, USHORT velHigh) : usKeyLow(keyLow), usKeyHigh(keyHigh), usVelLow(velLow), usVelHigh(velHigh), Wsmp(NULL), Art(NULL) {} DLSRgn(USHORT keyLow, USHORT keyHigh, USHORT velLow, USHORT velHigh, DLSArt& art); //: usKeyLow(keyLow), usKeyHigh(keyHigh), usVelLow(velLow), usVelHigh(velHigh) {} ~DLSRgn(void); DLSArt* AddArt(void); DLSArt* AddArt(vector<connectionBlock*> connBlocks); DLSWsmp* AddWsmp(void); DLSWsmp* AddWsmp(DLSWsmp wsmp); void SetRanges(USHORT keyLow = 0, USHORT keyHigh = 0x7F, USHORT velLow = 0, USHORT velHigh = 0x7F); void SetWaveLinkInfo(USHORT options, USHORT phaseGroup, ULONG theChannel, ULONG theTableIndex); UINT GetSize(void); void Write(vector<BYTE> &buf); public: USHORT usKeyLow; USHORT usKeyHigh; USHORT usVelLow; USHORT usVelHigh; USHORT fusOptions; USHORT usPhaseGroup; ULONG channel; ULONG tableIndex; DLSWsmp* Wsmp; DLSArt* Art; }; class ConnectionBlock { public: ConnectionBlock(void); ConnectionBlock(USHORT source, USHORT control, USHORT destination, USHORT transform, LONG scale) : usSource(source), usControl(control), usDestination(destination), usTransform(transform), lScale(scale) {} ~ConnectionBlock(void) {} UINT GetSize(void) {return 12;} void Write(vector<BYTE> &buf); private: USHORT usSource; USHORT usControl; USHORT usDestination; USHORT usTransform; LONG lScale; }; class DLSArt { public: DLSArt(void) {} DLSArt(vector<ConnectionBlock>& connectionBlocks); //DLSArt(USHORT source, USHORT control, USHORT destination, USHORT transform); ~DLSArt(void); void AddADSR(long attack_time, USHORT atk_transform, long decay_time, long sustain_lev, long release_time, USHORT rls_transform); void AddPan(long pan); void AddVibrato(long frequency, long delay_time); UINT GetSize(void); void Write(vector<BYTE> &buf); private: vector<ConnectionBlock*> aConnBlocks; }; class DLSWsmp { public: DLSWsmp(void) {} DLSWsmp(USHORT unityNote, SHORT fineTune, LONG attenuation, char sampleLoops, ULONG loopType, ULONG loopStart, ULONG loopLength) : usUnityNote(unityNote), sFineTune(fineTune), lAttenuation(attenuation), cSampleLoops(sampleLoops), ulLoopType(loopType), ulLoopStart(loopStart), ulLoopLength(loopLength) {} ~DLSWsmp(void) {} void SetPitchInfo(USHORT unityNote, short fineTune, long attenuation); UINT GetSize(void); void Write(vector<BYTE> &buf); public: unsigned short usUnityNote; short sFineTune; long lAttenuation; char cSampleLoops; ULONG ulLoopType; ULONG ulLoopStart; ULONG ulLoopLength; }; class DLSWave { public: DLSWave(void) : Wsmp(NULL), data(NULL), name("Untitled Wave") { AlignName(name); } DLSWave(USHORT formatTag, USHORT channels, int samplesPerSec, int aveBytesPerSec, USHORT blockAlign, USHORT bitsPerSample, ULONG waveDataSize, unsigned char* waveData, string waveName = "Untitled Wave") : wFormatTag(formatTag), wChannels(channels), dwSamplesPerSec(samplesPerSec), dwAveBytesPerSec(aveBytesPerSec), wBlockAlign(blockAlign), wBitsPerSample(bitsPerSample), dataSize(waveDataSize), data(waveData), Wsmp(NULL), name(waveName) { AlignName(name); } ~DLSWave(void); // This function will always return an even value, to maintain the alignment // necessary for the RIFF format. unsigned long GetSampleSize(void) { if (dataSize % 2) return dataSize+1; else return dataSize; // return dataSize; } UINT GetSize(void); void Write(vector<BYTE> &buf); DLSWsmp* Wsmp; private: unsigned short wFormatTag; unsigned short wChannels; ULONG dwSamplesPerSec; ULONG dwAveBytesPerSec; unsigned short wBlockAlign; unsigned short wBitsPerSample; unsigned long dataSize; unsigned char* data; string name; };
26.052817
130
0.73537
[ "vector", "transform" ]
e73849c3d9599e07f5c98cf125303f737feef444
1,262
h
C
inc/main_app.h
funbiscuit/curvedetect
b12daaff9d3eb90fe7d3d582396f84d195e36a52
[ "MIT" ]
3
2019-08-26T21:00:24.000Z
2021-05-28T01:05:12.000Z
inc/main_app.h
funbiscuit/curvedetect
b12daaff9d3eb90fe7d3d582396f84d195e36a52
[ "MIT" ]
null
null
null
inc/main_app.h
funbiscuit/curvedetect
b12daaff9d3eb90fe7d3d582396f84d195e36a52
[ "MIT" ]
null
null
null
#ifndef CURVEDETECT_MAIN_APP_H #define CURVEDETECT_MAIN_APP_H #include <imgui.h> #include "main_window.h" #include <vector> #include <string> #include <imgui.h> struct GLFWwindow; class MainApp { private: MainApp(const MainApp&); MainApp& operator=(MainApp&); MainApp(); public: bool init(GLFWwindow* window, const char* glsl_version); bool new_frame(); static MainApp& get(); void copy_to_clipboard(const std::string& text); bool is_enter_up(){return bEnterReleased;} private: const int RENDER_FRAMES_MAX=20; int renderFrames = RENDER_FRAMES_MAX; bool bEnterReleased; MainWindow mainWindow; static void on_window_resize(GLFWwindow *wnd, int width, int height); static void on_key_callback(GLFWwindow *wnd, int key, int scancode, int action, int mods); static void on_mouse_button_callback(GLFWwindow *wnd, int button, int action, int mods); static void on_cursor_pos_callback(GLFWwindow *wnd, double xpos, double ypos); static void on_scroll_callback(GLFWwindow *wnd, double xoffset, double yoffset); bool bShouldUseIMGUICursor; int m_width, m_height; GLFWwindow *window; void set_use_imgui_cursor(bool bShowCursor); }; #endif //CURVEDETECT_MAIN_APP_H
20.354839
94
0.732171
[ "vector" ]
e73ffd1795ab123df5d1661e69af475366fce15a
3,609
h
C
include/SCCommon.h
BradyBrenot/screen_capture_lite
775d058408dcc393f632d2bf3483104d5d781432
[ "MIT" ]
3
2018-07-08T15:32:27.000Z
2019-11-08T16:50:55.000Z
include/SCCommon.h
BradyBrenot/screen_capture_lite
775d058408dcc393f632d2bf3483104d5d781432
[ "MIT" ]
null
null
null
include/SCCommon.h
BradyBrenot/screen_capture_lite
775d058408dcc393f632d2bf3483104d5d781432
[ "MIT" ]
1
2018-12-02T09:02:04.000Z
2018-12-02T09:02:04.000Z
#pragma once #include "ScreenCapture.h" #include <atomic> #include <thread> // this is INTERNAL DO NOT USE! namespace SL { namespace Screen_Capture { template <typename F, typename M, typename W> struct CaptureData { std::shared_ptr<ITimer> FrameTimer; F OnNewFrame; F OnFrameChanged; std::shared_ptr<ITimer> MouseTimer; M OnMouseChanged; W getThingsToWatch; }; struct CommonData { // Used to indicate abnormal error condition std::atomic<bool> UnexpectedErrorEvent; // Used to indicate a transition event occurred e.g. PnpStop, PnpStart, mode change, TDR, desktop switch and the application needs to recreate // the duplication interface std::atomic<bool> ExpectedErrorEvent; // Used to signal to threads to exit std::atomic<bool> TerminateThreadsEvent; std::atomic<bool> Paused; }; struct Thread_Data { CaptureData<ScreenCaptureCallback, MouseCallback, MonitorCallback> ScreenCaptureData; CaptureData<WindowCaptureCallback, MouseCallback, WindowCallback> WindowCaptureData; CommonData CommonData_; }; class BaseFrameProcessor { public: std::shared_ptr<Thread_Data> Data; std::unique_ptr<unsigned char[]> OldImageBuffer, NewImageBuffer; int ImageBufferSize = 0; bool FirstRun = true; }; enum DUPL_RETURN { DUPL_RETURN_SUCCESS = 0, DUPL_RETURN_ERROR_EXPECTED = 1, DUPL_RETURN_ERROR_UNEXPECTED = 2 }; const int PixelStride = 4; Monitor CreateMonitor(int index, int id, int h, int w, int ox, int oy, const std::string &n, float scale); Image Create(const ImageRect &imgrect, int pixelstride, int rowpadding, const unsigned char *data); // this function will copy data from the src into the dst. The only requirement is that src must not be larger than dst, but it can be smaller // void Copy(const Image& dst, const Image& src); std::vector<ImageRect> GetDifs(const Image &oldimg, const Image &newimg); template <class F, class T, class C> void ProcessCapture(const F &data, T &base, const C &mointor, ImageRect &imageract) { if (data.OnNewFrame) { auto wholeimg = Create(imageract, PixelStride, 0, base.NewImageBuffer.get()); data.OnNewFrame(wholeimg, mointor); } if (data.OnFrameChanged) { if (base.FirstRun) { // first time through, just send the whole image auto wholeimgfirst = Create(imageract, PixelStride, 0, base.NewImageBuffer.get()); data.OnFrameChanged(wholeimgfirst, mointor); base.FirstRun = false; } else { // user wants difs, lets do it! auto newimg = Create(imageract, PixelStride, 0, base.NewImageBuffer.get()); auto oldimg = Create(imageract, PixelStride, 0, base.OldImageBuffer.get()); auto imgdifs = GetDifs(oldimg, newimg); for (auto &r : imgdifs) { auto padding = (r.left * PixelStride) + ((Width(newimg) - r.right) * PixelStride); auto startsrc = base.NewImageBuffer.get(); startsrc += (r.left * PixelStride) + (r.top * PixelStride * Width(newimg)); auto difimg = Create(r, PixelStride, padding, startsrc); data.OnFrameChanged(difimg, mointor); } } std::swap(base.NewImageBuffer, base.OldImageBuffer); } } } // namespace Screen_Capture } // namespace SL
41.482759
150
0.6312
[ "vector" ]
e74955ebf6d1ead8bae712359ca980d27d6cc419
3,615
c
C
examples/10-send-with-imm/client.c
ldorau/rpma-lgtm
4a4cfd43b91b25db954bf07d16dc8eafe78d4483
[ "BSD-3-Clause" ]
83
2020-02-18T13:19:10.000Z
2022-03-29T08:22:28.000Z
examples/10-send-with-imm/client.c
ldorau/rpma-lgtm
4a4cfd43b91b25db954bf07d16dc8eafe78d4483
[ "BSD-3-Clause" ]
603
2020-02-13T10:45:28.000Z
2022-03-31T11:13:17.000Z
examples/10-send-with-imm/client.c
ldorau/rpma-lgtm
4a4cfd43b91b25db954bf07d16dc8eafe78d4483
[ "BSD-3-Clause" ]
51
2020-02-13T09:11:15.000Z
2022-03-29T08:22:31.000Z
// SPDX-License-Identifier: BSD-3-Clause /* Copyright (c) 2020-2021 Fujitsu */ /* Copyright 2021, Intel Corporation */ /* * client.c -- a client of the send-with-imm example * * Please see README.md for a detailed description of this example. */ #include <librpma.h> #include <limits.h> #include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include "common-conn.h" #define USAGE_STR "usage: %s <server_address> <port> <imm> [word]\n" int main(int argc, char *argv[]) { /* validate parameters */ if (argc < 4) { fprintf(stderr, USAGE_STR, argv[0]); return -1; } /* configure logging thresholds to see more details */ rpma_log_set_threshold(RPMA_LOG_THRESHOLD, RPMA_LOG_LEVEL_INFO); rpma_log_set_threshold(RPMA_LOG_THRESHOLD_AUX, RPMA_LOG_LEVEL_INFO); /* read common parameters */ char *addr = argv[1]; char *port = argv[2]; char *word = NULL; uint64_t imm = strtoul(argv[3], NULL, 10); if (imm == ULONG_MAX && errno == ERANGE) { fprintf(stderr, "strtoul() overflow\n"); return -1; } if (imm > UINT32_MAX) { fprintf(stderr, "The provided immediate data is too big (%lu > %u)\n", imm, UINT32_MAX); return -1; } if (argc == 5) word = argv[4]; /* RPMA resources - general */ struct rpma_peer *peer = NULL; struct rpma_conn *conn = NULL; struct rpma_mr_local *send_mr = NULL; struct rpma_completion cmpl; uint64_t len = 0; char *send = NULL; int ret; if (word) { /* prepare memory */ len = KILOBYTE; send = malloc_aligned(len); if (!send) return -1; } /* * lookup an ibv_context via the address and create a new peer using it */ ret = client_peer_via_address(addr, &peer); if (ret) goto err_mr_free; if (word) { /* register the memory */ ret = rpma_mr_reg(peer, send, KILOBYTE, RPMA_MR_USAGE_SEND, &send_mr); if (ret) goto err_peer_delete; } /* * establish a new connection to a server and send an immediate * data for validation on the sever side */ struct rpma_conn_private_data pdata; pdata.ptr = (uint32_t *)&imm; pdata.len = sizeof(uint32_t); ret = client_connect(peer, addr, port, NULL, &pdata, &conn); if (ret) goto err_mr_dereg; if (word) { /* send a message with immediate data to the server */ fprintf(stdout, "Sending value '%s' with immediate data '%u'\n", word, (uint32_t)imm); strncpy(send, word, KILOBYTE - 1); } else { /* send a 0B message with immediate data to the server */ fprintf(stdout, "Sending immediate data '%u'\n", (uint32_t)imm); } ret = rpma_send_with_imm(conn, send_mr, 0, len, RPMA_F_COMPLETION_ALWAYS, (uint32_t)imm, NULL); if (ret) goto err_conn_disconnect; /* get the connection's main CQ */ struct rpma_cq *cq = NULL; ret = rpma_conn_get_cq(conn, &cq); if (ret) goto err_conn_disconnect; /* prepare completions, get one and validate it */ ret = rpma_cq_wait(cq); if (ret) goto err_conn_disconnect; ret = rpma_cq_get_completion(cq, &cmpl); if (ret) goto err_conn_disconnect; if (cmpl.op_status != IBV_WC_SUCCESS) { fprintf(stderr, "Received unexpected completion: %s\n", ibv_wc_status_str(cmpl.op_status)); ret = -1; goto err_conn_disconnect; } if (cmpl.op != RPMA_OP_SEND) { fprintf(stderr, "Received unexpected type of operation (%d != %d)\n", cmpl.op, RPMA_OP_SEND); ret = -1; } err_conn_disconnect: (void) common_disconnect_and_wait_for_conn_close(&conn); err_mr_dereg: /* deregister the memory regions */ (void) rpma_mr_dereg(&send_mr); err_peer_delete: /* delete the peer object */ (void) rpma_peer_delete(&peer); err_mr_free: /* free the memory */ free(send); return ret; }
22.59375
72
0.680498
[ "object" ]
e749f0eb96e94095494dd8f807b77db5567d2298
4,411
h
C
3rdparty/wxWidgets/docs/doxygen/overviews/fontencoding.h
mikiec84/winsparkle
e73db4ddb3be830b36b58e2f90f4bee6a0c684b7
[ "MIT" ]
2
2015-01-10T09:15:16.000Z
2018-01-03T21:21:46.000Z
3rdparty/wxWidgets/docs/doxygen/overviews/fontencoding.h
mikiec84/winsparkle
e73db4ddb3be830b36b58e2f90f4bee6a0c684b7
[ "MIT" ]
null
null
null
3rdparty/wxWidgets/docs/doxygen/overviews/fontencoding.h
mikiec84/winsparkle
e73db4ddb3be830b36b58e2f90f4bee6a0c684b7
[ "MIT" ]
1
2019-01-20T12:55:33.000Z
2019-01-20T12:55:33.000Z
///////////////////////////////////////////////////////////////////////////// // Name: fontencoding.h // Purpose: topic overview // Author: wxWidgets team // RCS-ID: $Id: fontencoding.h 59609 2009-03-18 15:30:06Z FM $ // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// /** @page overview_fontencoding Font Encodings wxWidgets has support for multiple font encodings. By encoding we mean here the mapping between the character codes and the letters. Probably the most well-known encoding is (7 bit) ASCII one which is used almost universally now to represent the letters of the English alphabet and some other common characters. However, it is not enough to represent the letters of foreign alphabets and here other encodings come into play. Please note that we will only discuss 8-bit fonts here and not Unicode (see @ref overview_unicode). Font encoding support is ensured by several classes: wxFont itself, but also wxFontEnumerator and wxFontMapper. wxFont encoding support is reflected by a (new) constructor parameter @e encoding which takes one of the following values (elements of enumeration type @c wxFontEncoding): @beginDefList @itemdef{wxFONTENCODING_SYSTEM, The default encoding of the underlying operating system (notice that this might be a "foreign" encoding for foreign versions of Windows 9x/NT).} @itemdef{wxFONTENCODING_DEFAULT, The applications default encoding as returned by wxFont::GetDefaultEncoding. On program startup, the applications default encoding is the same as wxFONTENCODING_SYSTEM, but may be changed to make all the fonts created later to use it (by default).} @itemdef{wxFONTENCODING_ISO8859_1..15, ISO8859 family encodings which are usually used by all non-Microsoft operating systems.} @itemdef{wxFONTENCODING_KOI8, Standard Cyrillic encoding for the Internet (but see also wxFONTENCODING_ISO8859_5 and wxFONTENCODING_CP1251).} @itemdef{wxFONTENCODING_CP1250, Microsoft analogue of ISO8859-2} @itemdef{wxFONTENCODING_CP1251, Microsoft analogue of ISO8859-5} @itemdef{wxFONTENCODING_CP1252, Microsoft analogue of ISO8859-1} @endDefList As you may see, Microsoft's encoding partly mirror the standard ISO8859 ones, but there are (minor) differences even between ISO8859-1 (Latin1, ISO encoding for Western Europe) and CP1251 (WinLatin1, standard code page for English versions of Windows) and there are more of them for other encodings. The situation is particularly complicated with Cyrillic encodings for which (more than) three incompatible encodings exist: KOI8 (the old standard, widely used on the Internet), ISO8859-5 (ISO standard for Cyrillic) and CP1251 (WinCyrillic). This abundance of (incompatible) encodings should make it clear that using encodings is less easy than it might seem. The problems arise both from the fact that the standard encodings for the given language (say Russian, which is written in Cyrillic) are different on different platforms and because the fonts in the given encoding might just not be installed (this is especially a problem with Unix, or, in general, non-Win32 systems). To clarify, the wxFontEnumerator class may be used to enumerate both all available encodings and to find the facename(s) in which the given encoding exists. If you can find the font in the correct encoding with wxFontEnumerator then your troubles are over, but, unfortunately, sometimes this is not enough. For example, there is no standard way (that I know of, please tell me if you do!) to find a font on a Windows system for KOI8 encoding (only for WinCyrillic one which is quite different), so wxFontEnumerator will never return one, even if the user has installed a KOI8 font on his system. To solve this problem, a wxFontMapper class is provided. This class stores the mapping between the encodings and the font face names which support them in wxConfigBase object. Of course, it would be fairly useless if it tried to determine these mappings by itself, so, instead, it (optionally) asks the user and remembers his answers so that the next time the program will automatically choose the correct font. All these topics are illustrated by the @ref page_samples_font; please refer to it and the documentation of the classes mentioned here for further explanations. */
49.561798
85
0.758558
[ "object" ]
e7524ff42c10e0db8289f13d2088a8c35630eac0
1,316
h
C
scene/2d/editor/poly_node_2d_editor_plugin.h
mbrlabs/goost
f2ed253ddd12328ad93d14a99531442c099315fa
[ "CC-BY-3.0", "MIT" ]
null
null
null
scene/2d/editor/poly_node_2d_editor_plugin.h
mbrlabs/goost
f2ed253ddd12328ad93d14a99531442c099315fa
[ "CC-BY-3.0", "MIT" ]
null
null
null
scene/2d/editor/poly_node_2d_editor_plugin.h
mbrlabs/goost
f2ed253ddd12328ad93d14a99531442c099315fa
[ "CC-BY-3.0", "MIT" ]
null
null
null
#ifndef GOOST_POLY_NODE_2D_EDITOR_PLUGIN_H #define GOOST_POLY_NODE_2D_EDITOR_PLUGIN_H #include "editor/plugins/abstract_polygon_2d_editor.h" #include "goost/core/math/2d/geometry/poly/poly_node_2d.h" class PolyNode2DEditor : public AbstractPolygon2DEditor { GDCLASS(PolyNode2DEditor, AbstractPolygon2DEditor); friend class PolyNode2DEditorPlugin; protected: PolyNode2D *node = nullptr; enum Menu { MENU_OPTION_FLATTEN_OUTLINES = 100, }; MenuButton *options = nullptr; Menu selected_menu_item; virtual void _menu_option(int p_option); static PolyNode2DEditor* singleton; virtual void _set_node(Node *p_node); virtual Node2D *_get_node() const; virtual bool _is_line() const; virtual Variant _get_polygon(int p_idx) const; virtual void _set_polygon(int p_idx, const Variant &p_polygon) const; virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon); public: static PolyNode2DEditor* get_singleton() { return singleton; } PolyNode2DEditor(EditorNode *p_editor); }; class PolyNode2DEditorPlugin : public AbstractPolygon2DEditorPlugin { GDCLASS(PolyNode2DEditorPlugin, AbstractPolygon2DEditorPlugin); public: virtual void make_visible(bool p_visible); PolyNode2DEditorPlugin(EditorNode *p_node); }; #endif // GOOST_POLY_NODE_2D_EDITOR_PLUGIN_H
27.416667
98
0.81307
[ "geometry" ]
e756c051f40ebd855af4d43804151f92a3f94884
36,924
c
C
new/libr/core/cmd_help.c
benbenwt/lisa_docker
0b851223dbaecef9b27c418eae05890fea752d49
[ "Apache-2.0" ]
null
null
null
new/libr/core/cmd_help.c
benbenwt/lisa_docker
0b851223dbaecef9b27c418eae05890fea752d49
[ "Apache-2.0" ]
1
2021-12-17T00:14:27.000Z
2021-12-17T00:14:27.000Z
new/libr/core/cmd_help.c
benbenwt/lisa_docker
0b851223dbaecef9b27c418eae05890fea752d49
[ "Apache-2.0" ]
null
null
null
/* radare - LGPL - Copyright 2009-2020 - pancake */ #include <stddef.h> #include <math.h> // required for signbit #include "r_cons.h" #include "r_core.h" #include "r_util.h" static ut32 vernum(const char *s) { // XXX this is known to be buggy, only works for strings like "x.x.x" // XXX anything like "x.xx.x" will break the parsing // XXX -git is ignored, maybe we should shift for it char *a = strdup (s); a = r_str_replace (a, ".", "0", 1); char *dash = strchr (a, '-'); if (dash) { *dash = 0; } ut32 res = atoi (a); free (a); return res; } static const char *help_msg_percent[] = { "Usage:", "%[name[=value]]", "Set each NAME to VALUE in the environment", "%", "", "list all environment variables", "%", "SHELL", "prints SHELL value", "%", "TMPDIR=/tmp", "sets TMPDIR value to \"/tmp\"", NULL }; // NOTE: probably not all environment vars takes sesnse // because they can be replaced by commands in the given // command.. we should only expose the most essential and // unidirectional ones. static const char *help_msg_env[] = { "\nEnvironment:", "", "", "R2_FILE", "", "file name", "R2_OFFSET", "", "10base offset 64bit value", "R2_BYTES", "", "TODO: variable with bytes in curblock", "R2_XOFFSET", "", "same as above, but in 16 base", "R2_BSIZE", "", "block size", "R2_ENDIAN", "", "'big' or 'little'", "R2_IOVA", "", "is io.va true? virtual addressing (1,0)", "R2_DEBUG", "", "debug mode enabled? (1,0)", "R2_BLOCK", "", "TODO: dump current block to tmp file", "R2_SIZE", "","file size", "R2_ARCH", "", "value of asm.arch", "R2_BITS", "", "arch reg size (8, 16, 32, 64)", "RABIN2_LANG", "", "assume this lang to demangle", "RABIN2_DEMANGLE", "", "demangle or not", "RABIN2_PDBSERVER", "", "e pdb.server", NULL }; static const char *help_msg_exclamation[] = { "Usage:", "!<cmd>", " Run given command as in system(3)", "!", "", "list all historic commands", "!", "ls", "execute 'ls' in shell", "!*", "r2p x", "run r2 command via r2pipe in current session", "!!", "", "save command history to hist file", "!!", "ls~txt", "print output of 'ls' and grep for 'txt'", "!!!", "cmd [args|$type]", "adds the autocomplete value", "!!!-", "cmd [args]", "removes the autocomplete value", ".!", "rabin2 -rpsei ${FILE}", "run each output line as a r2 cmd", "!", "echo $R2_SIZE", "display file size", "!-", "", "clear history in current session", "!-*", "", "clear and save empty history log", "!=!", "", "enable remotecmd mode", "=!=", "", "disable remotecmd mode", NULL }; static const char *help_msg_root[] = { "%var", "=value", "alias for 'env' command", "*", "[?] off[=[0x]value]", "pointer read/write data/values (see ?v, wx, wv)", "(macro arg0 arg1)", "", "manage scripting macros", ".", "[?] [-|(m)|f|!sh|cmd]", "Define macro or load r2, cparse or rlang file", ",", "[?] [/jhr]", "create a dummy table import from file and query it to filter/sort", "_", "[?]", "Print last output", "=","[?] [cmd]", "send/listen for remote commands (rap://, raps://, udp://, http://, <fd>)", "<","[...]", "push escaped string into the RCons.readChar buffer", "/","[?]", "search for bytes, regexps, patterns, ..", "!","[?] [cmd]", "run given command as in system(3)", "#","[?] !lang [..]", "Hashbang to run an rlang script", "a","[?]", "analysis commands", "b","[?]", "display or change the block size", "c","[?] [arg]", "compare block with given data", "C","[?]", "code metadata (comments, format, hints, ..)", "d","[?]", "debugger commands", "e","[?] [a[=b]]", "list/get/set config evaluable vars", "f","[?] [name][sz][at]", "add flag at current address", "g","[?] [arg]", "generate shellcodes with r_egg", "i","[?] [file]", "get info about opened file from r_bin", "k","[?] [sdb-query]", "run sdb-query. see k? for help, 'k *', 'k **' ...", "l"," [filepattern]", "list files and directories", "L","[?] [-] [plugin]", "list, unload load r2 plugins", "m","[?]", "mountpoints commands", "o","[?] [file] ([offset])", "open file at optional address", "p","[?] [len]", "print current block with format and length", "P","[?]", "project management utilities", "q","[?] [ret]", "quit program with a return value", "r","[?] [len]", "resize file", "s","[?] [addr]", "seek to address (also for '0x', '0x1' == 's 0x1')", "t","[?]", "types, noreturn, signatures, C parser and more", "T","[?] [-] [num|msg]", "Text log utility (used to chat, sync, log, ...)", "u","[?]", "uname/undo seek/write", "v","", "panels mode", "V", "", "visual mode (Vv = func/var anal, VV = graph mode, ...)", "w","[?] [str]", "multiple write operations", "x","[?] [len]", "alias for 'px' (print hexadecimal)", "y","[?] [len] [[[@]addr", "Yank/paste bytes from/to memory", "z", "[?]", "zignatures management", "?[??]","[expr]", "Help or evaluate math expression", "?$?", "", "show available '$' variables and aliases", "?@?", "", "misc help for '@' (seek), '~' (grep) (see ~?\"\"?)", "?>?", "", "output redirection", "?|?", "", "help for '|' (pipe)", NULL }; static const char *help_msg_question_e[] = { "Usage: ?e[=bdgnpst] arg", "print/echo things", "", "?e", "", "echo message with newline", "?e=", " 32", "progress bar at 32 percentage", "?eb", " 10 20 30", "proportional segments bar", "?ed", " 1", "draw a 3D ascii donut at the given animation frame", "?eg", " 10 20", "move cursor to column 10, row 20", "?en", " nonl", "echo message without ending newline", "?ep", " 10 20 30", "draw a pie char with given portion sizes", "?es", " msg", "speak message using the text-to-speech program (e cfg.tts)", "?et", " msg", "change terminal title", NULL }; static const char *help_msg_question[] = { "Usage: ?[?[?]] expression", "", "", "?!", " [cmd]", "run cmd if $? == 0", "?", " eip-0x804800", "show all representation result for this math expr", "?$", "", "show value all the variables ($)", "?+", " [cmd]", "run cmd if $? > 0", "?-", " [cmd]", "run cmd if $? < 0", "?:", "", "list core cmd plugins", "?=", " eip-0x804800", "hex and dec result for this math expr", "?==", " x86 `e asm.arch`", "strcmp two strings", "??", " [cmd]", "run cmd if $? != 0", "??", "", "show value of operation", "?a", "", "show ascii table", "?B", " [elem]", "show range boundaries like 'e?search.in", "?b", " [num]", "show binary value of number", "?b64[-]", " [str]", "encode/decode in base64", "?btw", " num|expr num|expr num|expr", "returns boolean value of a <= b <= c", "?e", "[=bdgnpst] arg", "echo messages, bars, pie charts and more (see ?e? for details)", "?f", " [num] [str]", "map each bit of the number as flag string index", "?F", "", "flush cons output", "?h", " [str]", "calculate hash for given string", "?i", "[ynmkp] arg", "prompt for number or Yes,No,Msg,Key,Path and store in $$?", "?ik", "", "press any key input dialog", "?im", " message", "show message centered in screen", "?in", " prompt", "noyes input prompt", "?ip", " prompt", "path input prompt", "?iy", " prompt", "yesno input prompt", "?j", " arg", "same as '? num' but in JSON", "?l", "[q] str", "returns the length of string ('q' for quiet, just set $?)", "?o", " num", "get octal value", "?P", " paddr", "get virtual address for given physical one", "?p", " vaddr", "get physical address for given virtual address", "?q", " eip-0x804800", "compute expression like ? or ?v but in quiet mode", "?r", " [from] [to]", "generate random number between from-to", "?s", " from to step", "sequence of numbers from to by steps", "?t", " cmd", "returns the time to run a command", "?T", "", "show loading times", "?u", " num", "get value in human units (KB, MB, GB, TB)", "?v", " eip-0x804800", "show hex value of math expr", "?V", "", "show library version of r_core", "?vi", " rsp-rbp", "show decimal value of math expr", "?w", " addr", "show what's in this address (like pxr/pxq does)", "?X", " num|expr", "returns the hexadecimal value numeric expr", "?x", " str", "returns the hexpair of number or string", "?x", "+num", "like ?v, but in hexpairs honoring cfg.bigendian", "?x", "-hexst", "convert hexpair into raw string with newline", "?_", " hudfile", "load hud menu with given file", "[cmd]?*", "", "recursive help for the given cmd", NULL }; static const char *help_msg_question_v[] = { "Usage: ?v [$.]","","", "flag", "", "offset of flag", "$", "{ev}", "get value of eval config variable", "$$", "", "here (current virtual seek)", "$$$", "", "current non-temporary virtual seek", "$?", "", "last comparison value", "$alias", "=value", "alias commands (simple macros)", "$B", "", "base address (aligned lowest map address)", "$b", "", "block size", "$c", "", "get terminal width in character columns", "$Cn", "", "get nth call of function", "$D", "", "current debug map base address ?v $D @ rsp", "$DB", "", "same as dbg.baddr, progam base address", "$DD", "", "current debug map size", "$Dn", "", "get nth data reference in function", "$e", "", "1 if end of block, else 0", "$e", "{flag}", "end of flag (flag->offset + flag->size)", "$f", "", "jump fail address (e.g. jz 0x10 => next instruction)", "$F", "", "Same as $FB", "$Fb", "", "begin of basic block", "$FB", "", "begin of function", "$Fe", "", "end of basic block", "$FE", "", "end of function", "$Ff", "", "function false destination", "$Fi", "", "basic block instructions", "$FI", "", "function instructions", "$Fj", "", "function jump destination", "$fl", "", "flag length (size) at current address (fla; pD $l @ entry0)", "$FS", "", "function size (linear length)", "$Fs", "", "size of the current basic block", "$FSS", "", "function size (sum bb sizes)", "$i", "{n}", "address of nth instruction forward", "$I", "{n}", "address of nth instruction backward (s $I1@$Fe) #last instr in bb", "$j", "", "jump address (e.g. jmp 0x10, jz 0x10 => 0x10)", "$Ja", "", "get nth jump of function", "$k", "{kv}", "get value of an sdb query value", "$l", "", "opcode length", "$M", "", "map address (lowest map address)", "$m", "", "opcode memory reference (e.g. mov eax,[0x10] => 0x10)", "$MM", "", "map size (lowest map address)", "$O", "", "cursor here (current offset pointed by the cursor)", "$o", "", "here (current disk io offset)", "$p", "", "getpid()", "$P", "", "pid of children (only in debug)", "$r", "", "get console height (in rows, see $c for columns)", "$r", "{reg}", "get value of named register", "$s", "", "file size", "$S", "", "section offset", "$SS", "", "section size", "$s", "{flag}", "get size of flag", "$v", "", "opcode immediate value (e.g. lui a0,0x8010 => 0x8010)", "$w", "", "get word size, 4 if asm.bits=32, 8 if 64, ...", "$Xn", "", "get nth xref of function", "RNum", "", "$variables usable in math expressions", NULL }; static const char *help_msg_question_V[] = { "Usage: ?V[jq]","","", "?V", "", "show version information", "?V0", "", "show major version", "?V1", "", "show minor version", "?V2", "", "show patch version", "?Vn", "", "show numeric version (2)", "?Vc", "", "show numeric version", "?Vj", "", "same as above but in JSON", "?Vq", "", "quiet mode, just show the version number", NULL }; static const char *help_msg_greater_sign[] = { "Usage:", "[cmd]>[file]", "redirects console from 'cmd' output to 'file'", "[cmd] > [file]", "", "redirect STDOUT of 'cmd' to 'file'", "[cmd] > $alias", "", "save the output of the command as an alias (see $?)", "[cmd] H> [file]", "", "redirect html output of 'cmd' to 'file'", "[cmd] 2> [file]", "", "redirect STDERR of 'cmd' to 'file'", "[cmd] 2> /dev/null", "", "omit the STDERR output of 'cmd'", NULL }; static const char *help_msg_intro[] = { "Usage: [.][times][cmd][~grep][@[@iter]addr!size][|>pipe] ; ...", "", "", "Append '?' to any char command to get detailed help", "", "", "Prefix with number to repeat command N times (f.ex: 3x)", "", "", NULL }; static void cmd_help_exclamation(RCore *core) { r_core_cmd_help (core, help_msg_exclamation); r_core_cmd_help (core, help_msg_env); } static void cmd_help_percent(RCore *core) { r_core_cmd_help (core, help_msg_percent); r_core_cmd_help (core, help_msg_env); } static void cmd_help_init(RCore *core, RCmdDesc *parent) { DEFINE_CMD_DESCRIPTOR_SPECIAL (core, ?, question); DEFINE_CMD_DESCRIPTOR_SPECIAL (core, ?v, question_v); DEFINE_CMD_DESCRIPTOR_SPECIAL (core, ?V, question_V); } static const char* findBreakChar(const char *s) { while (*s) { if (!r_name_validate_char (*s)) { break; } s++; } return s; } static char *filterFlags(RCore *core, const char *msg) { const char *dollar, *end; char *word, *buf = NULL; for (;;) { dollar = strchr (msg, '$'); if (!dollar) { break; } buf = r_str_appendlen (buf, msg, dollar-msg); if (dollar[1]=='{') { // find } end = strchr (dollar+2, '}'); if (end) { word = r_str_newlen (dollar+2, end-dollar-2); end++; } else { msg = dollar+1; buf = r_str_append (buf, "$"); continue; } } else { end = findBreakChar (dollar+1); if (!end) { end = dollar + strlen (dollar); } word = r_str_newlen (dollar+1, end-dollar-1); } if (end && word) { ut64 val = r_num_math (core->num, word); char num[32]; snprintf (num, sizeof (num), "0x%"PFMT64x, val); buf = r_str_append (buf, num); msg = end; } else { break; } free (word); } buf = r_str_append (buf, msg); return buf; } static const char *avatar_orangg[] = { " _______\n" " / \\ .-%s-.\n" " _| ( o) (o)\\_ | %s |\n" " / _ .\\. | \\ <| %s |\n" " \\| \\ ____ / 7` | %s |\n" " '|\\| `---'/ `-%s-'\n" " | /----. \\\n" " | \\___/ |___\n" " `-----'`-----'\n" }; static const char *avatar_clippy[] = { " .--. .-%s-.\n" " | _| | %s |\n" " | O O < %s |\n" " | | | | %s |\n" " || | / `-%s-'\n" " |`-'|\n" " `---'\n", " .--. .-%s-.\n" " | \\ | %s |\n" " | O o < %s |\n" " | | / | %s |\n" " | ( / `-%s-'\n" " | / \n" " `--'\n", " .--. .-%s-.\n" " | _|_ | %s |\n" " | O O < %s |\n" " | || | %s |\n" " | _:| `-%s-'\n" " | |\n" " `---'\n", }; static const char *avatar_clippy_utf8[] = { " ╭──╮ ╭─%s─╮\n" " │ _│ │ %s │\n" " │ O O < %s │\n" " │ │╭ │ %s │\n" " ││ ││ ╰─%s─╯\n" " │└─┘│\n" " ╰───╯\n", " ╭──╮ ╭─%s─╮\n" " │ ╶│╶ │ %s │\n" " │ O o < %s │\n" " │ │ ╱ │ %s │\n" " │ ╭┘ ╱ ╰─%s─╯\n" " │ ╰ ╱\n" " ╰──'\n", " ╭──╮ ╭─%s─╮\n" " │ _│_ │ %s │\n" " │ O O < %s │\n" " │ │╷ │ %s │\n" " │ ││ ╰─%s─╯\n" " │ ─╯│\n" " ╰───╯\n", }; static const char *avatar_cybcat[] = { " /\\.---./\\ .-%s-.\n" " '-- --' | %s |\n" "---- ^ ^ ---- < %s |\n" " _.- Y -._ | %s |\n" " `-%s-'\n", " /\\.---./\\ .-%s-.\n" " '-- @ @ --' | %s |\n" "---- Y ---- < %s |\n" " _.- O -._ | %s |\n" " `-%s-'\n", " /\\.---./\\ .-%s-.\n" " '-- = = --' | %s |\n" "---- Y ---- < %s |\n" " _.- U -._ | %s |\n" " `-%s-'\n", }; enum { R_AVATAR_ORANGG, R_AVATAR_CYBCAT, R_AVATAR_CLIPPY, }; R_API void r_core_clippy(RCore *core, const char *msg) { int type = R_AVATAR_CLIPPY; if (*msg == '+' || *msg == '3') { char *space = strchr (msg, ' '); if (!space) { return; } type = (*msg == '+')? R_AVATAR_ORANGG: R_AVATAR_CYBCAT; msg = space + 1; } const char *f; int msglen = r_str_len_utf8 (msg); char *s = strdup (r_str_pad (' ', msglen)); char *l; if (type == R_AVATAR_ORANGG) { l = strdup (r_str_pad ('-', msglen)); f = avatar_orangg[0]; } else if (type == R_AVATAR_CYBCAT) { l = strdup (r_str_pad ('-', msglen)); f = avatar_cybcat[r_num_rand (R_ARRAY_SIZE (avatar_cybcat))]; } else if (r_config_get_i (core->config, "scr.utf8")) { l = (char *)r_str_repeat ("─", msglen); f = avatar_clippy_utf8[r_num_rand (R_ARRAY_SIZE (avatar_clippy_utf8))]; } else { l = strdup (r_str_pad ('-', msglen)); f = avatar_clippy[r_num_rand (R_ARRAY_SIZE (avatar_clippy))]; } r_cons_printf (f, l, s, msg, s, l); free (l); free (s); } static int cmd_help(void *data, const char *input) { RCore *core = (RCore *)data; RIOMap *map; const char *k; RListIter *iter; char *p, out[128] = R_EMPTY; ut64 n; int i; RList *tmp; switch (input[0]) { case 't': { // "?t" switch (input[1]) { case '0': core->curtab = 0; break; case '1': if (core->curtab < 0) { core->curtab = 0; } core->curtab ++; break; case ' ': { struct r_prof_t prof; r_prof_start (&prof); r_core_cmd (core, input + 1, 0); r_prof_end (&prof); core->num->value = (ut64)(int)prof.result; eprintf ("%lf\n", prof.result); break; } default: eprintf ("Usage: ?t[0,1] [cmd]\n"); eprintf ("?t pd 32 # show time needed to run 'pd 32'\n"); eprintf ("?t0 # select first visual tab\n"); eprintf ("?t1 # select next visual tab\n"); break; } break; } case 'r': // "?r" { // TODO : Add support for 64bit random numbers ut64 b = 0; ut32 r = UT32_MAX; if (input[1]) { strncpy (out, input+(input[1]==' '? 2: 1), sizeof (out)-1); p = strchr (out + 1, ' '); if (p) { *p = 0; b = (ut32)r_num_math (core->num, out); r = (ut32)r_num_math (core->num, p+1)-b; } else { r = (ut32)r_num_math (core->num, out); } } else { r = 0LL; } if (!r) { r = UT32_MAX >> 1; } core->num->value = (ut64) (b + r_num_rand (r)); r_cons_printf ("0x%"PFMT64x"\n", core->num->value); } break; case 'a': // "?a" r_cons_printf ("%s", ret_ascii_table()); break; case 'b': // "?b" if (input[1] == '6' && input[2] == '4') { //b64 decoding takes at most strlen(str) * 4 const int buflen = (strlen (input+3) * 4) + 1; char* buf = calloc (buflen, sizeof(char)); if (!buf) { return false; } if (input[3] == '-') { r_base64_decode ((ut8*)buf, input + 4, -1); } else if (input[3] == ' ') { r_base64_encode (buf, (const ut8*)input + 4, -1); } r_cons_println (buf); free (buf); } else if (input[1] == 't' && input[2] == 'w') { // "?btw" if (r_num_between (core->num, input + 3) == -1) { eprintf ("Usage: ?btw num|(expr) num|(expr) num|(expr)\n"); } } else { n = r_num_get (core->num, input+1); r_num_to_bits (out, n); r_cons_printf ("%sb\n", out); } break; case 'B': // "?B" k = r_str_trim_head_ro (input + 1); tmp = r_core_get_boundaries_prot (core, -1, k, "search"); if (!tmp) { return false; } r_list_foreach (tmp, iter, map) { r_cons_printf ("0x%"PFMT64x" 0x%"PFMT64x"\n", r_io_map_begin (map), r_io_map_end (map)); } r_list_free (tmp); break; case 'h': // "?h" if (input[1] == ' ') { r_cons_printf ("0x%08x\n", (ut32)r_str_hash (input + 2)); } else { eprintf ("Usage: ?h [string-to-hash]\n"); } break; case 'F': // "?F" r_cons_flush (); break; case 'f': // "?f" if (input[1] == ' ') { char *q, *p = strdup (input + 2); if (!p) { eprintf ("Cannot strdup\n"); return 0; } q = strchr (p, ' '); if (q) { *q = 0; n = r_num_get (core->num, p); r_str_bits (out, (const ut8*)&n, sizeof (n) * 8, q + 1); r_cons_println (out); } else { eprintf ("Usage: \"?b value bitstring\"\n"); } free (p); } else { eprintf ("Whitespace expected after '?f'\n"); } break; case 'o': // "?o" n = r_num_math (core->num, input+1); r_cons_printf ("0%"PFMT64o"\n", n); break; case 'T': // "?T" r_cons_printf("plug.init = %"PFMT64d"\n" "plug.load = %"PFMT64d"\n" "file.load = %"PFMT64d"\n", core->times->loadlibs_init_time, core->times->loadlibs_time, core->times->file_open_time); break; case 'u': // "?u" { char unit[8]; n = r_num_math (core->num, input+1); r_num_units (unit, sizeof (unit), n); r_cons_println (unit); } break; case 'j': // "?j" case ' ': // "? " { char *asnum, unit[8]; ut32 s, a; double d; float f; char * const inputs = strdup (input + 1); RList *list = r_num_str_split_list (inputs); const int list_len = r_list_length (list); PJ *pj = NULL; if (*input == 'j') { pj = pj_new (); pj_o (pj); } for (i = 0; i < list_len; i++) { const char *str = r_list_pop_head (list); if (!*str) { continue; } n = r_num_math (core->num, str); if (core->num->dbz) { eprintf ("RNum ERROR: Division by Zero\n"); } asnum = r_num_as_string (NULL, n, false); /* decimal, hexa, octal */ s = n >> 16 << 12; a = n & 0x0fff; r_num_units (unit, sizeof (unit), n); if (*input == 'j') { pj_ks (pj, "int32", sdb_fmt ("%d", (st32)(n & UT32_MAX))); pj_ks (pj, "uint32", sdb_fmt ("%u", (ut32)n)); pj_ks (pj, "int64", sdb_fmt ("%"PFMT64d, (st64)n)); pj_ks (pj, "uint64", sdb_fmt ("%"PFMT64u, (ut64)n)); pj_ks (pj, "hex", sdb_fmt ("0x%08"PFMT64x, n)); pj_ks (pj, "octal", sdb_fmt ("0%"PFMT64o, n)); pj_ks (pj, "unit", unit); pj_ks (pj, "segment", sdb_fmt ("%04x:%04x", s, a)); } else { if (n >> 32) { r_cons_printf ("int64 %"PFMT64d"\n", (st64)n); r_cons_printf ("uint64 %"PFMT64u"\n", (ut64)n); } else { r_cons_printf ("int32 %d\n", (st32)n); r_cons_printf ("uint32 %u\n", (ut32)n); } r_cons_printf ("hex 0x%"PFMT64x"\n", n); r_cons_printf ("octal 0%"PFMT64o"\n", n); r_cons_printf ("unit %s\n", unit); r_cons_printf ("segment %04x:%04x\n", s, a); if (asnum) { r_cons_printf ("string \"%s\"\n", asnum); free (asnum); } } /* binary and floating point */ r_str_bits64 (out, n); f = d = core->num->fvalue; memcpy (&f, &n, sizeof (f)); memcpy (&d, &n, sizeof (d)); /* adjust sign for nan floats, different libcs are confused */ if (isnan (f) && signbit (f)) { f = -f; } if (isnan (d) && signbit (d)) { d = -d; } if (*input == 'j') { pj_ks (pj, "fvalue", sdb_fmt ("%.1lf", core->num->fvalue)); pj_ks (pj, "float", sdb_fmt ("%ff", f)); pj_ks (pj, "double", sdb_fmt ("%lf", d)); pj_ks (pj, "binary", sdb_fmt ("0b%s", out)); r_num_to_ternary (out, n); pj_ks (pj, "ternary", sdb_fmt ("0t%s", out)); } else { r_cons_printf ("fvalue: %.1lf\n", core->num->fvalue); r_cons_printf ("float: %ff\n", f); r_cons_printf ("double: %lf\n", d); r_cons_printf ("binary 0b%s\n", out); r_num_to_ternary (out, n); r_cons_printf ("ternary 0t%s\n", out); } } if (*input == 'j') { pj_end (pj); } free (inputs); r_list_free (list); if (pj) { r_cons_printf ("%s\n", pj_string (pj)); pj_free (pj); } } break; case 'q': // "?q" if (core->num->dbz) { eprintf ("RNum ERROR: Division by Zero\n"); } if (input[1] == '?') { r_cons_printf ("|Usage: ?q [num] # Update $? without printing anything\n" "|?q 123; ?? x # hexdump if 123 != 0"); } else { const char *space = strchr (input, ' '); if (space) { n = r_num_math (core->num, space + 1); } else { n = r_num_math (core->num, "$?"); } core->num->value = n; // redundant } break; case 'v': // "?v" { const char *space = strchr (input, ' '); if (space) { n = r_num_math (core->num, space + 1); } else { n = r_num_math (core->num, "$?"); } } if (core->num->dbz) { eprintf ("RNum ERROR: Division by Zero\n"); } switch (input[1]) { case '?': r_cons_printf ("|Usage: ?v[id][ num] # Show value\n" "|?vx number -> show 8 digit padding in hex\n" "|?vi1 200 -> 1 byte size value (char)\n" "|?vi2 0xffff -> 2 byte size value (short)\n" "|?vi4 0xffff -> 4 byte size value (int)\n" "|?vi8 0xffff -> 8 byte size value (st64)\n" "| No argument shows $? value\n" "|?vi will show in decimal instead of hex\n"); break; case '\0': r_cons_printf ("%d\n", (st32)n); break; case 'x': // "?vx" r_cons_printf ("0x%08"PFMT64x"\n", n); break; case 'i': // "?vi" switch (input[2]) { case '1': // byte r_cons_printf ("%d\n", (st8)(n & UT8_MAX)); break; case '2': // word r_cons_printf ("%d\n", (st16)(n & UT16_MAX)); break; case '4': // dword r_cons_printf ("%d\n", (st32)(n & UT32_MAX)); break; case '8': // qword r_cons_printf ("%"PFMT64d"\n", (st64)(n & UT64_MAX)); break; default: r_cons_printf ("%"PFMT64d"\n", n); break; } break; case 'd': r_cons_printf ("%"PFMT64d"\n", n); break; default: r_cons_printf ("0x%"PFMT64x"\n", n); } core->num->value = n; // redundant break; case '=': // "?=" set num->value if (input[1] == '=') { // ?== if (input[2] == ' ') { char *s = strdup (input + 3); char *e = strchr (s, ' '); if (e) { *e++ = 0; core->num->value = strcmp (s, e); } else { eprintf ("Missing secondary word in expression to compare\n"); } free (s); } else { eprintf ("Usage: ?== str1 str2\n"); } } else { if (input[1]) { // ?= r_num_math (core->num, input+1); } else { r_cons_printf ("0x%"PFMT64x"\n", core->num->value); } } break; case '+': // "?+" if (input[1]) { st64 n = (st64)core->num->value; if (n > 0) { r_core_cmd (core, input + 1, 0); } } else { r_cons_printf ("0x%"PFMT64x"\n", core->num->value); } break; case '-': // "?-" if (input[1]) { st64 n = (st64)core->num->value; if (n < 0) { r_core_cmd (core, input + 1, 0); } } else { r_cons_printf ("0x%"PFMT64x"\n", core->num->value); } break; case '!': // "?!" if (input[1]) { if (!core->num->value) { if (input[1] == '?') { cmd_help_exclamation (core); return 0; } return core->num->value = r_core_cmd (core, input+1, 0); } } else { r_cons_printf ("0x%"PFMT64x"\n", core->num->value); } break; case '@': // "?@" if (input[1] == '@') { if (input[2] == '@') { r_core_cmd_help (core, help_msg_at_at_at); } else { r_core_cmd_help (core, help_msg_at_at); } } else { r_core_cmd_help (core, help_msg_at); } break; case '&': // "?&" helpCmdTasks (core); break; case '%': // "?%" if (input[1] == '?') { cmd_help_percent (core); } break; case '$': // "?$" if (input[1] == '?') { r_core_cmd_help (core, help_msg_question_v); } else { int i = 0; const char *vars[] = { "$$", "$$$", "$?", "$B", "$b", "$c", "$Cn", "$D", "$DB", "$DD", "$Dn", "$e", "$f", "$F", "$Fb", "$FB", "$Fe", "$FE", "$Ff", "$Fi", "$FI", "$Fj", "$fl", "$FS", "$Fs", "$FSS", "$i", "$j", "$Ja", "$l", "$M", "$m", "$MM", "$O", "$o", "$p", "$P", "$r", "$s", "$S", "$SS", "$v", "$w", "$Xn", NULL }; const bool wideOffsets = r_config_get_i (core->config, "scr.wideoff"); while (vars[i]) { const char *pad = r_str_pad (' ', 6 - strlen (vars[i])); if (wideOffsets) { eprintf ("%s %s 0x%016"PFMT64x"\n", vars[i], pad, r_num_math (core->num, vars[i])); } else { eprintf ("%s %s 0x%08"PFMT64x"\n", vars[i], pad, r_num_math (core->num, vars[i])); } i++; } } return true; case 'V': // "?V" switch (input[1]) { case '?': // "?V?" r_core_cmd_help (core, help_msg_question_V); break; case 0: // "?V" #if R2_VERSION_COMMIT == 0 r_cons_printf ("%s release\n", R2_VERSION); #else if (!strcmp (R2_VERSION, R2_GITTAP)) { r_cons_printf ("%s %d\n", R2_VERSION, R2_VERSION_COMMIT); } else { r_cons_printf ("%s aka %s commit %d\n", R2_VERSION, R2_GITTAP, R2_VERSION_COMMIT); } #endif break; case 'c': // "?Vc" r_cons_printf ("%d\n", vernum (R2_VERSION)); break; case 'j': // "?Vj" { PJ *pj = pj_new (); pj_o (pj); pj_ks (pj, "arch", R_SYS_ARCH); pj_ks (pj, "os", R_SYS_OS); pj_ki (pj, "bits", R_SYS_BITS); pj_ki (pj, "commit", R2_VERSION_COMMIT); pj_ks (pj, "tap", R2_GITTAP); pj_ki (pj, "major", R2_VERSION_MAJOR); pj_ki (pj, "minor", R2_VERSION_MINOR); pj_ki (pj, "patch", R2_VERSION_PATCH); pj_ki (pj, "number", R2_VERSION_NUMBER); pj_ki (pj, "nversion", vernum (R2_VERSION)); pj_ks (pj, "version", R2_VERSION); pj_end (pj); r_cons_printf ("%s\n", pj_string (pj)); pj_free (pj); } break; case 'n': // "?Vn" r_cons_printf ("%d\n", R2_VERSION_NUMBER); break; case 'q': // "?Vq" r_cons_println (R2_VERSION); break; case '0': r_cons_printf ("%d\n", R2_VERSION_MAJOR); break; case '1': r_cons_printf ("%d\n", R2_VERSION_MINOR); break; case '2': r_cons_printf ("%d\n", R2_VERSION_PATCH); break; } break; case 'l': // "?l" if (input[1] == 'q') { for (input += 2; input[0] == ' '; input++); core->num->value = strlen (input); } else { for (input++; input[0] == ' '; input++); core->num->value = strlen (input); r_cons_printf ("%" PFMT64d "\n", core->num->value); } break; case 'X': // "?X" for (input++; input[0] == ' '; input++); n = r_num_math (core->num, input); r_cons_printf ("%"PFMT64x"\n", n); break; case 'x': // "?x" for (input++; input[0] == ' '; input++); if (*input == '-') { ut8 *out = malloc (strlen (input) + 1); if (out) { int len = r_hex_str2bin (input + 1, out); if (len >= 0) { out[len] = 0; r_cons_println ((const char*)out); } else { eprintf ("Error parsing the hexpair string\n"); } free (out); } } else if (*input == '+') { ut64 n = r_num_math (core->num, input); int bits = r_num_to_bits (NULL, n) / 8; for (i = 0; i < bits; i++) { r_cons_printf ("%02x", (ut8)((n >> (i * 8)) &0xff)); } r_cons_newline (); } else { if (*input == ' ') { input++; } for (i = 0; input[i]; i++) { r_cons_printf ("%02x", input[i]); } r_cons_newline (); } break; case 'E': // "?E" clippy echo r_core_clippy (core, r_str_trim_head_ro (input + 1)); break; case 'e': // "?e" echo switch (input[1]) { case 't': // "?e=t newtitle" r_cons_set_title (r_str_trim_head_ro (input + 2)); break; case '=': { // "?e=" ut64 pc = r_num_math (core->num, input + 2); r_print_progressbar (core->print, pc, 80); r_cons_newline (); break; } case 'b': { // "?eb" char *arg = strdup (r_str_trim_head_ro (input + 2)); int n = r_str_split (arg, ' '); ut64 *portions = calloc (n, sizeof (ut64)); for (i = 0; i < n; i++) { portions[i] = r_num_math (core->num, r_str_word_get0 (arg, i)); } r_print_portionbar (core->print, portions, n); free (arg); break; } case 's': { // "?es" char *msg = strdup (input + 2); r_str_trim (msg); char *p = strchr (msg, '&'); if (p) *p = 0; r_sys_tts (msg, p != NULL); free (msg); break; } case 'c': // "?ec" column r_cons_column (r_num_math (core->num, input + 2)); break; case 'g': { // "?eg" gotoxy int x = atoi (input + 2); char *arg = strchr (input + 2, ' '); int y = arg? atoi (arg + 1): 0; r_cons_gotoxy (x, y); } break; case 'n': { // "?en" echo -n const char *msg = r_str_trim_head_ro (input + 2); // TODO: replace all ${flagname} by its value in hexa char *newmsg = filterFlags (core, msg); r_str_unescape (newmsg); r_cons_print (newmsg); free (newmsg); break; } case 'd': // "?ed" if (input[2] == 'd') { int i,j; r_cons_show_cursor (0); r_cons_clear00 (); for (i = 1; i < 100; i++) { if (r_cons_is_breaked ()) { break; } for (j = 0; j < 20; j++) { char *d = r_str_donut (i); r_cons_gotoxy (0,0); r_str_trim_tail (d); r_cons_clear_line (0); r_cons_printf ("Downloading the Gibson...\n\n"); r_core_cmdf (core, "?e=%d", i); r_cons_strcat (d); r_cons_clear_line (0); r_cons_newline (); free (d); r_cons_flush (); r_sys_usleep (2000); } } r_cons_clear00(); r_cons_printf ("\nPayload installed. Thanks for your patience.\n\n"); } else { char *d = r_str_donut (r_num_math (core->num, input + 2)); r_str_trim_tail (d); const char *color = (core->cons && core->cons->context->pal.flag)? core->cons->context->pal.flag: ""; r_cons_printf ("%s%s", color, d); r_cons_newline (); free (d); } break; case 'p': { char *word, *str = strdup (input + 2); RList *list = r_str_split_list (str, " ", 0); ut64 *nums = calloc (sizeof (ut64), r_list_length (list)); int i = 0; r_list_foreach (list, iter, word) { nums[i] = r_num_math (core->num, word);; i++; } int size = r_config_get_i (core->config, "hex.cols"); r_print_pie (core->print, nums, r_list_length (list), size); r_list_free (list); } break; case ' ': { const char *msg = r_str_trim_head_ro (input+1); // TODO: replace all ${flagname} by its value in hexa char *newmsg = filterFlags (core, msg); r_str_unescape (newmsg); r_cons_println (newmsg); free (newmsg); } break; case 0: r_cons_newline (); break; default: r_core_cmd_help (core, help_msg_question_e); break; } break; case 's': { // "?s" sequence from to step ut64 from, to, step; char *p, *p2; for (input++; *input==' '; input++); p = strchr (input, ' '); if (p) { *p = '\0'; from = r_num_math (core->num, input); p2 = strchr (p+1, ' '); if (p2) { *p2 = '\0'; step = r_num_math (core->num, p2 + 1); } else { step = 1; } to = r_num_math (core->num, p + 1); for (;from <= to; from += step) r_cons_printf ("%"PFMT64d" ", from); r_cons_newline (); } break; } case 'P': // "?P" if (core->io->va) { ut64 o, n = (input[0] && input[1])? r_num_math (core->num, input+2): core->offset; RIOMap *map = r_io_map_get_paddr (core->io, n); if (map) { o = n + r_io_map_begin (map) - map->delta; r_cons_printf ("0x%08"PFMT64x"\n", o); } else { r_cons_printf ("no map at 0x%08"PFMT64x"\n", n); } } else { r_cons_printf ("0x%08"PFMT64x"\n", core->offset); } break; case 'p': // "?p" if (core->io->va) { // physical address ut64 o, n = (input[0] && input[1])? r_num_math (core->num, input + 2): core->offset; RIOMap *map = r_io_map_get_at (core->io, n); if (map) { o = n - r_io_map_begin (map) + map->delta; r_cons_printf ("0x%08"PFMT64x"\n", o); } else { r_cons_printf ("no map at 0x%08"PFMT64x"\n", n); } } else { r_cons_printf ("0x%08"PFMT64x"\n", core->offset); } break; case '_': // "?_" hud input r_core_yank_hud_file (core, input+1); break; case 'i': // "?i" input num r_cons_set_raw(0); if (!r_cons_is_interactive ()) { eprintf ("Not running in interactive mode\n"); } else { switch (input[1]) { case 'f': // "?if" core->num->value = !r_num_conditional (core->num, input + 2); eprintf ("%s\n", r_str_bool (!core->num->value)); break; case 'm': // "?im" r_cons_message (input + 2); break; case 'p': // "?ip" core->num->value = r_core_yank_hud_path (core, input + 2, 0) == true; break; case 'k': // "?ik" r_cons_any_key (NULL); break; case 'y': // "?iy" for (input += 2; *input==' '; input++); core->num->value = r_cons_yesno (1, "%s? (Y/n)", input); break; case 'n': // "?in" for (input += 2; *input==' '; input++); core->num->value = r_cons_yesno (0, "%s? (y/N)", input); break; default: { char foo[1024]; r_cons_flush (); for (input++; *input == ' '; input++); // TODO: r_cons_input() snprintf (foo, sizeof (foo) - 1, "%s: ", input); r_line_set_prompt (foo); r_cons_fgets (foo, sizeof (foo), 0, NULL); foo[sizeof (foo) - 1] = 0; r_core_yank_set_str (core, R_CORE_FOREIGN_ADDR, foo, strlen (foo) + 1); core->num->value = r_num_math (core->num, foo); } break; } } r_cons_set_raw (0); break; case 'w': { // "?w" ut64 addr = r_num_math (core->num, input + 1); char *rstr = core->print->hasrefs (core->print->user, addr, true); if (!rstr) { eprintf ("Cannot get refs\n"); break; } r_cons_println (rstr); free (rstr); break; } case '?': // "??" if (input[1] == '?') { if (input[2] == '?') { // "???" r_core_clippy (core, "What are you doing?"); return 0; } if (input[2]) { if (core->num->value) { r_core_cmd (core, input + 1, 0); } break; } r_core_cmd_help (core, help_msg_question); return 0; } else if (input[1]) { if (core->num->value) { core->num->value = r_core_cmd (core, input+1, 0); } } else { if (core->num->dbz) { eprintf ("RNum ERROR: Division by Zero\n"); } r_cons_printf ("%"PFMT64d"\n", core->num->value); } break; case '\0': // "?" default: // TODO #7967 help refactor r_core_cmd_help (core, help_msg_intro); r_core_cmd_help (core, help_msg_root); break; } return 0; }
29.5392
107
0.532743
[ "3d" ]
e760781caa142ab17a9eb174bb45eeee7635e8b1
7,259
h
C
src/irr/asset/CXMeshFileLoader.h
qbasa12/IrrlichtBAW
6473f1dcd440eddaaacee9c33c782697a262f7ac
[ "Apache-2.0" ]
null
null
null
src/irr/asset/CXMeshFileLoader.h
qbasa12/IrrlichtBAW
6473f1dcd440eddaaacee9c33c782697a262f7ac
[ "Apache-2.0" ]
2
2019-05-20T12:28:51.000Z
2019-05-24T10:33:41.000Z
src/irr/asset/CXMeshFileLoader.h
manhnt9/IrrlichtBAW
502f2200070d8181f235294403a7de63782e9dcc
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_X_MESH_FILE_LOADER_H_INCLUDED__ #define __C_X_MESH_FILE_LOADER_H_INCLUDED__ #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_X_LOADER_ #include "irr/asset/IAssetLoader.h" #include "irr/asset/CCPUSkinnedMesh.h" #include <sstream> namespace irr { class IrrlichtDevice; namespace io { class IFileSystem; class IReadFile; } // end namespace io namespace scene { class ISceneManager; } namespace asset { #include "irr/irrpack.h" struct SkinnedVertexIntermediateData { SkinnedVertexIntermediateData() { memset(this, 0, 20); } uint8_t boneIDs[4]; float boneWeights[4]; } PACK_STRUCT; struct SkinnedVertexFinalData { public: uint8_t boneIDs[4]; //! rgb10a2 uint32_t boneWeights; } PACK_STRUCT; #include "irr/irrunpack.h" //! Meshloader capable of loading x meshes. class CXMeshFileLoader : public asset::IAssetLoader { public: //! Constructor CXMeshFileLoader(IrrlichtDevice* _dev); ~CXMeshFileLoader(); virtual bool isALoadableFileFormat(io::IReadFile* _file) const override; virtual const char** getAssociatedFileExtensions() const override { static const char* ext[]{ "x", nullptr }; return ext; } virtual uint64_t getSupportedAssetTypesBitfield() const override { return asset::IAsset::ET_MESH; } //! creates/loads an animated mesh from the file. virtual asset::IAsset* loadAsset(io::IReadFile* _file, const asset::IAssetLoader::SAssetLoadParams& _params, asset::IAssetLoader::IAssetLoaderOverride* _override = nullptr, uint32_t _hierarchyLevel = 0u) override; struct SXTemplateMaterial { std::string Name; // template name from Xfile video::SCPUMaterial Material; // material }; //! REMOVE EVENTUALLY struct SXVertex { core::vector3df Pos; core::vector3df Normal; core::vector2df TCoords; }; struct SXMesh { SXMesh() : BoneCount(0),AttachedJointID(-1), HasVertexColors(false) {} // this mesh contains triangulated texture data. // because in an .x file, faces can be made of more than 3 // vertices, the indices data structure is triangulated during the // loading process. The IndexCountPerFace vector is filled during // this triangulation process and stores how much indices belong to // every face. This data structure can be ignored, because all data // in this structure is triangulated. core::stringc Name; uint32_t BoneCount; core::vector<uint16_t> IndexCountPerFace; // default 3, but could be more core::vector<asset::ICPUSkinnedMeshBuffer*> Buffers; core::vector<SXVertex> Vertices; core::vector<uint32_t> Colors; core::vector<core::vector2df> TCoords2; core::vector<SkinnedVertexIntermediateData> VertexSkinWeights; core::vector<uint32_t> Indices; core::vector<uint32_t> FaceMaterialIndices; // index of material for each face core::vector<video::SCPUMaterial> Materials; // material vector int32_t AttachedJointID; bool HasVertexColors; }; private: struct SContext { SContext(const asset::IAssetLoader::SAssetLoadContext& _inner, asset::IAssetLoader::IAssetLoaderOverride* _ovrr) : Inner(_inner), loaderOverride(_ovrr), AllJoints(0), AnimatedMesh(0), BinaryNumCount(0), CurFrame(0), MajorVersion(0), MinorVersion(0), BinaryFormat(false), FloatSize(0) {} ~SContext() { for (SXMesh* m : Meshes) delete m; } core::vector<asset::ICPUSkinnedMesh::SJoint*> *AllJoints; asset::CCPUSkinnedMesh* AnimatedMesh; std::istringstream fileContents; // counter for number arrays in binary format uint32_t BinaryNumCount; io::path FilePath; asset::ICPUSkinnedMesh::SJoint *CurFrame; core::vector<SXMesh*> Meshes; core::vector<SXTemplateMaterial> TemplateMaterials; uint32_t MajorVersion; uint32_t MinorVersion; bool BinaryFormat; int8_t FloatSize; asset::IAssetLoader::SAssetLoadContext Inner; asset::IAssetLoader::IAssetLoaderOverride* loaderOverride; }; bool load(SContext& _ctx, io::IReadFile* file); bool readFileIntoMemory(SContext& _ctx, io::IReadFile* file); bool parseFile(SContext& _ctx); bool parseDataObject(SContext& _ctx); bool parseDataObjectTemplate(SContext& _ctx); bool parseDataObjectFrame(SContext& _ctx, asset::ICPUSkinnedMesh::SJoint *parent); bool parseDataObjectTransformationMatrix(SContext& _ctx, core::matrix4x3 &mat); bool parseDataObjectMesh(SContext& _ctx, SXMesh &mesh); bool parseDataObjectSkinWeights(SContext& _ctx, SXMesh &mesh); bool parseDataObjectSkinMeshHeader(SContext& _ctx, SXMesh &mesh); bool parseDataObjectMeshNormals(SContext& _ctx, SXMesh &mesh); bool parseDataObjectMeshTextureCoords(SContext& _ctx, SXMesh &mesh); bool parseDataObjectMeshVertexColors(SContext& _ctx, SXMesh &mesh); bool parseDataObjectMeshMaterialList(SContext& _ctx, SXMesh &mesh); bool parseDataObjectMaterial(SContext& _ctx, video::SCPUMaterial& material); bool parseDataObjectAnimationSet(SContext& _ctx); bool parseDataObjectAnimation(SContext& _ctx); bool parseDataObjectAnimationKey(SContext& _ctx, asset::ICPUSkinnedMesh::SJoint *joint); bool parseDataObjectTextureFilename(SContext& _ctx, std::string& texturename); bool parseUnknownDataObject(SContext& _ctx); //! places pointer to next begin of a token, and ignores comments void findNextNoneWhiteSpace(SContext& _ctx); //! places pointer to next begin of a token, which must be a number, // and ignores comments void findNextNoneWhiteSpaceNumber(SContext& _ctx); //! returns next parseable token. Returns empty string if no token there std::string getNextToken(SContext& _ctx); //! reads header of dataobject including the opening brace. //! returns false if error happened, and writes name of object //! if there is one bool readHeadOfDataObject(SContext& _ctx, std::string* outname=0); //! checks for closing curly brace, returns false if not there bool checkForClosingBrace(SContext& _ctx); //! checks for one following semicolons, returns false if not there bool checkForOneFollowingSemicolons(SContext& _ctx); //! checks for two following semicolons, returns false if they are not there bool checkForTwoFollowingSemicolons(SContext& _ctx); //! reads a x file style string bool getNextTokenAsString(SContext& _ctx, std::string& out); uint16_t readBinWord(SContext& _ctx); uint32_t readBinDWord(SContext& _ctx); uint32_t readInt(SContext& _ctx); float readFloat(SContext& _ctx); bool readVector2(SContext& _ctx, core::vector2df& vec); bool readVector3(SContext& _ctx, core::vector3df& vec); bool readMatrix(SContext& _ctx, core::matrix4& mat); bool readRGB(SContext& _ctx, video::SColor& color); bool readRGBA(SContext& _ctx, video::SColor& color); IrrlichtDevice* Device; scene::ISceneManager* SceneManager; io::IFileSystem* FileSystem; }; } // end namespace asset } // end namespace irr #endif // _IRR_COMPILE_WITH_X_LOADER_ #endif
29.036
217
0.732883
[ "mesh", "object", "vector" ]
e76344cf96c0348b30e4d035dc2975fba8dfcea5
2,305
h
C
Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UnityEngine_Events_InvokableCallList2295673753MethodDeclarations.h
Yuunagi-Yu/NumberDisk
f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f
[ "MIT" ]
null
null
null
Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UnityEngine_Events_InvokableCallList2295673753MethodDeclarations.h
Yuunagi-Yu/NumberDisk
f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f
[ "MIT" ]
null
null
null
Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UnityEngine_Events_InvokableCallList2295673753MethodDeclarations.h
Yuunagi-Yu/NumberDisk
f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // UnityEngine.Events.InvokableCallList struct InvokableCallList_t2295673753; // UnityEngine.Events.BaseInvokableCall struct BaseInvokableCall_t2229564840; // System.Object struct Il2CppObject; // System.Reflection.MethodInfo struct MethodInfo_t; // System.Object[] struct ObjectU5BU5D_t3614634134; #include "codegen/il2cpp-codegen.h" #include "UnityEngine_UnityEngine_Events_BaseInvokableCall2229564840.h" #include "mscorlib_System_Object2689449295.h" #include "mscorlib_System_Reflection_MethodInfo3330546337.h" // System.Void UnityEngine.Events.InvokableCallList::.ctor() extern "C" void InvokableCallList__ctor_m1209277579 (InvokableCallList_t2295673753 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Events.InvokableCallList::AddPersistentInvokableCall(UnityEngine.Events.BaseInvokableCall) extern "C" void InvokableCallList_AddPersistentInvokableCall_m1312060710 (InvokableCallList_t2295673753 * __this, BaseInvokableCall_t2229564840 * ___call0, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Events.InvokableCallList::AddListener(UnityEngine.Events.BaseInvokableCall) extern "C" void InvokableCallList_AddListener_m786891050 (InvokableCallList_t2295673753 * __this, BaseInvokableCall_t2229564840 * ___call0, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Events.InvokableCallList::RemoveListener(System.Object,System.Reflection.MethodInfo) extern "C" void InvokableCallList_RemoveListener_m3776101648 (InvokableCallList_t2295673753 * __this, Il2CppObject * ___targetObj0, MethodInfo_t * ___method1, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Events.InvokableCallList::ClearPersistent() extern "C" void InvokableCallList_ClearPersistent_m3606847843 (InvokableCallList_t2295673753 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Events.InvokableCallList::Invoke(System.Object[]) extern "C" void InvokableCallList_Invoke_m1839244635 (InvokableCallList_t2295673753 * __this, ObjectU5BU5D_t3614634134* ___parameters0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
53.604651
205
0.846421
[ "object" ]
e765e835c8ac5b8a0c720a503e6a65fc25be8314
5,813
h
C
System/Library/Frameworks/MediaPlayer.framework/MPMediaLibraryEntityTranslator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/Frameworks/MediaPlayer.framework/MPMediaLibraryEntityTranslator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/Frameworks/MediaPlayer.framework/MPMediaLibraryEntityTranslator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:39:52 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <MediaPlayer/MediaPlayer-Structs.h> @class NSMutableDictionary; @interface MPMediaLibraryEntityTranslator : NSObject { NSMutableDictionary* _propertiesToTranslators; NSMutableDictionary* _relationshipsToTranslators; BOOL _transient; Class _MPModelClass; EntityClass* _entityClass; /*^block*/id _allowedItemPredicatesBlock; /*^block*/id _entityQueryBlock; } @property (nonatomic,readonly) Class MPModelClass; //@synthesize MPModelClass=_MPModelClass - In the implementation block @property (getter=isTransient,nonatomic,readonly) BOOL transient; //@synthesize transient=_transient - In the implementation block @property (nonatomic,readonly) EntityClass* entityClass; //@synthesize entityClass=_entityClass - In the implementation block @property (nonatomic,copy) id allowedItemPredicatesBlock; //@synthesize allowedItemPredicatesBlock=_allowedItemPredicatesBlock - In the implementation block @property (nonatomic,copy) id entityQueryBlock; //@synthesize entityQueryBlock=_entityQueryBlock - In the implementation block +(id)translatorForTransientMPModelClass:(Class)arg1 ; +(id)translatorForMPModelClass:(Class)arg1 ; +(id)translatorForMPModelClass:(Class)arg1 mlcoreEntityClass:(EntityClass*)arg2 ; +(id)_translatorForMPModelClass:(Class)arg1 mlcoreEntityClass:(EntityClass*)arg2 create:(BOOL)arg3 transient:(BOOL)arg4 ; -(id)entityQueryBlock; -(BOOL)isTransient; -(map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)propertiesToFetchForPropertyKey:(id)arg1 ; -(void)mapPropertyKey:(id)arg1 toMLProperty:(ModelPropertyBase*)arg2 ; -(id)_propertyTranslatorForKeyPath:(id)arg1 ; -(vector<mlcore::ModelPropertyBase *, std::__1::allocator<mlcore::ModelPropertyBase *> >*)_MLCorePropertiesForPropertySet:(id)arg1 withForeignPropertyBase:(ModelPropertyBase*)arg2 ; -(void)mapIdentifierMLProperties:(const map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)arg1 identifierCreationBlock:(/*^block*/id)arg2 ; -(Class)MPModelClass; -(ModelPropertyBase*)_propertyForKeyPath:(id)arg1 ; -(EntityClass*)entityClass; -(shared_ptr<mlcore::PropertiesQuery>*)propertiesQueryForPropertySet:(id)arg1 scopedContainers:(id)arg2 allowedItemIdentifiers:(id)arg3 view:(id)arg4 ; -(Class)classForRelationshipKey:(id)arg1 ; -(void)setEntityQueryBlock:(id)arg1 ; -(void)setAllowedItemPredicatesBlock:(id)arg1 ; -(shared_ptr<mlcore::EntityQuery>*)entityQueryForPropertySet:(id)arg1 sortDescriptors:(id)arg2 context:(id)arg3 view:(id)arg4 ; -(vector<mlcore::ModelPropertyBase *, std::__1::allocator<mlcore::ModelPropertyBase *> >*)MLCorePropertiesForPropertySet:(id)arg1 ; -(id)objectForPropertySet:(id)arg1 entity:(shared_ptr<mlcore::Entity>*)arg2 context:(id)arg3 ; -(id)_objectForPropertySet:(id)arg1 entity:(shared_ptr<mlcore::Entity>*)arg2 baseTranslator:(id)arg3 prependKeyPath:(id)arg4 context:(id)arg5 ; -(id)allowedItemPredicatesBlock; -(void)mapPropertyKey:(id)arg1 withPropertiesToFetch:(const map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)arg2 propertiesToSort:(const map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)arg3 sortTransformer:(/*^block*/id)arg4 valueTransformer:(/*^block*/id)arg5 ; -(void)mapRelationshipKey:(id)arg1 toModelClass:(Class)arg2 usingForeignPropertyBase:(ModelPropertyBase*)arg3 ; -(id)identifiersForEntity:(shared_ptr<mlcore::Entity>*)arg1 context:(id)arg2 ; -(vector<mlcore::SortDescriptor, std::__1::allocator<mlcore::SortDescriptor> >*)MLCoreSortDescriptorsForModelSortDescriptors:(id)arg1 ; -(void)mapPropertyKey:(id)arg1 withPropertiesToFetch:(const map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)arg2 valueTransformer:(/*^block*/id)arg3 ; -(void)mapRelationshipKey:(id)arg1 toModelClass:(Class)arg2 transient:(BOOL)arg3 usingForeignPropertyBase:(ModelPropertyBase*)arg4 ; -(void)mapRelationshipKey:(id)arg1 toModelClass:(Class)arg2 transient:(BOOL)arg3 usingForeignPropertyBase:(ModelPropertyBase*)arg4 relationshipValidationProperties:(const map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)arg5 isValidRelationshipHandler:(/*^block*/id)arg6 ; -(map<std::__1::basic_string<char>, mlcore::ModelPropertyBase *, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, mlcore::ModelPropertyBase *> > >*)_propertyMapForKeyPath:(id)arg1 includePropertiesToSort:(BOOL)arg2 ; -(id)_valueForKeyPath:(id)arg1 forEntity:(shared_ptr<mlcore::Entity>*)arg2 context:(id)arg3 ; @end
90.828125
596
0.770686
[ "vector" ]
e76f2e2ff5dbaed81aa98170c8a675409c82c26d
1,826
c
C
firmware/src/ai/nnom/src/core/nnom_layers.c
noah95/edison
652af8ed4c99c11000a6c0136d770583a5318d8e
[ "Apache-2.0" ]
3
2020-09-16T18:43:40.000Z
2022-03-24T12:09:05.000Z
azure-sphere-combo-mnist-rtcore/nnom/src/core/nnom_layers.c
xiongyu0523/azure-sphere-combo-mnist
e78f682c47675cf6c92bef5ff24128eb352a1152
[ "MIT" ]
13
2020-11-13T18:50:47.000Z
2022-03-12T00:29:36.000Z
azure-sphere-combo-mnist-rtcore/nnom/src/core/nnom_layers.c
xiongyu0523/azure-sphere-combo-mnist
e78f682c47675cf6c92bef5ff24128eb352a1152
[ "MIT" ]
2
2020-09-16T18:43:46.000Z
2021-04-14T06:33:53.000Z
/* * Copyright (c) 2018-2019 * Jianjia Ma, Wearable Bio-Robotics Group (WBR) * majianjia@live.com * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2019-02-05 Jianjia Ma The first version */ #include <stdint.h> #include <string.h> #include <stdbool.h> #include "nnom.h" #include "nnom_local.h" #include "nnom_layers.h" size_t shape_size(nnom_shape_t *s) { if (s == NULL) return 0; return s->h * s->w * s->c; } nnom_shape_t shape(size_t h, size_t w, size_t c) { nnom_shape_t s; s.h = h; s.w = w; s.c = c; return s; } nnom_shape_t kernel(size_t h, size_t w) { return shape(h, w, 1); } nnom_shape_t stride(size_t h, size_t w) { return shape(h, w, 1); } nnom_border_t border(size_t top, size_t bottom, size_t left, size_t right) { nnom_border_t b; b.top = top; b.bottom = bottom; b.left = left; b.right = right; return b; } nnom_qformat_t qformat(int8_t m, int8_t n) { nnom_qformat_t fmt; fmt.n = n; fmt.m = m; return fmt; } // this function has to be used while assign a io for a layer. // because the io needs to know who is its owner. nnom_layer_io_t *io_init(void *owner_layer, nnom_layer_io_t *io) { io->owner = (nnom_layer_t *)owner_layer; return io; } // this function is to add a new IO to current inited IO // input, the targeted IO that the new IO will be added to // output , the new IO nnom_layer_io_t *io_add_aux(nnom_layer_io_t *targeted_io) { nnom_layer_io_t *new_io; // check if the targeted io is inited, and its aux = NULL if (targeted_io == NULL || targeted_io->owner == NULL || targeted_io->aux != NULL) return NULL; // create new io, init it new_io = nnom_mem(sizeof(nnom_layer_io_t)); if (new_io == NULL) return NULL; // add to aux targeted_io->aux = new_io; return io_init(targeted_io->owner, new_io); }
21.232558
83
0.680723
[ "shape" ]
e7704fe151be5a052f9698fed7185ce0ac1ff618
12,444
h
C
applications/mne_scan/plugins/tmsi/tmsi.h
slew/mne-cpp
94ae7dae593cd3cc783730a7538ca85bd9ba3b63
[ "BSD-3-Clause" ]
null
null
null
applications/mne_scan/plugins/tmsi/tmsi.h
slew/mne-cpp
94ae7dae593cd3cc783730a7538ca85bd9ba3b63
[ "BSD-3-Clause" ]
null
null
null
applications/mne_scan/plugins/tmsi/tmsi.h
slew/mne-cpp
94ae7dae593cd3cc783730a7538ca85bd9ba3b63
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file tmsi.h * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Lorenz Esch <lesch@mgh.harvard.edu>; * Viktor Klueber <Viktor.Klueber@tu-ilmenau.de> * @since 0.1.0 * @date September, 2013 * * @section LICENSE * * Copyright (C) 2013, Christoph Dinh, Lorenz Esch, Viktor Klueber. 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 MNE-CPP authors 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. * * * @brief Contains the declaration of the TMSI class. * */ #ifndef TMSI_H #define TMSI_H //============================================================================================================= // INCLUDES //============================================================================================================= #include "tmsi_global.h" #include "FormFiles/tmsisetupwidget.h" #include "FormFiles/tmsimanualannotationwidget.h" #include "FormFiles/tmsiimpedancewidget.h" #include "FormFiles/tmsisetupprojectwidget.h" #include <iostream> #include <fstream> #include <direct.h> #include <scShared/Plugins/abstractsensor.h> #include <utils/generics/circularbuffer.h> #include <scMeas/realtimemultisamplearray.h> #include <utils/layoutloader.h> #include <fiff/fiff.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtWidgets> #include <QVector> #include <QTime> #include <QtConcurrent/QtConcurrent> //============================================================================================================= // EIGEN INCLUDES //============================================================================================================= #include <unsupported/Eigen/FFT> #include <Eigen/Geometry> //============================================================================================================= // TMSIPLUGIN FORWARD DECLARATIONS //============================================================================================================= namespace FIFFLIB { class FiffInfo; class FiffStream; } //============================================================================================================= // DEFINE NAMESPACE TMSIPLUGIN //============================================================================================================= namespace TMSIPLUGIN { //============================================================================================================= // TMSIPLUGIN FORWARD DECLARATIONS //============================================================================================================= class TMSIProducer; //============================================================================================================= /** * TMSI... * * @brief The TMSI class provides a EEG connector. In order for this plugin to work properly the driver dll "RTINST.dll" must be installed in the system directory. This dll is automatically copied in the system directory during the driver installtion of the TMSi Refa device. */ class TMSISHARED_EXPORT TMSI : public SCSHAREDLIB::AbstractSensor { Q_OBJECT Q_PLUGIN_METADATA(IID "scsharedlib/1.0" FILE "tmsi.json") //NEw Qt5 Plugin system replaces Q_EXPORT_PLUGIN2 macro // Use the Q_INTERFACES() macro to tell Qt's meta-object system about the interfaces Q_INTERFACES(SCSHAREDLIB::AbstractSensor) friend class TMSIProducer; friend class TMSISetupWidget; friend class TMSIImpedanceWidget; friend class TMSISetupProjectWidget; public: //========================================================================================================= /** * Constructs a TMSI. */ TMSI(); //========================================================================================================= /** * Destroys the TMSI. */ virtual ~TMSI(); //========================================================================================================= /** * Clone the plugin */ virtual QSharedPointer<AbstractPlugin> clone() const; //========================================================================================================= /** * Initialise input and output connectors. */ virtual void init(); //========================================================================================================= /** * Is called when plugin is detached of the stage. Can be used to safe settings. */ virtual void unload(); //========================================================================================================= /** * Sets up the fiff info with the current data chosen by the user. Note: Only works for ANT Neuro Waveguard Duke caps. */ void setUpFiffInfo(); //========================================================================================================= /** * Starts the TMSI by starting the tmsi's thread. */ virtual bool start(); //========================================================================================================= /** * Stops the TMSI by stopping the tmsi's thread. */ virtual bool stop(); virtual AbstractPlugin::PluginType getType() const; virtual QString getName() const; virtual QWidget* setupWidget(); void setKeyboardTriggerType(int type); void splitRecordingFile(); protected: //========================================================================================================= /** * The starting point for the thread. After calling start(), the newly created thread calls this function. * Returning from this method will end the execution of the thread. * Pure virtual method inherited by QThread. */ virtual void run(); //========================================================================================================= /** * Opens a widget to check the impedance values */ void showImpedanceDialog(); //========================================================================================================= /** * Opens a dialog to setup the project to check the impedance values */ void showSetupProjectDialog(); //========================================================================================================= /** * Starts data recording */ void showStartRecording(); //========================================================================================================= /** * Implements blinking recording button */ void changeRecordingButton(); //========================================================================================================= /** * Checks if a dir exists */ bool dirExists(const std::string& dirName_in); private: QSharedPointer<SCSHAREDLIB::PluginOutputData<SCMEASLIB::RealTimeMultiSampleArray> > m_pRMTSA_TMSI; /**< The RealTimeSampleArray to provide the EEG data.*/ QSharedPointer<TMSIManualAnnotationWidget> m_pTmsiManualAnnotationWidget; /**< Widget for manually annotation the trigger during session.*/ QSharedPointer<TMSIImpedanceWidget> m_pTmsiImpedanceWidget; /**< Widget for checking the impedances*/ QSharedPointer<TMSISetupProjectWidget> m_pTmsiSetupProjectWidget; /**< Widget for checking the impedances*/ QString m_qStringResourcePath; /**< The path to the EEG resource directory.*/ int m_iSamplingFreq; /**< The sampling frequency defined by the user via the GUI (in Hertz).*/ int m_iNumberOfChannels; /**< The number of channels defined by the user via the GUI.*/ int m_iSamplesPerBlock; /**< The samples per block defined by the user via the GUI.*/ int m_iTriggerInterval; /**< The gap between the trigger signals which request the subject to do something (in ms).*/ QTime m_qTimerTrigger; /**< Time stemp of the last trigger event (in ms).*/ bool m_bUseChExponent; /**< Flag for using the channels exponent. Defined by the user via the GUI.*/ bool m_bUseUnitGain; /**< Flag for using the channels unit gain. Defined by the user via the GUI.*/ bool m_bUseUnitOffset; /**< Flag for using the channels unit offset. Defined by the user via the GUI.*/ bool m_bWriteDriverDebugToFile; /**< Flag for for writing driver debug informstions to a file. Defined by the user via the GUI.*/ bool m_bBeepTrigger; /**< Flag for using a trigger input.*/ bool m_bUseCommonAverage; /**< Flag for using common average.*/ bool m_bUseKeyboardTrigger; /**< Flag for using the keyboard as a trigger input.*/ bool m_bCheckImpedances; /**< Flag for checking the impedances of the EEG amplifier.*/ int m_iTriggerType; /**< Holds the trigger type | 0 - no trigger activated, 254 - left, 253 - right, 252 - beep.*/ QString m_sElcFilePath; /**< Holds the path for the .elc file (electrode positions). Defined by the user via the GUI.*/ QSharedPointer<FIFFLIB::FiffInfo> m_pFiffInfo; /**< Fiff measurement info.*/ QSharedPointer<UTILSLIB::CircularBuffer_Matrix_float> m_pCircularBuffer; /**< Holds incoming raw data.*/ QSharedPointer<TMSIProducer> m_pTMSIProducer; /**< the TMSIProducer.*/ Eigen::MatrixXf m_matOldMatrix; /**< Last received sample matrix by the tmsiproducer/tmsidriver class. Used for simple HP filtering.*/ QMutex m_qMutex; /**< Holds the threads mutex.*/ QAction* m_pActionImpedance; /**< shows impedance widget. */ QAction* m_pActionSetupProject; /**< shows setup project dialog. */ }; } // NAMESPACE #endif // TMSI_H
48.046332
275
0.467213
[ "geometry", "object" ]
e7836db0e9cbe1bb3623651135470b7b7894133d
226,613
c
C
src/dns.c
thelinuxkid/levee
947847fd9e4bf67333f285f13c92e47441b0f8ce
[ "BSD-2-Clause" ]
11
2018-11-05T20:32:06.000Z
2020-08-16T09:32:17.000Z
src/dns.c
thelinuxkid/levee
947847fd9e4bf67333f285f13c92e47441b0f8ce
[ "BSD-2-Clause" ]
null
null
null
src/dns.c
thelinuxkid/levee
947847fd9e4bf67333f285f13c92e47441b0f8ce
[ "BSD-2-Clause" ]
3
2018-09-12T03:53:11.000Z
2021-03-08T04:34:07.000Z
/* ========================================================================== * dns.c - Recursive, Reentrant DNS Resolver. * -------------------------------------------------------------------------- * Copyright (c) 2008, 2009, 2010, 2012-2016 William Ahern * * 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. * ========================================================================== */ #if !defined(__FreeBSD__) && !defined(__sun) #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 600 #endif #undef _BSD_SOURCE #define _BSD_SOURCE #undef _DARWIN_C_SOURCE #define _DARWIN_C_SOURCE #undef _NETBSD_SOURCE #define _NETBSD_SOURCE #endif #include <limits.h> /* INT_MAX */ #include <stddef.h> /* offsetof() */ #ifdef _WIN32 #define uint32_t unsigned int #else #include <stdint.h> /* uint32_t */ #endif #include <stdlib.h> /* malloc(3) realloc(3) free(3) rand(3) random(3) arc4random(3) */ #include <stdio.h> /* FILE fopen(3) fclose(3) getc(3) rewind(3) */ #include <string.h> /* memcpy(3) strlen(3) memmove(3) memchr(3) memcmp(3) strchr(3) strsep(3) strcspn(3) */ #include <strings.h> /* strcasecmp(3) strncasecmp(3) */ #include <ctype.h> /* isspace(3) isdigit(3) */ #include <time.h> /* time_t time(2) difftime(3) */ #include <signal.h> /* SIGPIPE sigemptyset(3) sigaddset(3) sigpending(2) sigprocmask(2) pthread_sigmask(3) sigtimedwait(2) */ #include <errno.h> /* errno EINVAL ENOENT */ #undef NDEBUG #include <assert.h> /* assert(3) */ #if _WIN32 #ifndef FD_SETSIZE #define FD_SETSIZE 256 #endif #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/types.h> /* FD_SETSIZE socklen_t */ #include <sys/select.h> /* FD_ZERO FD_SET fd_set select(2) */ #include <sys/socket.h> /* AF_INET AF_INET6 AF_UNIX struct sockaddr struct sockaddr_in struct sockaddr_in6 socket(2) */ #if defined(AF_UNIX) #include <sys/un.h> /* struct sockaddr_un */ #endif #include <fcntl.h> /* F_SETFD F_GETFL F_SETFL O_NONBLOCK fcntl(2) */ #include <unistd.h> /* _POSIX_THREADS gethostname(3) close(2) */ #include <poll.h> /* POLLIN POLLOUT */ #include <netinet/in.h> /* struct sockaddr_in struct sockaddr_in6 */ #include <arpa/inet.h> /* inet_pton(3) inet_ntop(3) htons(3) ntohs(3) */ #include <netdb.h> /* struct addrinfo */ #endif #include "dns.h" /* * C O M P I L E R V E R S I O N & F E A T U R E D E T E C T I O N * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define DNS_GNUC_2VER(M, m, p) (((M) * 10000) + ((m) * 100) + (p)) #define DNS_GNUC_PREREQ(M, m, p) (__GNUC__ > 0 && DNS_GNUC_2VER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) >= DNS_GNUC_2VER((M), (m), (p))) #define DNS_MSC_2VER(M, m, p) ((((M) + 6) * 10000000) + ((m) * 1000000) + (p)) #define DNS_MSC_PREREQ(M, m, p) (_MSC_VER_FULL > 0 && _MSC_VER_FULL >= DNS_MSC_2VER((M), (m), (p))) #define DNS_SUNPRO_PREREQ(M, m, p) (__SUNPRO_C > 0 && __SUNPRO_C >= 0x ## M ## m ## p) #if defined __has_builtin #define dns_has_builtin(x) __has_builtin(x) #else #define dns_has_builtin(x) 0 #endif #if defined __has_extension #define dns_has_extension(x) __has_extension(x) #else #define dns_has_extension(x) 0 #endif #ifndef HAVE___ASSUME #define HAVE___ASSUME DNS_MSC_PREREQ(8,0,0) #endif #ifndef HAVE___BUILTIN_TYPES_COMPATIBLE_P #define HAVE___BUILTIN_TYPES_COMPATIBLE_P (DNS_GNUC_PREREQ(3,1,1) || __clang__) #endif #ifndef HAVE___BUILTIN_UNREACHABLE #define HAVE___BUILTIN_UNREACHABLE (DNS_GNUC_PREREQ(4,5,0) || dns_has_builtin(__builtin_unreachable)) #endif #ifndef HAVE_PRAGMA_MESSAGE #define HAVE_PRAGMA_MESSAGE (DNS_GNUC_PREREQ(4,4,0) || __clang__ || _MSC_VER) #endif /* * C O M P I L E R A N N O T A T I O N S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if __GNUC__ #define DNS_NOTUSED __attribute__((unused)) #define DNS_NORETURN __attribute__((noreturn)) #else #define DNS_NOTUSED #define DNS_NORETURN #endif #if __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #pragma clang diagnostic ignored "-Wmissing-field-initializers" #elif DNS_GNUC_PREREQ(4,6,0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #endif /* * S T A N D A R D M A C R O S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if HAVE___BUILTIN_TYPES_COMPATIBLE_P #define dns_same_type(a, b, def) __builtin_types_compatible_p(__typeof__ (a), __typeof__ (b)) #else #define dns_same_type(a, b, def) (def) #endif #define dns_isarray(a) (!dns_same_type((a), (&(a)[0]), 0)) /* NB: "_" field silences Sun Studio "zero-sized struct/union" error diagnostic */ #define dns_inline_assert(cond) ((void)(sizeof (struct { int:-!(cond); int _; }))) #if HAVE___ASSUME #define dns_assume(cond) __assume(cond) #elif HAVE___BUILTIN_UNREACHABLE #define dns_assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0) #else #define dns_assume(cond) do { (void)(cond); } while (0) #endif #ifndef lengthof #define lengthof(a) (dns_inline_assert(dns_isarray(a)), (sizeof (a) / sizeof (a)[0])) #endif #ifndef endof #define endof(a) (dns_inline_assert(dns_isarray(a)), &(a)[lengthof((a))]) #endif /* * M I S C E L L A N E O U S C O M P A T * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if _WIN32 || _WIN64 #define PRIuZ "Iu" #else #define PRIuZ "zu" #endif #ifndef DNS_THREAD_SAFE #if (defined _REENTRANT || defined _THREAD_SAFE) && _POSIX_THREADS > 0 #define DNS_THREAD_SAFE 1 #else #define DNS_THREAD_SAFE 0 #endif #endif #ifndef HAVE__STATIC_ASSERT #define HAVE__STATIC_ASSERT \ (dns_has_extension(c_static_assert) || DNS_GNUC_PREREQ(4,6,0) || \ __C11FEATURES__ || __STDC_VERSION__ >= 201112L) #endif #ifndef HAVE_STATIC_ASSERT #if DNS_GNUC_PREREQ(0,0,0) && !DNS_GNUC_PREREQ(4,6,0) #define HAVE_STATIC_ASSERT 0 /* glibc doesn't check GCC version */ #else #define HAVE_STATIC_ASSERT (defined static_assert) #endif #endif #if HAVE_STATIC_ASSERT #define dns_static_assert(cond, msg) static_assert(cond, msg) #elif HAVE__STATIC_ASSERT #define dns_static_assert(cond, msg) _Static_assert(cond, msg) #else #define dns_static_assert(cond, msg) extern char DNS_PP_XPASTE(dns_assert_, __LINE__)[sizeof (int[1 - 2*!(cond)])] #endif /* * D E B U G M A C R O S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int *dns_debug_p(void) { static int debug; return &debug; } /* dns_debug_p() */ #if DNS_DEBUG #undef DNS_DEBUG #define DNS_DEBUG dns_debug #define DNS_SAY_(fmt, ...) \ do { if (DNS_DEBUG > 0) fprintf(stderr, fmt "%.1s", __func__, __LINE__, __VA_ARGS__); } while (0) #define DNS_SAY(...) DNS_SAY_("@@ (%s:%d) " __VA_ARGS__, "\n") #define DNS_HAI DNS_SAY("HAI") #define DNS_SHOW_(P, fmt, ...) do { \ if (DNS_DEBUG > 1) { \ fprintf(stderr, "@@ BEGIN * * * * * * * * * * * *\n"); \ fprintf(stderr, "@@ " fmt "%.0s\n", __VA_ARGS__); \ dns_p_dump((P), stderr); \ fprintf(stderr, "@@ END * * * * * * * * * * * * *\n\n"); \ } \ } while (0) #define DNS_SHOW(...) DNS_SHOW_(__VA_ARGS__, "") #else /* !DNS_DEBUG */ #undef DNS_DEBUG #define DNS_DEBUG 0 #define DNS_SAY(...) #define DNS_HAI #define DNS_SHOW(...) #endif /* DNS_DEBUG */ #define DNS_CARP(...) DNS_SAY(__VA_ARGS__) /* * V E R S I O N R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ const char *dns_vendor(void) { return DNS_VENDOR; } /* dns_vendor() */ int dns_v_rel(void) { return DNS_V_REL; } /* dns_v_rel() */ int dns_v_abi(void) { return DNS_V_ABI; } /* dns_v_abi() */ int dns_v_api(void) { return DNS_V_API; } /* dns_v_api() */ /* * E R R O R R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if _WIN32 #define DNS_EINTR WSAEINTR #define DNS_EINPROGRESS WSAEINPROGRESS #define DNS_EISCONN WSAEISCONN #define DNS_EWOULDBLOCK WSAEWOULDBLOCK #define DNS_EALREADY WSAEALREADY #define DNS_EAGAIN EAGAIN #define DNS_ETIMEDOUT WSAETIMEDOUT #define dns_syerr() ((int)GetLastError()) #define dns_soerr() ((int)WSAGetLastError()) #else #define DNS_EINTR EINTR #define DNS_EINPROGRESS EINPROGRESS #define DNS_EISCONN EISCONN #define DNS_EWOULDBLOCK EWOULDBLOCK #define DNS_EALREADY EALREADY #define DNS_EAGAIN EAGAIN #define DNS_ETIMEDOUT ETIMEDOUT #define dns_syerr() errno #define dns_soerr() errno #endif const char *dns_strerror(int error) { switch (error) { case DNS_ENOBUFS: return "DNS packet buffer too small"; case DNS_EILLEGAL: return "Illegal DNS RR name or data"; case DNS_EORDER: return "Attempt to push RR out of section order"; case DNS_ESECTION: return "Invalid section specified"; case DNS_EUNKNOWN: return "Unknown DNS error"; case DNS_EADDRESS: return "Invalid textual address form"; case DNS_ENOQUERY: return "Bad execution state (missing query packet)"; case DNS_ENOANSWER: return "Bad execution state (missing answer packet)"; case DNS_EFETCHED: return "Answer already fetched"; case DNS_ESERVICE: return "The service passed was not recognized for the specified socket type"; case DNS_ENONAME: return "The name does not resolve for the supplied parameters"; case DNS_EFAIL: return "A non-recoverable error occurred when attempting to resolve the name"; default: return strerror(error); } /* switch() */ } /* dns_strerror() */ /* * A T O M I C R O U T I N E S * * Use GCC's __atomic built-ins if possible. Unlike the __sync built-ins, we * can use the preprocessor to detect API and, more importantly, ISA * support. We want to avoid linking headaches where the API depends on an * external library if the ISA (e.g. i386) doesn't support lockless * operation. * * TODO: Support C11's atomic API. Although that may require some finesse * with how we define some public types, such as dns_atomic_t and struct * dns_resolv_conf. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef HAVE___ATOMIC_FETCH_ADD #define HAVE___ATOMIC_FETCH_ADD (defined __ATOMIC_RELAXED) #endif #ifndef HAVE___ATOMIC_FETCH_SUB #define HAVE___ATOMIC_FETCH_SUB HAVE___ATOMIC_FETCH_ADD #endif #ifndef DNS_ATOMIC_FETCH_ADD #if HAVE___ATOMIC_FETCH_ADD && __GCC_ATOMIC_LONG_LOCK_FREE == 2 #define DNS_ATOMIC_FETCH_ADD(i) __atomic_fetch_add((i), 1, __ATOMIC_RELAXED) #else #pragma message("no atomic_fetch_add available") #define DNS_ATOMIC_FETCH_ADD(i) ((*(i))++) #endif #endif #ifndef DNS_ATOMIC_FETCH_SUB #if HAVE___ATOMIC_FETCH_SUB && __GCC_ATOMIC_LONG_LOCK_FREE == 2 #define DNS_ATOMIC_FETCH_SUB(i) __atomic_fetch_sub((i), 1, __ATOMIC_RELAXED) #else #pragma message("no atomic_fetch_sub available") #define DNS_ATOMIC_FETCH_SUB(i) ((*(i))--) #endif #endif static inline unsigned dns_atomic_fetch_add(dns_atomic_t *i) { return DNS_ATOMIC_FETCH_ADD(i); } /* dns_atomic_fetch_add() */ static inline unsigned dns_atomic_fetch_sub(dns_atomic_t *i) { return DNS_ATOMIC_FETCH_SUB(i); } /* dns_atomic_fetch_sub() */ /* * C R Y P T O R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * P R N G */ #ifndef DNS_RANDOM #if defined(HAVE_ARC4RANDOM) \ || defined(__OpenBSD__) \ || defined(__FreeBSD__) \ || defined(__NetBSD__) \ || defined(__APPLE__) #define DNS_RANDOM arc4random #elif __linux #define DNS_RANDOM random #else #define DNS_RANDOM rand #endif #endif #define DNS_RANDOM_arc4random 1 #define DNS_RANDOM_random 2 #define DNS_RANDOM_rand 3 #define DNS_RANDOM_RAND_bytes 4 #define DNS_RANDOM_OPENSSL (DNS_RANDOM_RAND_bytes == DNS_PP_XPASTE(DNS_RANDOM_, DNS_RANDOM)) #if DNS_RANDOM_OPENSSL #include <openssl/rand.h> #endif static unsigned dns_random_(void) { #if DNS_RANDOM_OPENSSL unsigned r; _Bool ok; ok = (1 == RAND_bytes((unsigned char *)&r, sizeof r)); assert(ok && "1 == RAND_bytes()"); return r; #else return DNS_RANDOM(); #endif } /* dns_random_() */ dns_random_f **dns_random_p(void) { static dns_random_f *random_f = &dns_random_; return &random_f; } /* dns_random_p() */ /* * P E R M U T A T I O N G E N E R A T O R */ #define DNS_K_TEA_KEY_SIZE 16 #define DNS_K_TEA_BLOCK_SIZE 8 #define DNS_K_TEA_CYCLES 32 #define DNS_K_TEA_MAGIC 0x9E3779B9U struct dns_k_tea { uint32_t key[DNS_K_TEA_KEY_SIZE / sizeof (uint32_t)]; unsigned cycles; }; /* struct dns_k_tea */ static void dns_k_tea_init(struct dns_k_tea *tea, uint32_t key[], unsigned cycles) { memcpy(tea->key, key, sizeof tea->key); tea->cycles = (cycles)? cycles : DNS_K_TEA_CYCLES; } /* dns_k_tea_init() */ static void dns_k_tea_encrypt(struct dns_k_tea *tea, uint32_t v[], uint32_t *w) { uint32_t y, z, sum, n; y = v[0]; z = v[1]; sum = 0; for (n = 0; n < tea->cycles; n++) { sum += DNS_K_TEA_MAGIC; y += ((z << 4) + tea->key[0]) ^ (z + sum) ^ ((z >> 5) + tea->key[1]); z += ((y << 4) + tea->key[2]) ^ (y + sum) ^ ((y >> 5) + tea->key[3]); } w[0] = y; w[1] = z; return /* void */; } /* dns_k_tea_encrypt() */ /* * Permutation generator, based on a Luby-Rackoff Feistel construction. * * Specifically, this is a generic balanced Feistel block cipher using TEA * (another block cipher) as the pseudo-random function, F. At best it's as * strong as F (TEA), notwithstanding the seeding. F could be AES, SHA-1, or * perhaps Bernstein's Salsa20 core; I am naively trying to keep things * simple. * * The generator can create a permutation of any set of numbers, as long as * the size of the set is an even power of 2. This limitation arises either * out of an inherent property of balanced Feistel constructions, or by my * own ignorance. I'll tackle an unbalanced construction after I wrap my * head around Schneier and Kelsey's paper. * * CAVEAT EMPTOR. IANAC. */ #define DNS_K_PERMUTOR_ROUNDS 8 struct dns_k_permutor { unsigned stepi, length, limit; unsigned shift, mask, rounds; struct dns_k_tea tea; }; /* struct dns_k_permutor */ static inline unsigned dns_k_permutor_powof(unsigned n) { unsigned m, i = 0; for (m = 1; m < n; m <<= 1, i++) ;; return i; } /* dns_k_permutor_powof() */ static void dns_k_permutor_init(struct dns_k_permutor *p, unsigned low, unsigned high) { uint32_t key[DNS_K_TEA_KEY_SIZE / sizeof (uint32_t)]; unsigned width, i; p->stepi = 0; p->length = (high - low) + 1; p->limit = high; width = dns_k_permutor_powof(p->length); width += width % 2; p->shift = width / 2; p->mask = (1U << p->shift) - 1; p->rounds = DNS_K_PERMUTOR_ROUNDS; for (i = 0; i < lengthof(key); i++) key[i] = dns_random(); dns_k_tea_init(&p->tea, key, 0); return /* void */; } /* dns_k_permutor_init() */ static unsigned dns_k_permutor_F(struct dns_k_permutor *p, unsigned k, unsigned x) { uint32_t in[DNS_K_TEA_BLOCK_SIZE / sizeof (uint32_t)], out[DNS_K_TEA_BLOCK_SIZE / sizeof (uint32_t)]; memset(in, '\0', sizeof in); in[0] = k; in[1] = x; dns_k_tea_encrypt(&p->tea, in, out); return p->mask & out[0]; } /* dns_k_permutor_F() */ static unsigned dns_k_permutor_E(struct dns_k_permutor *p, unsigned n) { unsigned l[2], r[2]; unsigned i; i = 0; l[i] = p->mask & (n >> p->shift); r[i] = p->mask & (n >> 0); do { l[(i + 1) % 2] = r[i % 2]; r[(i + 1) % 2] = l[i % 2] ^ dns_k_permutor_F(p, i, r[i % 2]); i++; } while (i < p->rounds - 1); return ((l[i % 2] & p->mask) << p->shift) | ((r[i % 2] & p->mask) << 0); } /* dns_k_permutor_E() */ DNS_NOTUSED static unsigned dns_k_permutor_D(struct dns_k_permutor *p, unsigned n) { unsigned l[2], r[2]; unsigned i; i = p->rounds - 1; l[i % 2] = p->mask & (n >> p->shift); r[i % 2] = p->mask & (n >> 0); do { i--; r[i % 2] = l[(i + 1) % 2]; l[i % 2] = r[(i + 1) % 2] ^ dns_k_permutor_F(p, i, l[(i + 1) % 2]); } while (i > 0); return ((l[i % 2] & p->mask) << p->shift) | ((r[i % 2] & p->mask) << 0); } /* dns_k_permutor_D() */ static unsigned dns_k_permutor_step(struct dns_k_permutor *p) { unsigned n; do { n = dns_k_permutor_E(p, p->stepi++); } while (n >= p->length); return n + (p->limit + 1 - p->length); } /* dns_k_permutor_step() */ /* * Simple permutation box. Useful for shuffling rrsets from an iterator. * Uses AES s-box to provide good diffusion. * * Seems to pass muster under runs test. * * $ for i in 0 1 2 3 4 5 6 7 8 9; do ./dns shuffle-16 > /tmp/out; done * $ R -q -f /dev/stdin 2>/dev/null <<-EOF | awk '/p-value/{ print $8 }' * library(lawstat) * runs.test(scan(file="/tmp/out")) * EOF */ static unsigned short dns_k_shuffle16(unsigned short n, unsigned s) { static const unsigned char sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; unsigned char a, b; unsigned i; a = 0xff & (n >> 0); b = 0xff & (n >> 8); for (i = 0; i < 4; i++) { a ^= 0xff & s; a = sbox[a] ^ b; b = sbox[b] ^ a; s >>= 8; } return ((0xff00 & (a << 8)) | (0x00ff & (b << 0))); } /* dns_k_shuffle16() */ /* * S T A T E M A C H I N E R O U T I N E S * * Application code should define DNS_SM_RESTORE and DNS_SM_SAVE, and the * local variable pc. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define DNS_SM_ENTER \ do { \ static const int pc0 = __LINE__; \ DNS_SM_RESTORE; \ switch (pc0 + pc) { \ case __LINE__: (void)0 #define DNS_SM_SAVE_AND_DO(do_statement) \ do { \ pc = __LINE__ - pc0; \ DNS_SM_SAVE; \ do_statement; \ case __LINE__: (void)0; \ } while (0) #define DNS_SM_YIELD(rv) \ DNS_SM_SAVE_AND_DO(return (rv)) #define DNS_SM_EXIT \ do { goto leave; } while (0) #define DNS_SM_LEAVE \ leave: (void)0; \ DNS_SM_SAVE_AND_DO(break); \ } \ } while (0) /* * U T I L I T Y R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define DNS_MAXINTERVAL 300 struct dns_clock { time_t sample, elapsed; }; /* struct dns_clock */ static void dns_begin(struct dns_clock *clk) { clk->sample = time(0); clk->elapsed = 0; } /* dns_begin() */ static time_t dns_elapsed(struct dns_clock *clk) { time_t curtime; if ((time_t)-1 == time(&curtime)) return clk->elapsed; if (curtime > clk->sample) clk->elapsed += (time_t)DNS_PP_MIN(difftime(curtime, clk->sample), DNS_MAXINTERVAL); clk->sample = curtime; return clk->elapsed; } /* dns_elapsed() */ DNS_NOTUSED static size_t dns_strnlen(const char *src, size_t m) { size_t n = 0; while (*src++ && n < m) ++n; return n; } /* dns_strnlen() */ DNS_NOTUSED static size_t dns_strnlcpy(char *dst, size_t lim, const char *src, size_t max) { size_t len = dns_strnlen(src, max), n; if (lim > 0) { n = DNS_PP_MIN(lim - 1, len); memcpy(dst, src, n); dst[n] = '\0'; } return len; } /* dns_strnlcpy() */ #define DNS_HAVE_SOCKADDR_UN (defined AF_UNIX && !defined _WIN32) static size_t dns_af_len(int af) { static const size_t table[AF_MAX] = { [AF_INET6] = sizeof (struct sockaddr_in6), [AF_INET] = sizeof (struct sockaddr_in), #if DNS_HAVE_SOCKADDR_UN [AF_UNIX] = sizeof (struct sockaddr_un), #endif }; return table[af]; } /* dns_af_len() */ #define dns_sa_family(sa) (((struct sockaddr *)(sa))->sa_family) #define dns_sa_len(sa) dns_af_len(dns_sa_family(sa)) #define DNS_SA_NOPORT &dns_sa_noport static unsigned short dns_sa_noport; static unsigned short *dns_sa_port(int af, void *sa) { switch (af) { case AF_INET6: return &((struct sockaddr_in6 *)sa)->sin6_port; case AF_INET: return &((struct sockaddr_in *)sa)->sin_port; default: return DNS_SA_NOPORT; } } /* dns_sa_port() */ static void *dns_sa_addr(int af, const void *sa, socklen_t *size) { switch (af) { case AF_INET6: { struct in6_addr *in6 = &((struct sockaddr_in6 *)sa)->sin6_addr; if (size) *size = sizeof *in6; return in6; } case AF_INET: { struct in_addr *in = &((struct sockaddr_in *)sa)->sin_addr; if (size) *size = sizeof *in; return in; } default: if (size) *size = 0; return 0; } } /* dns_sa_addr() */ #if DNS_HAVE_SOCKADDR_UN #define DNS_SUNPATHMAX (sizeof ((struct sockaddr_un *)0)->sun_path) #endif DNS_NOTUSED static void *dns_sa_path(void *sa, socklen_t *size) { switch (dns_sa_family(sa)) { #if DNS_HAVE_SOCKADDR_UN case AF_UNIX: { char *path = ((struct sockaddr_un *)sa)->sun_path; if (size) *size = dns_strnlen(path, DNS_SUNPATHMAX); return path; } #endif default: if (size) *size = 0; return NULL; } } /* dns_sa_path() */ static int dns_sa_cmp(void *a, void *b) { int cmp, af; if ((cmp = dns_sa_family(a) - dns_sa_family(b))) return cmp; switch ((af = dns_sa_family(a))) { case AF_INET: { struct in_addr *a4, *b4; if ((cmp = htons(*dns_sa_port(af, a)) - htons(*dns_sa_port(af, b)))) return cmp; a4 = dns_sa_addr(af, a, NULL); b4 = dns_sa_addr(af, b, NULL); if (ntohl(a4->s_addr) < ntohl(b4->s_addr)) return -1; if (ntohl(a4->s_addr) > ntohl(b4->s_addr)) return 1; return 0; } case AF_INET6: { struct in6_addr *a6, *b6; size_t i; if ((cmp = htons(*dns_sa_port(af, a)) - htons(*dns_sa_port(af, b)))) return cmp; a6 = dns_sa_addr(af, a, NULL); b6 = dns_sa_addr(af, b, NULL); /* XXX: do we need to use in6_clearscope()? */ for (i = 0; i < sizeof a6->s6_addr; i++) { if ((cmp = a6->s6_addr[i] - b6->s6_addr[i])) return cmp; } return 0; } #if DNS_HAVE_SOCKADDR_UN case AF_UNIX: { char a_path[DNS_SUNPATHMAX + 1], b_path[sizeof a_path]; dns_strnlcpy(a_path, sizeof a_path, dns_sa_path(a, NULL), DNS_SUNPATHMAX); dns_strnlcpy(b_path, sizeof b_path, dns_sa_path(b, NULL), DNS_SUNPATHMAX); return strcmp(a_path, b_path); } #endif default: return -1; } } /* dns_sa_cmp() */ #if _WIN32 static int dns_inet_pton(int af, const void *src, void *dst) { union { struct sockaddr_in sin; struct sockaddr_in6 sin6; } u; u.sin.sin_family = af; if (0 != WSAStringToAddressA((void *)src, af, (void *)0, (struct sockaddr *)&u, &(int){ sizeof u })) return -1; switch (af) { case AF_INET6: *(struct in6_addr *)dst = u.sin6.sin6_addr; return 1; case AF_INET: *(struct in_addr *)dst = u.sin.sin_addr; return 1; default: return 0; } } /* dns_inet_pton() */ static const char *dns_inet_ntop(int af, const void *src, void *dst, unsigned long lim) { union { struct sockaddr_in sin; struct sockaddr_in6 sin6; } u; /* NOTE: WSAAddressToString will print .sin_port unless zeroed. */ memset(&u, 0, sizeof u); u.sin.sin_family = af; switch (af) { case AF_INET6: u.sin6.sin6_addr = *(struct in6_addr *)src; break; case AF_INET: u.sin.sin_addr = *(struct in_addr *)src; break; default: return 0; } if (0 != WSAAddressToStringA((struct sockaddr *)&u, dns_sa_len(&u), (void *)0, dst, &lim)) return 0; return dst; } /* dns_inet_ntop() */ #else #define dns_inet_pton(...) inet_pton(__VA_ARGS__) #define dns_inet_ntop(...) inet_ntop(__VA_ARGS__) #endif static dns_error_t dns_pton(int af, const void *src, void *dst) { switch (dns_inet_pton(af, src, dst)) { case 1: return 0; case -1: return dns_soerr(); default: return DNS_EADDRESS; } } /* dns_pton() */ static dns_error_t dns_ntop(int af, const void *src, void *dst, unsigned long lim) { return (dns_inet_ntop(af, src, dst, lim))? 0 : dns_soerr(); } /* dns_ntop() */ size_t dns_strlcpy(char *dst, const char *src, size_t lim) { char *d = dst; char *e = &dst[lim]; const char *s = src; if (d < e) { do { if ('\0' == (*d++ = *s++)) return s - src - 1; } while (d < e); d[-1] = '\0'; } while (*s++ != '\0') ;; return s - src - 1; } /* dns_strlcpy() */ size_t dns_strlcat(char *dst, const char *src, size_t lim) { char *d = memchr(dst, '\0', lim); char *e = &dst[lim]; const char *s = src; const char *p; if (d && d < e) { do { if ('\0' == (*d++ = *s++)) return d - dst - 1; } while (d < e); d[-1] = '\0'; } p = s; while (*s++ != '\0') ;; return lim + (s - p - 1); } /* dns_strlcat() */ #if _WIN32 static char *dns_strsep(char **sp, const char *delim) { char *p; if (!(p = *sp)) return 0; *sp += strcspn(p, delim); if (**sp != '\0') { **sp = '\0'; ++*sp; } else *sp = NULL; return p; } /* dns_strsep() */ #else #define dns_strsep(...) strsep(__VA_ARGS__) #endif #if _WIN32 #define strcasecmp(...) _stricmp(__VA_ARGS__) #define strncasecmp(...) _strnicmp(__VA_ARGS__) #endif static inline _Bool dns_isalpha(unsigned char c) { return isalpha(c); } /* dns_isalpha() */ static inline _Bool dns_isdigit(unsigned char c) { return isdigit(c); } /* dns_isdigit() */ static inline _Bool dns_isalnum(unsigned char c) { return isalnum(c); } /* dns_isalnum() */ static inline _Bool dns_isspace(unsigned char c) { return isspace(c); } /* dns_isspace() */ static int dns_poll(int fd, short events, int timeout) { fd_set rset, wset; if (!events) return 0; assert(fd >= 0 && (unsigned)fd < FD_SETSIZE); FD_ZERO(&rset); FD_ZERO(&wset); if (events & DNS_POLLIN) FD_SET(fd, &rset); if (events & DNS_POLLOUT) FD_SET(fd, &wset); select(fd + 1, &rset, &wset, 0, (timeout >= 0)? &(struct timeval){ timeout, 0 } : NULL); return 0; } /* dns_poll() */ #if !_WIN32 DNS_NOTUSED static int dns_sigmask(int how, const sigset_t *set, sigset_t *oset) { #if DNS_THREAD_SAFE return pthread_sigmask(how, set, oset); #else return (0 == sigprocmask(how, set, oset))? 0 : errno; #endif } /* dns_sigmask() */ #endif static long dns_send(int fd, const void *src, size_t lim, int flags) { #if _WIN32 || !defined SIGPIPE || defined SO_NOSIGPIPE return send(fd, src, lim, flags); #elif defined MSG_NOSIGNAL return send(fd, src, lim, flags|MSG_NOSIGNAL); #elif _POSIX_REALTIME_SIGNALS > 0 /* require sigtimedwait */ /* * SIGPIPE handling similar to the approach described in * http://krokisplace.blogspot.com/2010/02/suppressing-sigpipe-in-library.html */ sigset_t pending, blocked, piped; long count; int saved, error; sigemptyset(&pending); sigpending(&pending); if (!sigismember(&pending, SIGPIPE)) { sigemptyset(&piped); sigaddset(&piped, SIGPIPE); sigemptyset(&blocked); if ((error = dns_sigmask(SIG_BLOCK, &piped, &blocked))) goto error; } count = send(fd, src, lim, flags); if (!sigismember(&pending, SIGPIPE)) { saved = errno; if (count == -1 && errno == EPIPE) { while (-1 == sigtimedwait(&piped, NULL, &(struct timespec){ 0, 0 }) && errno == EINTR) ;; } if ((error = dns_sigmask(SIG_SETMASK, &blocked, NULL))) goto error; errno = saved; } return count; error: errno = error; return -1; #else #error "unable to suppress SIGPIPE" return send(fd, src, lim, flags); #endif } /* dns_send() */ #define DNS_FOPEN_STDFLAGS "rwabt+" static dns_error_t dns_fopen_addflag(char *dst, const char *src, size_t lim, int fc) { char *p = dst, *pe = dst + lim; /* copy standard flags */ while (*src && strchr(DNS_FOPEN_STDFLAGS, *src)) { if (!(p < pe)) return ENOMEM; *p++ = *src++; } /* append flag to standard flags */ if (!(p < pe)) return ENOMEM; *p++ = fc; /* copy remaining mode string, including '\0' */ do { if (!(p < pe)) return ENOMEM; } while ((*p++ = *src++)); return 0; } /* dns_fopen_addflag() */ static FILE *dns_fopen(const char *path, const char *mode, dns_error_t *_error) { FILE *fp; char mode_cloexec[32]; int error; assert(path && mode && *mode); if (!*path) { error = EINVAL; goto error; } #if _WIN32 || _WIN64 if ((error = dns_fopen_addflag(mode_cloexec, mode, sizeof mode_cloexec, 'N'))) goto error; if (!(fp = fopen(path, mode_cloexec))) goto syerr; #else if ((error = dns_fopen_addflag(mode_cloexec, mode, sizeof mode_cloexec, 'e'))) goto error; if (!(fp = fopen(path, mode_cloexec))) { if (errno != EINVAL) goto syerr; if (!(fp = fopen(path, mode))) goto syerr; } #endif return fp; syerr: error = dns_syerr(); error: *_error = error; return NULL; } /* dns_fopen() */ /* * F I X E D - S I Z E D B U F F E R R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define DNS_B_INIT(src, n) { \ (unsigned char *)(src), \ (unsigned char *)(src), \ (unsigned char *)(src) + (n), \ } #define DNS_B_FROM(src, n) DNS_B_INIT((src), (n)) #define DNS_B_INTO(src, n) DNS_B_INIT((src), (n)) struct dns_buf { const unsigned char *base; unsigned char *p; const unsigned char *pe; dns_error_t error; size_t overflow; }; /* struct dns_buf */ static inline size_t dns_b_tell(struct dns_buf *b) { return b->p - b->base; } static inline dns_error_t dns_b_setoverflow(struct dns_buf *b, size_t n, dns_error_t error) { b->overflow += n; return b->error = error; } DNS_NOTUSED static struct dns_buf * dns_b_into(struct dns_buf *b, void *src, size_t n) { *b = (struct dns_buf)DNS_B_INTO(src, n); return b; } static dns_error_t dns_b_putc(struct dns_buf *b, unsigned char uc) { if (!(b->p < b->pe)) return dns_b_setoverflow(b, 1, DNS_ENOBUFS); *b->p++ = uc; return 0; } static dns_error_t dns_b_pputc(struct dns_buf *b, unsigned char uc, size_t p) { size_t pe = b->pe - b->base; if (pe <= p) return dns_b_setoverflow(b, p - pe + 1, DNS_ENOBUFS); *((unsigned char *)b->base + p) = uc; return 0; } static inline dns_error_t dns_b_put16(struct dns_buf *b, uint16_t u) { return dns_b_putc(b, u >> 8), dns_b_putc(b, u >> 0); } static inline dns_error_t dns_b_pput16(struct dns_buf *b, uint16_t u, size_t p) { if (dns_b_pputc(b, u >> 8, p) || dns_b_pputc(b, u >> 0, p + 1)) return b->error; return 0; } DNS_NOTUSED static inline dns_error_t dns_b_put32(struct dns_buf *b, uint32_t u) { return dns_b_putc(b, u >> 24), dns_b_putc(b, u >> 16), dns_b_putc(b, u >> 8), dns_b_putc(b, u >> 0); } static dns_error_t dns_b_put(struct dns_buf *b, const void *src, size_t len) { size_t n = DNS_PP_MIN((size_t)(b->pe - b->p), len); memcpy(b->p, src, n); b->p += n; if (n < len) return dns_b_setoverflow(b, len - n, DNS_ENOBUFS); return 0; } static dns_error_t dns_b_puts(struct dns_buf *b, const void *src) { return dns_b_put(b, src, strlen(src)); } DNS_NOTUSED static inline dns_error_t dns_b_fmtju(struct dns_buf *b, const uintmax_t u, const unsigned width) { size_t digits, padding, overflow; uintmax_t r; unsigned char *tp, *te, tc; digits = 0; r = u; do { digits++; r /= 10; } while (r); padding = width - DNS_PP_MIN(digits, width); overflow = (digits + padding) - DNS_PP_MIN((size_t)(b->pe - b->p), (digits + padding)); while (padding--) { dns_b_putc(b, '0'); } digits = 0; tp = b->p; r = u; do { if (overflow < ++digits) dns_b_putc(b, '0' + (r % 10)); r /= 10; } while (r); te = b->p; while (tp < te) { tc = *--te; *te = *tp; *tp++ = tc; } return b->error; } static void dns_b_popc(struct dns_buf *b) { if (b->overflow && !--b->overflow) b->error = 0; if (b->p > b->base) b->p--; } static inline const char * dns_b_tolstring(struct dns_buf *b, size_t *n) { if (b->p < b->pe) { *b->p = '\0'; *n = b->p - b->base; return (const char *)b->base; } else if (b->p > b->base) { if (b->p[-1] != '\0') { dns_b_setoverflow(b, 1, DNS_ENOBUFS); b->p[-1] = '\0'; } *n = &b->p[-1] - b->base; return (const char *)b->base; } else { *n = 0; return ""; } } static inline const char * dns_b_tostring(struct dns_buf *b) { size_t n; return dns_b_tolstring(b, &n); } static inline size_t dns_b_strlen(struct dns_buf *b) { size_t n; dns_b_tolstring(b, &n); return n; } static inline size_t dns_b_strllen(struct dns_buf *b) { size_t n = dns_b_strlen(b); return n + b->overflow; } DNS_NOTUSED static const struct dns_buf * dns_b_from(const struct dns_buf *b, const void *src, size_t n) { *(struct dns_buf *)b = (struct dns_buf)DNS_B_FROM(src, n); return b; } static inline int dns_b_getc(const struct dns_buf *_b, const int eof) { struct dns_buf *b = (struct dns_buf *)_b; if (!(b->p < b->pe)) return dns_b_setoverflow(b, 1, DNS_EILLEGAL), eof; return *b->p++; } static inline intmax_t dns_b_get16(const struct dns_buf *b, const intmax_t eof) { intmax_t n; n = (dns_b_getc(b, 0) << 8); n |= (dns_b_getc(b, 0) << 0); return (!b->overflow)? n : eof; } DNS_NOTUSED static inline intmax_t dns_b_get32(const struct dns_buf *b, const intmax_t eof) { intmax_t n; n = (dns_b_get16(b, 0) << 16); n |= (dns_b_get16(b, 0) << 0); return (!b->overflow)? n : eof; } static inline dns_error_t dns_b_move(struct dns_buf *dst, const struct dns_buf *_src, size_t n) { struct dns_buf *src = (struct dns_buf *)_src; size_t src_n = DNS_PP_MIN((size_t)(src->pe - src->p), n); size_t src_r = n - src_n; dns_b_put(dst, src->p, src_n); src->p += src_n; if (src_r) return dns_b_setoverflow(src, src_r, DNS_EILLEGAL); return dst->error; } /* * P A C K E T R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ unsigned dns_p_count(struct dns_packet *P, enum dns_section section) { unsigned count; switch (section) { case DNS_S_QD: return ntohs(dns_header(P)->qdcount); case DNS_S_AN: return ntohs(dns_header(P)->ancount); case DNS_S_NS: return ntohs(dns_header(P)->nscount); case DNS_S_AR: return ntohs(dns_header(P)->arcount); default: count = 0; if (section & DNS_S_QD) count += ntohs(dns_header(P)->qdcount); if (section & DNS_S_AN) count += ntohs(dns_header(P)->ancount); if (section & DNS_S_NS) count += ntohs(dns_header(P)->nscount); if (section & DNS_S_AR) count += ntohs(dns_header(P)->arcount); return count; } } /* dns_p_count() */ struct dns_packet *dns_p_init(struct dns_packet *P, size_t size) { if (!P) return 0; assert(size >= offsetof(struct dns_packet, data) + 12); memset(P, 0, sizeof *P); P->size = size - offsetof(struct dns_packet, data); P->end = 12; memset(P->data, '\0', 12); return P; } /* dns_p_init() */ static struct dns_packet *dns_p_reset(struct dns_packet *P) { return dns_p_init(P, offsetof(struct dns_packet, data) + P->size); } /* dns_p_reset() */ static unsigned short dns_p_qend(struct dns_packet *P) { unsigned short qend = 12; unsigned i, count = dns_p_count(P, DNS_S_QD); for (i = 0; i < count && qend < P->end; i++) { if (P->end == (qend = dns_d_skip(qend, P))) goto invalid; if (P->end - qend < 4) goto invalid; qend += 4; } return DNS_PP_MIN(qend, P->end); invalid: return P->end; } /* dns_p_qend() */ struct dns_packet *dns_p_make(size_t len, int *error) { struct dns_packet *P; size_t size = dns_p_calcsize(len); if (!(P = dns_p_init(malloc(size), size))) *error = dns_syerr(); return P; } /* dns_p_make() */ static void dns_p_free(struct dns_packet *P) { free(P); } /* dns_p_free() */ /* convience routine to free any existing packet before storing new packet */ static struct dns_packet *dns_p_setptr(struct dns_packet **dst, struct dns_packet *src) { dns_p_free(*dst); *dst = src; return src; } /* dns_p_setptr() */ static struct dns_packet *dns_p_movptr(struct dns_packet **dst, struct dns_packet **src) { dns_p_setptr(dst, *src); *src = NULL; return *dst; } /* dns_p_movptr() */ int dns_p_grow(struct dns_packet **P) { struct dns_packet *tmp; size_t size; int error; if (!*P) { if (!(*P = dns_p_make(DNS_P_QBUFSIZ, &error))) return error; return 0; } size = dns_p_sizeof(*P); size |= size >> 1; size |= size >> 2; size |= size >> 4; size |= size >> 8; size++; if (size > 65536) return DNS_ENOBUFS; if (!(tmp = realloc(*P, dns_p_calcsize(size)))) return dns_syerr(); tmp->size = size; *P = tmp; return 0; } /* dns_p_grow() */ struct dns_packet *dns_p_copy(struct dns_packet *P, const struct dns_packet *P0) { if (!P) return 0; P->end = DNS_PP_MIN(P->size, P0->end); memcpy(P->data, P0->data, P->end); return P; } /* dns_p_copy() */ struct dns_packet *dns_p_merge(struct dns_packet *A, enum dns_section Amask, struct dns_packet *B, enum dns_section Bmask, int *error_) { size_t bufsiz = DNS_PP_MIN(65535, ((A)? A->end : 0) + ((B)? B->end : 0)); struct dns_packet *M; enum dns_section section; struct dns_rr rr, mr; int error, copy; if (!A && B) { A = B; Amask = Bmask; B = 0; } merge: if (!(M = dns_p_make(bufsiz, &error))) goto error; for (section = DNS_S_QD; (DNS_S_ALL & section); section <<= 1) { if (A && (section & Amask)) { dns_rr_foreach(&rr, A, .section = section) { if ((error = dns_rr_copy(M, &rr, A))) goto error; } } if (B && (section & Bmask)) { dns_rr_foreach(&rr, B, .section = section) { copy = 1; dns_rr_foreach(&mr, M, .type = rr.type, .section = DNS_S_ALL) { if (!(copy = dns_rr_cmp(&rr, B, &mr, M))) break; } if (copy && (error = dns_rr_copy(M, &rr, B))) goto error; } } } return M; error: dns_p_setptr(&M, NULL); if (error == DNS_ENOBUFS && bufsiz < 65535) { bufsiz = DNS_PP_MIN(65535, bufsiz * 2); goto merge; } *error_ = error; return 0; } /* dns_p_merge() */ static unsigned short dns_l_skip(unsigned short, const unsigned char *, size_t); void dns_p_dictadd(struct dns_packet *P, unsigned short dn) { unsigned short lp, lptr, i; lp = dn; while (lp < P->end) { if (0xc0 == (0xc0 & P->data[lp]) && P->end - lp >= 2 && lp != dn) { lptr = ((0x3f & P->data[lp + 0]) << 8) | ((0xff & P->data[lp + 1]) << 0); for (i = 0; i < lengthof(P->dict) && P->dict[i]; i++) { if (P->dict[i] == lptr) { P->dict[i] = dn; return; } } } lp = dns_l_skip(lp, P->data, P->end); } for (i = 0; i < lengthof(P->dict); i++) { if (!P->dict[i]) { P->dict[i] = dn; break; } } } /* dns_p_dictadd() */ int dns_p_push(struct dns_packet *P, enum dns_section section, const void *dn, size_t dnlen, enum dns_type type, enum dns_class class, unsigned ttl, const void *any) { size_t end = P->end; int error; if ((error = dns_d_push(P, dn, dnlen))) goto error; if (P->size - P->end < 4) goto nobufs; P->data[P->end++] = 0xff & (type >> 8); P->data[P->end++] = 0xff & (type >> 0); P->data[P->end++] = 0xff & (class >> 8); P->data[P->end++] = 0xff & (class >> 0); if (section == DNS_S_QD) goto update; if (P->size - P->end < 6) goto nobufs; if (type != DNS_T_OPT) ttl = DNS_PP_MIN(ttl, 0x7fffffffU); P->data[P->end++] = ttl >> 24; P->data[P->end++] = ttl >> 16; P->data[P->end++] = ttl >> 8; P->data[P->end++] = ttl >> 0; if ((error = dns_any_push(P, (union dns_any *)any, type))) goto error; update: switch (section) { case DNS_S_QD: if (dns_p_count(P, DNS_S_AN|DNS_S_NS|DNS_S_AR)) goto order; if (!P->memo.qd.base && (error = dns_p_study(P))) goto error; dns_header(P)->qdcount = htons(ntohs(dns_header(P)->qdcount) + 1); P->memo.qd.end = P->end; P->memo.an.base = P->end; P->memo.an.end = P->end; P->memo.ns.base = P->end; P->memo.ns.end = P->end; P->memo.ar.base = P->end; P->memo.ar.end = P->end; break; case DNS_S_AN: if (dns_p_count(P, DNS_S_NS|DNS_S_AR)) goto order; if (!P->memo.an.base && (error = dns_p_study(P))) goto error; dns_header(P)->ancount = htons(ntohs(dns_header(P)->ancount) + 1); P->memo.an.end = P->end; P->memo.ns.base = P->end; P->memo.ns.end = P->end; P->memo.ar.base = P->end; P->memo.ar.end = P->end; break; case DNS_S_NS: if (dns_p_count(P, DNS_S_AR)) goto order; if (!P->memo.ns.base && (error = dns_p_study(P))) goto error; dns_header(P)->nscount = htons(ntohs(dns_header(P)->nscount) + 1); P->memo.ns.end = P->end; P->memo.ar.base = P->end; P->memo.ar.end = P->end; break; case DNS_S_AR: if (!P->memo.ar.base && (error = dns_p_study(P))) goto error; dns_header(P)->arcount = htons(ntohs(dns_header(P)->arcount) + 1); P->memo.ar.end = P->end; if (type == DNS_T_OPT && !P->memo.opt.p) { P->memo.opt.p = end; P->memo.opt.maxudp = class; P->memo.opt.ttl = ttl; } break; default: error = DNS_ESECTION; goto error; } /* switch() */ return 0; nobufs: error = DNS_ENOBUFS; goto error; order: error = DNS_EORDER; goto error; error: P->end = end; return error; } /* dns_p_push() */ static void dns_p_dump3(struct dns_packet *P, struct dns_rr_i *I, FILE *fp) { enum dns_section section; struct dns_rr rr; int error; union dns_any any; char pretty[sizeof any * 2]; size_t len; fputs(";; [HEADER]\n", fp); fprintf(fp, ";; qid : %d\n", ntohs(dns_header(P)->qid)); fprintf(fp, ";; qr : %s(%d)\n", (dns_header(P)->qr)? "RESPONSE" : "QUERY", dns_header(P)->qr); fprintf(fp, ";; opcode : %s(%d)\n", dns_stropcode(dns_header(P)->opcode), dns_header(P)->opcode); fprintf(fp, ";; aa : %s(%d)\n", (dns_header(P)->aa)? "AUTHORITATIVE" : "NON-AUTHORITATIVE", dns_header(P)->aa); fprintf(fp, ";; tc : %s(%d)\n", (dns_header(P)->tc)? "TRUNCATED" : "NOT-TRUNCATED", dns_header(P)->tc); fprintf(fp, ";; rd : %s(%d)\n", (dns_header(P)->rd)? "RECURSION-DESIRED" : "RECURSION-NOT-DESIRED", dns_header(P)->rd); fprintf(fp, ";; ra : %s(%d)\n", (dns_header(P)->ra)? "RECURSION-ALLOWED" : "RECURSION-NOT-ALLOWED", dns_header(P)->ra); fprintf(fp, ";; rcode : %s(%d)\n", dns_strrcode(dns_p_rcode(P)), dns_p_rcode(P)); section = 0; while (dns_rr_grep(&rr, 1, I, P, &error)) { if (section != rr.section) fprintf(fp, "\n;; [%s:%d]\n", dns_strsection(rr.section), dns_p_count(P, rr.section)); if ((len = dns_rr_print(pretty, sizeof pretty, &rr, P, &error))) fprintf(fp, "%s\n", pretty); section = rr.section; } } /* dns_p_dump3() */ void dns_p_dump(struct dns_packet *P, FILE *fp) { dns_p_dump3(P, dns_rr_i_new(P, .section = 0), fp); } /* dns_p_dump() */ static void dns_s_unstudy(struct dns_s_memo *m) { m->base = 0; m->end = 0; } static void dns_m_unstudy(struct dns_p_memo *m) { dns_s_unstudy(&m->qd); dns_s_unstudy(&m->an); dns_s_unstudy(&m->ns); dns_s_unstudy(&m->ar); m->opt.p = 0; m->opt.maxudp = 0; m->opt.ttl = 0; } /* dns_m_unstudy() */ static int dns_s_study(struct dns_s_memo *m, enum dns_section section, unsigned short base, struct dns_packet *P) { unsigned short count, rp; count = dns_p_count(P, section); for (rp = base; count && rp < P->end; count--) rp = dns_rr_skip(rp, P); m->base = base; m->end = rp; return 0; } /* dns_s_study() */ static int dns_m_study(struct dns_p_memo *m, struct dns_packet *P) { struct dns_rr rr; int error; if ((error = dns_s_study(&m->qd, DNS_S_QD, 12, P))) goto error; if ((error = dns_s_study(&m->an, DNS_S_AN, m->qd.end, P))) goto error; if ((error = dns_s_study(&m->ns, DNS_S_NS, m->an.end, P))) goto error; if ((error = dns_s_study(&m->ar, DNS_S_AR, m->ns.end, P))) goto error; m->opt.p = 0; m->opt.maxudp = 0; m->opt.ttl = 0; dns_rr_foreach(&rr, P, .type = DNS_T_OPT, .section = DNS_S_AR) { m->opt.p = rr.dn.p; m->opt.maxudp = rr.class; m->opt.ttl = rr.ttl; break; } return 0; error: dns_m_unstudy(m); return error; } /* dns_m_study() */ int dns_p_study(struct dns_packet *P) { return dns_m_study(&P->memo, P); } /* dns_p_study() */ enum dns_rcode dns_p_rcode(struct dns_packet *P) { return 0xfff & ((P->memo.opt.ttl >> 20) | dns_header(P)->rcode); } /* dns_p_rcode() */ /* * Q U E R Y P A C K E T R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define DNS_Q_RD 0x1 /* recursion desired */ #define DNS_Q_EDNS0 0x2 /* include OPT RR */ static dns_error_t dns_q_make2(struct dns_packet **_Q, const char *qname, size_t qlen, enum dns_type qtype, enum dns_class qclass, int qflags) { struct dns_packet *Q = NULL; int error; if (dns_p_movptr(&Q, _Q)) { dns_p_reset(Q); } else if (!(Q = dns_p_make(DNS_P_QBUFSIZ, &error))) { goto error; } if ((error = dns_p_push(Q, DNS_S_QD, qname, qlen, qtype, qclass, 0, 0))) goto error; dns_header(Q)->rd = !!(qflags & DNS_Q_RD); if (qflags & DNS_Q_EDNS0) { struct dns_opt opt = DNS_OPT_INIT(&opt); opt.version = 0; /* RFC 6891 version */ opt.maxudp = 4096; if ((error = dns_p_push(Q, DNS_S_AR, ".", 1, DNS_T_OPT, dns_opt_class(&opt), dns_opt_ttl(&opt), &opt))) goto error; } *_Q = Q; return 0; error: dns_p_free(Q); return error; } static dns_error_t dns_q_make(struct dns_packet **Q, const char *qname, enum dns_type qtype, enum dns_class qclass, int qflags) { return dns_q_make2(Q, qname, strlen(qname), qtype, qclass, qflags); } static dns_error_t dns_q_remake(struct dns_packet **Q, int qflags) { char qname[DNS_D_MAXNAME + 1]; size_t qlen; struct dns_rr rr; int error; assert(Q && *Q); if ((error = dns_rr_parse(&rr, 12, *Q))) return error; if (!(qlen = dns_d_expand(qname, sizeof qname, rr.dn.p, *Q, &error))) return error; if (qlen >= sizeof qname) return DNS_EILLEGAL; return dns_q_make2(Q, qname, qlen, rr.type, rr.class, qflags); } /* * D O M A I N N A M E R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef DNS_D_MAXPTRS #define DNS_D_MAXPTRS 127 /* Arbitrary; possible, valid depth is something like packet size / 2 + fudge. */ #endif static size_t dns_l_expand(unsigned char *dst, size_t lim, unsigned short src, unsigned short *nxt, const unsigned char *data, size_t end) { unsigned short len; unsigned nptrs = 0; retry: if (src >= end) goto invalid; switch (0x03 & (data[src] >> 6)) { case 0x00: len = (0x3f & (data[src++])); if (end - src < len) goto invalid; if (lim > 0) { memcpy(dst, &data[src], DNS_PP_MIN(lim, len)); dst[DNS_PP_MIN(lim - 1, len)] = '\0'; } *nxt = src + len; return len; case 0x01: goto invalid; case 0x02: goto invalid; case 0x03: if (++nptrs > DNS_D_MAXPTRS) goto invalid; if (end - src < 2) goto invalid; src = ((0x3f & data[src + 0]) << 8) | ((0xff & data[src + 1]) << 0); goto retry; } /* switch() */ /* NOT REACHED */ invalid: *nxt = end; return 0; } /* dns_l_expand() */ static unsigned short dns_l_skip(unsigned short src, const unsigned char *data, size_t end) { unsigned short len; if (src >= end) goto invalid; switch (0x03 & (data[src] >> 6)) { case 0x00: len = (0x3f & (data[src++])); if (end - src < len) goto invalid; return (len)? src + len : end; case 0x01: goto invalid; case 0x02: goto invalid; case 0x03: return end; } /* switch() */ /* NOT REACHED */ invalid: return end; } /* dns_l_skip() */ static _Bool dns_d_isanchored(const void *_src, size_t len) { const unsigned char *src = _src; return len > 0 && src[len - 1] == '.'; } /* dns_d_isanchored() */ static size_t dns_d_ndots(const void *_src, size_t len) { const unsigned char *p = _src, *pe = p + len; size_t ndots = 0; while ((p = memchr(p, '.', pe - p))) { ndots++; p++; } return ndots; } /* dns_d_ndots() */ static size_t dns_d_trim(void *dst_, size_t lim, const void *src_, size_t len, int flags) { unsigned char *dst = dst_; const unsigned char *src = src_; size_t dp = 0, sp = 0; int lc; /* trim any leading dot(s) */ while (sp < len && src[sp] == '.') sp++; for (lc = 0; sp < len; lc = src[sp++]) { /* trim extra dot(s) */ if (src[sp] == '.' && lc == '.') continue; if (dp < lim) dst[dp] = src[sp]; dp++; } if ((flags & DNS_D_ANCHOR) && lc != '.') { if (dp < lim) dst[dp] = '.'; dp++; } if (lim > 0) dst[DNS_PP_MIN(dp, lim - 1)] = '\0'; return dp; } /* dns_d_trim() */ char *dns_d_init(void *dst, size_t lim, const void *src, size_t len, int flags) { if (flags & DNS_D_TRIM) { dns_d_trim(dst, lim, src, len, flags); } if (flags & DNS_D_ANCHOR) { dns_d_anchor(dst, lim, src, len); } else { memmove(dst, src, DNS_PP_MIN(lim, len)); if (lim > 0) ((char *)dst)[DNS_PP_MIN(len, lim - 1)] = '\0'; } return dst; } /* dns_d_init() */ size_t dns_d_anchor(void *dst, size_t lim, const void *src, size_t len) { if (len == 0) return 0; memmove(dst, src, DNS_PP_MIN(lim, len)); if (((const char *)src)[len - 1] != '.') { if (len < lim) ((char *)dst)[len] = '.'; len++; } if (lim > 0) ((char *)dst)[DNS_PP_MIN(lim - 1, len)] = '\0'; return len; } /* dns_d_anchor() */ size_t dns_d_cleave(void *dst, size_t lim, const void *src, size_t len) { const char *dot; /* XXX: Skip any leading dot. Handles cleaving root ".". */ if (len == 0 || !(dot = memchr((const char *)src + 1, '.', len - 1))) return 0; len -= dot - (const char *)src; /* XXX: Unless root, skip the label's trailing dot. */ if (len > 1) { src = ++dot; len--; } else src = dot; memmove(dst, src, DNS_PP_MIN(lim, len)); if (lim > 0) ((char *)dst)[DNS_PP_MIN(lim - 1, len)] = '\0'; return len; } /* dns_d_cleave() */ size_t dns_d_comp(void *dst_, size_t lim, const void *src_, size_t len, struct dns_packet *P, int *error) { struct { unsigned char *b; size_t p, x; } dst, src; unsigned char ch = '.'; dst.b = dst_; dst.p = 0; dst.x = 1; src.b = (unsigned char *)src_; src.p = 0; src.x = 0; while (src.x < len) { ch = src.b[src.x]; if (ch == '.') { if (dst.p < lim) dst.b[dst.p] = (0x3f & (src.x - src.p)); dst.p = dst.x++; src.p = ++src.x; } else { if (dst.x < lim) dst.b[dst.x] = ch; dst.x++; src.x++; } } /* while() */ if (src.x > src.p) { if (dst.p < lim) dst.b[dst.p] = (0x3f & (src.x - src.p)); dst.p = dst.x; } if (dst.p > 1) { if (dst.p < lim) dst.b[dst.p] = 0x00; dst.p++; } #if 1 if (dst.p < lim) { struct { unsigned char label[DNS_D_MAXLABEL + 1]; size_t len; unsigned short p, x, y; } a, b; unsigned i; a.p = 0; while ((a.len = dns_l_expand(a.label, sizeof a.label, a.p, &a.x, dst.b, lim))) { for (i = 0; i < lengthof(P->dict) && P->dict[i]; i++) { b.p = P->dict[i]; while ((b.len = dns_l_expand(b.label, sizeof b.label, b.p, &b.x, P->data, P->end))) { a.y = a.x; b.y = b.x; while (a.len && b.len && 0 == strcasecmp((char *)a.label, (char *)b.label)) { a.len = dns_l_expand(a.label, sizeof a.label, a.y, &a.y, dst.b, lim); b.len = dns_l_expand(b.label, sizeof b.label, b.y, &b.y, P->data, P->end); } if (a.len == 0 && b.len == 0 && b.p <= 0x3fff) { dst.b[a.p++] = 0xc0 | (0x3f & (b.p >> 8)); dst.b[a.p++] = (0xff & (b.p >> 0)); /* silence static analyzers */ dns_assume(a.p > 0); return a.p; } b.p = b.x; } /* while() */ } /* for() */ a.p = a.x; } /* while() */ } /* if () */ #endif if (!dst.p) *error = DNS_EILLEGAL; return dst.p; } /* dns_d_comp() */ unsigned short dns_d_skip(unsigned short src, struct dns_packet *P) { unsigned short len; while (src < P->end) { switch (0x03 & (P->data[src] >> 6)) { case 0x00: /* FOLLOWS */ len = (0x3f & P->data[src++]); if (0 == len) { /* success ==> */ return src; } else if (P->end - src > len) { src += len; break; } else goto invalid; /* NOT REACHED */ case 0x01: /* RESERVED */ goto invalid; case 0x02: /* RESERVED */ goto invalid; case 0x03: /* POINTER */ if (P->end - src < 2) goto invalid; src += 2; /* success ==> */ return src; } /* switch() */ } /* while() */ invalid: return P->end; } /* dns_d_skip() */ #include <stdio.h> size_t dns_d_expand(void *dst, size_t lim, unsigned short src, struct dns_packet *P, int *error) { size_t dstp = 0; unsigned nptrs = 0; unsigned char len; while (src < P->end) { switch ((0x03 & (P->data[src] >> 6))) { case 0x00: /* FOLLOWS */ len = (0x3f & P->data[src]); if (0 == len) { if (dstp == 0) { if (dstp < lim) ((unsigned char *)dst)[dstp] = '.'; dstp++; } /* NUL terminate */ if (lim > 0) ((unsigned char *)dst)[DNS_PP_MIN(dstp, lim - 1)] = '\0'; /* success ==> */ return dstp; } src++; if (P->end - src < len) goto toolong; if (dstp < lim) memcpy(&((unsigned char *)dst)[dstp], &P->data[src], DNS_PP_MIN(len, lim - dstp)); src += len; dstp += len; if (dstp < lim) ((unsigned char *)dst)[dstp] = '.'; dstp++; nptrs = 0; continue; case 0x01: /* RESERVED */ goto reserved; case 0x02: /* RESERVED */ goto reserved; case 0x03: /* POINTER */ if (++nptrs > DNS_D_MAXPTRS) goto toolong; if (P->end - src < 2) goto toolong; src = ((0x3f & P->data[src + 0]) << 8) | ((0xff & P->data[src + 1]) << 0); continue; } /* switch() */ } /* while() */ toolong: *error = DNS_EILLEGAL; if (lim > 0) ((unsigned char *)dst)[DNS_PP_MIN(dstp, lim - 1)] = '\0'; return 0; reserved: *error = DNS_EILLEGAL; if (lim > 0) ((unsigned char *)dst)[DNS_PP_MIN(dstp, lim - 1)] = '\0'; return 0; } /* dns_d_expand() */ int dns_d_push(struct dns_packet *P, const void *dn, size_t len) { size_t lim = P->size - P->end; unsigned dp = P->end; int error = DNS_EILLEGAL; /* silence compiler */ len = dns_d_comp(&P->data[dp], lim, dn, len, P, &error); if (len == 0) return error; if (len > lim) return DNS_ENOBUFS; P->end += len; dns_p_dictadd(P, dp); return 0; } /* dns_d_push() */ size_t dns_d_cname(void *dst, size_t lim, const void *dn, size_t len, struct dns_packet *P, int *error_) { char host[DNS_D_MAXNAME + 1]; struct dns_rr_i i; struct dns_rr rr; unsigned depth; int error; if (sizeof host <= dns_d_anchor(host, sizeof host, dn, len)) { error = ENAMETOOLONG; goto error; } for (depth = 0; depth < 7; depth++) { dns_rr_i_init(memset(&i, 0, sizeof i), P); i.section = DNS_S_ALL & ~DNS_S_QD; i.name = host; i.type = DNS_T_CNAME; if (!dns_rr_grep(&rr, 1, &i, P, &error)) break; if ((error = dns_cname_parse((struct dns_cname *)host, &rr, P))) goto error; } return dns_strlcpy(dst, host, lim); error: *error_ = error; return 0; } /* dns_d_cname() */ /* * R E S O U R C E R E C O R D R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int dns_rr_copy(struct dns_packet *P, struct dns_rr *rr, struct dns_packet *Q) { unsigned char dn[DNS_D_MAXNAME + 1]; union dns_any any; size_t len; int error; if (!(len = dns_d_expand(dn, sizeof dn, rr->dn.p, Q, &error))) return error; else if (len >= sizeof dn) return DNS_EILLEGAL; if (rr->section != DNS_S_QD && (error = dns_any_parse(dns_any_init(&any, sizeof any), rr, Q))) return error; return dns_p_push(P, rr->section, dn, len, rr->type, rr->class, rr->ttl, &any); } /* dns_rr_copy() */ int dns_rr_parse(struct dns_rr *rr, unsigned short src, struct dns_packet *P) { unsigned short p = src; if (src >= P->end) goto invalid; rr->dn.p = p; rr->dn.len = (p = dns_d_skip(p, P)) - rr->dn.p; if (P->end - p < 4) goto invalid; rr->type = ((0xff & P->data[p + 0]) << 8) | ((0xff & P->data[p + 1]) << 0); rr->class = ((0xff & P->data[p + 2]) << 8) | ((0xff & P->data[p + 3]) << 0); p += 4; if (src < dns_p_qend(P)) { rr->section = DNS_S_QUESTION; rr->ttl = 0; rr->rd.p = 0; rr->rd.len = 0; return 0; } if (P->end - p < 4) goto invalid; rr->ttl = ((0xff & P->data[p + 0]) << 24) | ((0xff & P->data[p + 1]) << 16) | ((0xff & P->data[p + 2]) << 8) | ((0xff & P->data[p + 3]) << 0); if (rr->type != DNS_T_OPT) rr->ttl = DNS_PP_MIN(rr->ttl, 0x7fffffffU); p += 4; if (P->end - p < 2) goto invalid; rr->rd.len = ((0xff & P->data[p + 0]) << 8) | ((0xff & P->data[p + 1]) << 0); rr->rd.p = p + 2; p += 2; if (P->end - p < rr->rd.len) goto invalid; return 0; invalid: return DNS_EILLEGAL; } /* dns_rr_parse() */ static unsigned short dns_rr_len(const unsigned short src, struct dns_packet *P) { unsigned short rp, rdlen; rp = dns_d_skip(src, P); if (P->end - rp < 4) return P->end - src; rp += 4; /* TYPE, CLASS */ if (rp <= dns_p_qend(P)) return rp - src; if (P->end - rp < 6) return P->end - src; rp += 6; /* TTL, RDLEN */ rdlen = ((0xff & P->data[rp - 2]) << 8) | ((0xff & P->data[rp - 1]) << 0); if (P->end - rp < rdlen) return P->end - src; rp += rdlen; return rp - src; } /* dns_rr_len() */ unsigned short dns_rr_skip(unsigned short src, struct dns_packet *P) { return src + dns_rr_len(src, P); } /* dns_rr_skip() */ static enum dns_section dns_rr_section(unsigned short src, struct dns_packet *P) { enum dns_section section; unsigned count, index; unsigned short rp; if (src >= P->memo.qd.base && src < P->memo.qd.end) return DNS_S_QD; if (src >= P->memo.an.base && src < P->memo.an.end) return DNS_S_AN; if (src >= P->memo.ns.base && src < P->memo.ns.end) return DNS_S_NS; if (src >= P->memo.ar.base && src < P->memo.ar.end) return DNS_S_AR; /* NOTE: Possibly bad memoization. Try it the hard-way. */ for (rp = 12, index = 0; rp < src && rp < P->end; index++) rp = dns_rr_skip(rp, P); section = DNS_S_QD; count = dns_p_count(P, section); while (index >= count && section <= DNS_S_AR) { section <<= 1; count += dns_p_count(P, section); } return DNS_S_ALL & section; } /* dns_rr_section() */ static enum dns_type dns_rr_type(unsigned short src, struct dns_packet *P) { struct dns_rr rr; int error; if ((error = dns_rr_parse(&rr, src, P))) return 0; return rr.type; } /* dns_rr_type() */ int dns_rr_cmp(struct dns_rr *r0, struct dns_packet *P0, struct dns_rr *r1, struct dns_packet *P1) { char host0[DNS_D_MAXNAME + 1], host1[DNS_D_MAXNAME + 1]; union dns_any any0, any1; int cmp, error; size_t len; if ((cmp = r0->type - r1->type)) return cmp; if ((cmp = r0->class - r1->class)) return cmp; /* * FIXME: Do label-by-label comparison to handle illegally long names? */ if (!(len = dns_d_expand(host0, sizeof host0, r0->dn.p, P0, &error)) || len >= sizeof host0) return -1; if (!(len = dns_d_expand(host1, sizeof host1, r1->dn.p, P1, &error)) || len >= sizeof host1) return 1; if ((cmp = strcasecmp(host0, host1))) return cmp; if (DNS_S_QD & (r0->section | r1->section)) { if (r0->section == r1->section) return 0; return (r0->section == DNS_S_QD)? -1 : 1; } if ((error = dns_any_parse(&any0, r0, P0))) return -1; if ((error = dns_any_parse(&any1, r1, P1))) return 1; return dns_any_cmp(&any0, r0->type, &any1, r1->type); } /* dns_rr_cmp() */ static _Bool dns_rr_exists(struct dns_rr *rr0, struct dns_packet *P0, struct dns_packet *P1) { struct dns_rr rr1; dns_rr_foreach(&rr1, P1, .section = rr0->section, .type = rr0->type) { if (0 == dns_rr_cmp(rr0, P0, &rr1, P1)) return 1; } return 0; } /* dns_rr_exists() */ static unsigned short dns_rr_offset(struct dns_rr *rr) { return rr->dn.p; } /* dns_rr_offset() */ static _Bool dns_rr_i_match(struct dns_rr *rr, struct dns_rr_i *i, struct dns_packet *P) { if (i->section && !(rr->section & i->section)) return 0; if (i->type && rr->type != i->type && i->type != DNS_T_ALL) return 0; if (i->class && rr->class != i->class && i->class != DNS_C_ANY) return 0; if (i->name) { char dn[DNS_D_MAXNAME + 1]; size_t len; int error; if (!(len = dns_d_expand(dn, sizeof dn, rr->dn.p, P, &error)) || len >= sizeof dn) return 0; if (0 != strcasecmp(dn, i->name)) return 0; } if (i->data && i->type && rr->section > DNS_S_QD) { union dns_any rd; int error; if ((error = dns_any_parse(&rd, rr, P))) return 0; if (0 != dns_any_cmp(&rd, rr->type, i->data, i->type)) return 0; } return 1; } /* dns_rr_i_match() */ static unsigned short dns_rr_i_start(struct dns_rr_i *i, struct dns_packet *P) { unsigned short rp; struct dns_rr r0, rr; int error; if ((i->section & DNS_S_QD) && P->memo.qd.base) rp = P->memo.qd.base; else if ((i->section & DNS_S_AN) && P->memo.an.base) rp = P->memo.an.base; else if ((i->section & DNS_S_NS) && P->memo.ns.base) rp = P->memo.ns.base; else if ((i->section & DNS_S_AR) && P->memo.ar.base) rp = P->memo.ar.base; else rp = 12; for (; rp < P->end; rp = dns_rr_skip(rp, P)) { if ((error = dns_rr_parse(&rr, rp, P))) continue; rr.section = dns_rr_section(rp, P); if (!dns_rr_i_match(&rr, i, P)) continue; r0 = rr; goto lower; } return P->end; lower: if (i->sort == &dns_rr_i_packet) return dns_rr_offset(&r0); while ((rp = dns_rr_skip(rp, P)) < P->end) { if ((error = dns_rr_parse(&rr, rp, P))) continue; rr.section = dns_rr_section(rp, P); if (!dns_rr_i_match(&rr, i, P)) continue; if (i->sort(&rr, &r0, i, P) < 0) r0 = rr; } return dns_rr_offset(&r0); } /* dns_rr_i_start() */ static unsigned short dns_rr_i_skip(unsigned short rp, struct dns_rr_i *i, struct dns_packet *P) { struct dns_rr r0, r1, rr; int error; if ((error = dns_rr_parse(&r0, rp, P))) return P->end; r0.section = dns_rr_section(rp, P); rp = (i->sort == &dns_rr_i_packet)? dns_rr_skip(rp, P) : 12; for (; rp < P->end; rp = dns_rr_skip(rp, P)) { if ((error = dns_rr_parse(&rr, rp, P))) continue; rr.section = dns_rr_section(rp, P); if (!dns_rr_i_match(&rr, i, P)) continue; if (i->sort(&rr, &r0, i, P) <= 0) continue; r1 = rr; goto lower; } return P->end; lower: if (i->sort == &dns_rr_i_packet) return dns_rr_offset(&r1); while ((rp = dns_rr_skip(rp, P)) < P->end) { if ((error = dns_rr_parse(&rr, rp, P))) continue; rr.section = dns_rr_section(rp, P); if (!dns_rr_i_match(&rr, i, P)) continue; if (i->sort(&rr, &r0, i, P) <= 0) continue; if (i->sort(&rr, &r1, i, P) >= 0) continue; r1 = rr; } return dns_rr_offset(&r1); } /* dns_rr_i_skip() */ int dns_rr_i_packet(struct dns_rr *a, struct dns_rr *b, struct dns_rr_i *i, struct dns_packet *P) { (void)i; (void)P; return (int)a->dn.p - (int)b->dn.p; } /* dns_rr_i_packet() */ int dns_rr_i_order(struct dns_rr *a, struct dns_rr *b, struct dns_rr_i *i, struct dns_packet *P) { int cmp; (void)i; if ((cmp = a->section - b->section)) return cmp; if (a->type != b->type) return (int)a->dn.p - (int)b->dn.p; return dns_rr_cmp(a, P, b, P); } /* dns_rr_i_order() */ int dns_rr_i_shuffle(struct dns_rr *a, struct dns_rr *b, struct dns_rr_i *i, struct dns_packet *P) { int cmp; (void)i; (void)P; while (!i->state.regs[0]) i->state.regs[0] = dns_random(); if ((cmp = a->section - b->section)) return cmp; return dns_k_shuffle16(a->dn.p, i->state.regs[0]) - dns_k_shuffle16(b->dn.p, i->state.regs[0]); } /* dns_rr_i_shuffle() */ struct dns_rr_i *dns_rr_i_init(struct dns_rr_i *i, struct dns_packet *P) { static const struct dns_rr_i i_initializer; (void)P; i->state = i_initializer.state; i->saved = i->state; return i; } /* dns_rr_i_init() */ unsigned dns_rr_grep(struct dns_rr *rr, unsigned lim, struct dns_rr_i *i, struct dns_packet *P, int *error_) { unsigned count = 0; int error; switch (i->state.exec) { case 0: if (!i->sort) i->sort = &dns_rr_i_packet; i->state.next = dns_rr_i_start(i, P); i->state.exec++; /* FALL THROUGH */ case 1: while (count < lim && i->state.next < P->end) { if ((error = dns_rr_parse(rr, i->state.next, P))) goto error; rr->section = dns_rr_section(i->state.next, P); rr++; count++; i->state.count++; i->state.next = dns_rr_i_skip(i->state.next, i, P); } /* while() */ break; } /* switch() */ return count; error: *error_ = error; return count; } /* dns_rr_grep() */ size_t dns_rr_print(void *_dst, size_t lim, struct dns_rr *rr, struct dns_packet *P, int *_error) { struct dns_buf dst = DNS_B_INTO(_dst, lim); union dns_any any; size_t n; int error; if (rr->section == DNS_S_QD) dns_b_putc(&dst, ';'); if (!(n = dns_d_expand(any.ns.host, sizeof any.ns.host, rr->dn.p, P, &error))) goto error; dns_b_put(&dst, any.ns.host, DNS_PP_MIN(n, sizeof any.ns.host - 1)); if (rr->section != DNS_S_QD) { dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, rr->ttl, 0); } dns_b_putc(&dst, ' '); dns_b_puts(&dst, dns_strclass(rr->class)); dns_b_putc(&dst, ' '); dns_b_puts(&dst, dns_strtype(rr->type)); if (rr->section == DNS_S_QD) goto epilog; dns_b_putc(&dst, ' '); if ((error = dns_any_parse(dns_any_init(&any, sizeof any), rr, P))) goto error; n = dns_any_print(dst.p, dst.pe - dst.p, &any, rr->type); dst.p += DNS_PP_MIN(n, (size_t)(dst.pe - dst.p)); epilog: return dns_b_strllen(&dst); error: *_error = error; return 0; } /* dns_rr_print() */ int dns_a_parse(struct dns_a *a, struct dns_rr *rr, struct dns_packet *P) { unsigned long addr; if (rr->rd.len != 4) return DNS_EILLEGAL; addr = ((0xffU & P->data[rr->rd.p + 0]) << 24) | ((0xffU & P->data[rr->rd.p + 1]) << 16) | ((0xffU & P->data[rr->rd.p + 2]) << 8) | ((0xffU & P->data[rr->rd.p + 3]) << 0); a->addr.s_addr = htonl(addr); return 0; } /* dns_a_parse() */ int dns_a_push(struct dns_packet *P, struct dns_a *a) { unsigned long addr; if (P->size - P->end < 6) return DNS_ENOBUFS; P->data[P->end++] = 0x00; P->data[P->end++] = 0x04; addr = ntohl(a->addr.s_addr); P->data[P->end++] = 0xffU & (addr >> 24); P->data[P->end++] = 0xffU & (addr >> 16); P->data[P->end++] = 0xffU & (addr >> 8); P->data[P->end++] = 0xffU & (addr >> 0); return 0; } /* dns_a_push() */ size_t dns_a_arpa(void *_dst, size_t lim, const struct dns_a *a) { struct dns_buf dst = DNS_B_INTO(_dst, lim); unsigned long octets = ntohl(a->addr.s_addr); unsigned i; for (i = 0; i < 4; i++) { dns_b_fmtju(&dst, 0xff & octets, 0); dns_b_putc(&dst, '.'); octets >>= 8; } dns_b_puts(&dst, "in-addr.arpa."); return dns_b_strllen(&dst); } /* dns_a_arpa() */ int dns_a_cmp(const struct dns_a *a, const struct dns_a *b) { if (ntohl(a->addr.s_addr) < ntohl(b->addr.s_addr)) return -1; if (ntohl(a->addr.s_addr) > ntohl(b->addr.s_addr)) return 1; return 0; } /* dns_a_cmp() */ size_t dns_a_print(void *dst, size_t lim, struct dns_a *a) { char addr[INET_ADDRSTRLEN + 1] = "0.0.0.0"; dns_inet_ntop(AF_INET, &a->addr, addr, sizeof addr); return dns_strlcpy(dst, addr, lim); } /* dns_a_print() */ int dns_aaaa_parse(struct dns_aaaa *aaaa, struct dns_rr *rr, struct dns_packet *P) { if (rr->rd.len != sizeof aaaa->addr.s6_addr) return DNS_EILLEGAL; memcpy(aaaa->addr.s6_addr, &P->data[rr->rd.p], sizeof aaaa->addr.s6_addr); return 0; } /* dns_aaaa_parse() */ int dns_aaaa_push(struct dns_packet *P, struct dns_aaaa *aaaa) { if (P->size - P->end < 2 + sizeof aaaa->addr.s6_addr) return DNS_ENOBUFS; P->data[P->end++] = 0x00; P->data[P->end++] = 0x10; memcpy(&P->data[P->end], aaaa->addr.s6_addr, sizeof aaaa->addr.s6_addr); P->end += sizeof aaaa->addr.s6_addr; return 0; } /* dns_aaaa_push() */ int dns_aaaa_cmp(const struct dns_aaaa *a, const struct dns_aaaa *b) { unsigned i; int cmp; for (i = 0; i < lengthof(a->addr.s6_addr); i++) { if ((cmp = (a->addr.s6_addr[i] - b->addr.s6_addr[i]))) return cmp; } return 0; } /* dns_aaaa_cmp() */ size_t dns_aaaa_arpa(void *_dst, size_t lim, const struct dns_aaaa *aaaa) { static const unsigned char hex[16] = "0123456789abcdef"; struct dns_buf dst = DNS_B_INTO(_dst, lim); unsigned nyble; int i, j; for (i = sizeof aaaa->addr.s6_addr - 1; i >= 0; i--) { nyble = aaaa->addr.s6_addr[i]; for (j = 0; j < 2; j++) { dns_b_putc(&dst, hex[0x0f & nyble]); dns_b_putc(&dst, '.'); nyble >>= 4; } } dns_b_puts(&dst, "ip6.arpa."); return dns_b_strllen(&dst); } /* dns_aaaa_arpa() */ size_t dns_aaaa_print(void *dst, size_t lim, struct dns_aaaa *aaaa) { char addr[INET6_ADDRSTRLEN + 1] = "::"; dns_inet_ntop(AF_INET6, &aaaa->addr, addr, sizeof addr); return dns_strlcpy(dst, addr, lim); } /* dns_aaaa_print() */ int dns_mx_parse(struct dns_mx *mx, struct dns_rr *rr, struct dns_packet *P) { size_t len; int error; if (rr->rd.len < 3) return DNS_EILLEGAL; mx->preference = (0xff00 & (P->data[rr->rd.p + 0] << 8)) | (0x00ff & (P->data[rr->rd.p + 1] << 0)); if (!(len = dns_d_expand(mx->host, sizeof mx->host, rr->rd.p + 2, P, &error))) return error; else if (len >= sizeof mx->host) return DNS_EILLEGAL; return 0; } /* dns_mx_parse() */ int dns_mx_push(struct dns_packet *P, struct dns_mx *mx) { size_t end, len; int error; if (P->size - P->end < 5) return DNS_ENOBUFS; end = P->end; P->end += 2; P->data[P->end++] = 0xff & (mx->preference >> 8); P->data[P->end++] = 0xff & (mx->preference >> 0); if ((error = dns_d_push(P, mx->host, strlen(mx->host)))) goto error; len = P->end - end - 2; P->data[end + 0] = 0xff & (len >> 8); P->data[end + 1] = 0xff & (len >> 0); return 0; error: P->end = end; return error; } /* dns_mx_push() */ int dns_mx_cmp(const struct dns_mx *a, const struct dns_mx *b) { int cmp; if ((cmp = a->preference - b->preference)) return cmp; return strcasecmp(a->host, b->host); } /* dns_mx_cmp() */ size_t dns_mx_print(void *_dst, size_t lim, struct dns_mx *mx) { struct dns_buf dst = DNS_B_INTO(_dst, lim); dns_b_fmtju(&dst, mx->preference, 0); dns_b_putc(&dst, ' '); dns_b_puts(&dst, mx->host); return dns_b_strllen(&dst); } /* dns_mx_print() */ size_t dns_mx_cname(void *dst, size_t lim, struct dns_mx *mx) { return dns_strlcpy(dst, mx->host, lim); } /* dns_mx_cname() */ int dns_ns_parse(struct dns_ns *ns, struct dns_rr *rr, struct dns_packet *P) { size_t len; int error; if (!(len = dns_d_expand(ns->host, sizeof ns->host, rr->rd.p, P, &error))) return error; else if (len >= sizeof ns->host) return DNS_EILLEGAL; return 0; } /* dns_ns_parse() */ int dns_ns_push(struct dns_packet *P, struct dns_ns *ns) { size_t end, len; int error; if (P->size - P->end < 3) return DNS_ENOBUFS; end = P->end; P->end += 2; if ((error = dns_d_push(P, ns->host, strlen(ns->host)))) goto error; len = P->end - end - 2; P->data[end + 0] = 0xff & (len >> 8); P->data[end + 1] = 0xff & (len >> 0); return 0; error: P->end = end; return error; } /* dns_ns_push() */ int dns_ns_cmp(const struct dns_ns *a, const struct dns_ns *b) { return strcasecmp(a->host, b->host); } /* dns_ns_cmp() */ size_t dns_ns_print(void *dst, size_t lim, struct dns_ns *ns) { return dns_strlcpy(dst, ns->host, lim); } /* dns_ns_print() */ size_t dns_ns_cname(void *dst, size_t lim, struct dns_ns *ns) { return dns_strlcpy(dst, ns->host, lim); } /* dns_ns_cname() */ int dns_cname_parse(struct dns_cname *cname, struct dns_rr *rr, struct dns_packet *P) { return dns_ns_parse((struct dns_ns *)cname, rr, P); } /* dns_cname_parse() */ int dns_cname_push(struct dns_packet *P, struct dns_cname *cname) { return dns_ns_push(P, (struct dns_ns *)cname); } /* dns_cname_push() */ int dns_cname_cmp(const struct dns_cname *a, const struct dns_cname *b) { return strcasecmp(a->host, b->host); } /* dns_cname_cmp() */ size_t dns_cname_print(void *dst, size_t lim, struct dns_cname *cname) { return dns_ns_print(dst, lim, (struct dns_ns *)cname); } /* dns_cname_print() */ size_t dns_cname_cname(void *dst, size_t lim, struct dns_cname *cname) { return dns_strlcpy(dst, cname->host, lim); } /* dns_cname_cname() */ int dns_soa_parse(struct dns_soa *soa, struct dns_rr *rr, struct dns_packet *P) { struct { void *dst; size_t lim; } dn[] = { { soa->mname, sizeof soa->mname }, { soa->rname, sizeof soa->rname } }; unsigned *ts[] = { &soa->serial, &soa->refresh, &soa->retry, &soa->expire, &soa->minimum }; unsigned short rp; unsigned i, j, n; int error; /* MNAME / RNAME */ if ((rp = rr->rd.p) >= P->end) return DNS_EILLEGAL; for (i = 0; i < lengthof(dn); i++) { if (!(n = dns_d_expand(dn[i].dst, dn[i].lim, rp, P, &error))) return error; else if (n >= dn[i].lim) return DNS_EILLEGAL; if ((rp = dns_d_skip(rp, P)) >= P->end) return DNS_EILLEGAL; } /* SERIAL / REFRESH / RETRY / EXPIRE / MINIMUM */ for (i = 0; i < lengthof(ts); i++) { for (j = 0; j < 4; j++, rp++) { if (rp >= P->end) return DNS_EILLEGAL; *ts[i] <<= 8; *ts[i] |= (0xff & P->data[rp]); } } return 0; } /* dns_soa_parse() */ int dns_soa_push(struct dns_packet *P, struct dns_soa *soa) { void *dn[] = { soa->mname, soa->rname }; unsigned ts[] = { (0xffffffff & soa->serial), (0x7fffffff & soa->refresh), (0x7fffffff & soa->retry), (0x7fffffff & soa->expire), (0xffffffff & soa->minimum) }; unsigned i, j; size_t end, len; int error; end = P->end; if ((P->end += 2) >= P->size) goto toolong; /* MNAME / RNAME */ for (i = 0; i < lengthof(dn); i++) { if ((error = dns_d_push(P, dn[i], strlen(dn[i])))) goto error; } /* SERIAL / REFRESH / RETRY / EXPIRE / MINIMUM */ for (i = 0; i < lengthof(ts); i++) { if ((P->end += 4) >= P->size) goto toolong; for (j = 1; j <= 4; j++) { P->data[P->end - j] = (0xff & ts[i]); ts[i] >>= 8; } } len = P->end - end - 2; P->data[end + 0] = (0xff & (len >> 8)); P->data[end + 1] = (0xff & (len >> 0)); return 0; toolong: error = DNS_ENOBUFS; /* FALL THROUGH */ error: P->end = end; return error; } /* dns_soa_push() */ int dns_soa_cmp(const struct dns_soa *a, const struct dns_soa *b) { int cmp; if ((cmp = strcasecmp(a->mname, b->mname))) return cmp; if ((cmp = strcasecmp(a->rname, b->rname))) return cmp; if (a->serial > b->serial) return -1; else if (a->serial < b->serial) return 1; if (a->refresh > b->refresh) return -1; else if (a->refresh < b->refresh) return 1; if (a->retry > b->retry) return -1; else if (a->retry < b->retry) return 1; if (a->expire > b->expire) return -1; else if (a->expire < b->expire) return 1; if (a->minimum > b->minimum) return -1; else if (a->minimum < b->minimum) return 1; return 0; } /* dns_soa_cmp() */ size_t dns_soa_print(void *_dst, size_t lim, struct dns_soa *soa) { struct dns_buf dst = DNS_B_INTO(_dst, lim); dns_b_puts(&dst, soa->mname); dns_b_putc(&dst, ' '); dns_b_puts(&dst, soa->rname); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, soa->serial, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, soa->refresh, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, soa->retry, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, soa->expire, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, soa->minimum, 0); return dns_b_strllen(&dst); } /* dns_soa_print() */ int dns_srv_parse(struct dns_srv *srv, struct dns_rr *rr, struct dns_packet *P) { unsigned short rp; unsigned i; size_t n; int error; memset(srv, '\0', sizeof *srv); rp = rr->rd.p; if (rr->rd.len < 7) return DNS_EILLEGAL; for (i = 0; i < 2; i++, rp++) { srv->priority <<= 8; srv->priority |= (0xff & P->data[rp]); } for (i = 0; i < 2; i++, rp++) { srv->weight <<= 8; srv->weight |= (0xff & P->data[rp]); } for (i = 0; i < 2; i++, rp++) { srv->port <<= 8; srv->port |= (0xff & P->data[rp]); } if (!(n = dns_d_expand(srv->target, sizeof srv->target, rp, P, &error))) return error; else if (n >= sizeof srv->target) return DNS_EILLEGAL; return 0; } /* dns_srv_parse() */ int dns_srv_push(struct dns_packet *P, struct dns_srv *srv) { size_t end, len; int error; end = P->end; if (P->size - P->end < 2) goto toolong; P->end += 2; if (P->size - P->end < 6) goto toolong; P->data[P->end++] = 0xff & (srv->priority >> 8); P->data[P->end++] = 0xff & (srv->priority >> 0); P->data[P->end++] = 0xff & (srv->weight >> 8); P->data[P->end++] = 0xff & (srv->weight >> 0); P->data[P->end++] = 0xff & (srv->port >> 8); P->data[P->end++] = 0xff & (srv->port >> 0); if (0 == (len = dns_d_comp(&P->data[P->end], P->size - P->end, srv->target, strlen(srv->target), P, &error))) goto error; else if (P->size - P->end < len) goto toolong; P->end += len; if (P->end > 65535) goto toolong; len = P->end - end - 2; P->data[end + 0] = 0xff & (len >> 8); P->data[end + 1] = 0xff & (len >> 0); return 0; toolong: error = DNS_ENOBUFS; /* FALL THROUGH */ error: P->end = end; return error; } /* dns_srv_push() */ int dns_srv_cmp(const struct dns_srv *a, const struct dns_srv *b) { int cmp; if ((cmp = a->priority - b->priority)) return cmp; /* * FIXME: We need some sort of random seed to implement the dynamic * weighting required by RFC 2782. */ if ((cmp = a->weight - b->weight)) return cmp; if ((cmp = a->port - b->port)) return cmp; return strcasecmp(a->target, b->target); } /* dns_srv_cmp() */ size_t dns_srv_print(void *_dst, size_t lim, struct dns_srv *srv) { struct dns_buf dst = DNS_B_INTO(_dst, lim); dns_b_fmtju(&dst, srv->priority, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, srv->weight, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, srv->port, 0); dns_b_putc(&dst, ' '); dns_b_puts(&dst, srv->target); return dns_b_strllen(&dst); } /* dns_srv_print() */ size_t dns_srv_cname(void *dst, size_t lim, struct dns_srv *srv) { return dns_strlcpy(dst, srv->target, lim); } /* dns_srv_cname() */ unsigned int dns_opt_ttl(const struct dns_opt *opt) { unsigned int ttl = 0; ttl |= (0xffU & opt->rcode) << 24; ttl |= (0xffU & opt->version) << 16; ttl |= (0xffffU & opt->flags) << 0; return ttl; } /* dns_opt_ttl() */ unsigned short dns_opt_class(const struct dns_opt *opt) { return opt->maxudp; } /* dns_opt_class() */ struct dns_opt *dns_opt_init(struct dns_opt *opt, size_t size) { assert(size >= offsetof(struct dns_opt, data)); opt->size = size - offsetof(struct dns_opt, data); opt->len = 0; opt->rcode = 0; opt->version = 0; opt->maxudp = 0; return opt; } /* dns_opt_init() */ static union dns_any *dns_opt_initany(union dns_any *any, size_t size) { return dns_opt_init(&any->opt, size), any; } /* dns_opt_initany() */ int dns_opt_parse(struct dns_opt *opt, struct dns_rr *rr, struct dns_packet *P) { const struct dns_buf src = DNS_B_FROM(&P->data[rr->rd.p], rr->rd.len); struct dns_buf dst = DNS_B_INTO(opt->data, opt->size); int error; opt->rcode = 0xfff & ((rr->ttl >> 20) | dns_header(P)->rcode); opt->version = 0xff & (rr->ttl >> 16); opt->flags = 0xffff & rr->ttl; opt->maxudp = 0xffff & rr->class; while (src.p < src.pe) { int code, len; if (-1 == (code = dns_b_get16(&src, -1))) return src.error; if (-1 == (len = dns_b_get16(&src, -1))) return src.error; switch (code) { default: dns_b_put16(&dst, code); dns_b_put16(&dst, len); if ((error = dns_b_move(&dst, &src, len))) return error; break; } } return 0; } /* dns_opt_parse() */ int dns_opt_push(struct dns_packet *P, struct dns_opt *opt) { const struct dns_buf src = DNS_B_FROM(opt->data, opt->len); struct dns_buf dst = DNS_B_INTO(&P->data[P->end], (P->size - P->end)); int error; /* rdata length (see below) */ if ((error = dns_b_put16(&dst, 0))) goto error; /* ... push known options here */ /* push opaque option data */ if ((error = dns_b_move(&dst, &src, (size_t)(src.pe - src.p)))) goto error; /* rdata length */ if ((error = dns_b_pput16(&dst, dns_b_tell(&dst) - 2, 0))) goto error; #if !DNS_DEBUG_OPT_FORMERR P->end += dns_b_tell(&dst); #endif return 0; error: return error; } /* dns_opt_push() */ int dns_opt_cmp(const struct dns_opt *a, const struct dns_opt *b) { (void)a; (void)b; return -1; } /* dns_opt_cmp() */ size_t dns_opt_print(void *_dst, size_t lim, struct dns_opt *opt) { struct dns_buf dst = DNS_B_INTO(_dst, lim); size_t p; dns_b_putc(&dst, '"'); for (p = 0; p < opt->len; p++) { dns_b_putc(&dst, '\\'); dns_b_fmtju(&dst, opt->data[p], 3); } dns_b_putc(&dst, '"'); return dns_b_strllen(&dst); } /* dns_opt_print() */ int dns_ptr_parse(struct dns_ptr *ptr, struct dns_rr *rr, struct dns_packet *P) { return dns_ns_parse((struct dns_ns *)ptr, rr, P); } /* dns_ptr_parse() */ int dns_ptr_push(struct dns_packet *P, struct dns_ptr *ptr) { return dns_ns_push(P, (struct dns_ns *)ptr); } /* dns_ptr_push() */ size_t dns_ptr_qname(void *dst, size_t lim, int af, void *addr) { switch (af) { case AF_INET6: return dns_aaaa_arpa(dst, lim, addr); case AF_INET: return dns_a_arpa(dst, lim, addr); default: { struct dns_a a; a.addr.s_addr = INADDR_NONE; return dns_a_arpa(dst, lim, &a); } } } /* dns_ptr_qname() */ int dns_ptr_cmp(const struct dns_ptr *a, const struct dns_ptr *b) { return strcasecmp(a->host, b->host); } /* dns_ptr_cmp() */ size_t dns_ptr_print(void *dst, size_t lim, struct dns_ptr *ptr) { return dns_ns_print(dst, lim, (struct dns_ns *)ptr); } /* dns_ptr_print() */ size_t dns_ptr_cname(void *dst, size_t lim, struct dns_ptr *ptr) { return dns_strlcpy(dst, ptr->host, lim); } /* dns_ptr_cname() */ int dns_sshfp_parse(struct dns_sshfp *fp, struct dns_rr *rr, struct dns_packet *P) { unsigned p = rr->rd.p, pe = rr->rd.p + rr->rd.len; if (pe - p < 2) return DNS_EILLEGAL; fp->algo = P->data[p++]; fp->type = P->data[p++]; switch (fp->type) { case DNS_SSHFP_SHA1: if (pe - p < sizeof fp->digest.sha1) return DNS_EILLEGAL; memcpy(fp->digest.sha1, &P->data[p], sizeof fp->digest.sha1); break; default: break; } /* switch() */ return 0; } /* dns_sshfp_parse() */ int dns_sshfp_push(struct dns_packet *P, struct dns_sshfp *fp) { unsigned p = P->end, pe = P->size, n; if (pe - p < 4) return DNS_ENOBUFS; p += 2; P->data[p++] = 0xff & fp->algo; P->data[p++] = 0xff & fp->type; switch (fp->type) { case DNS_SSHFP_SHA1: if (pe - p < sizeof fp->digest.sha1) return DNS_ENOBUFS; memcpy(&P->data[p], fp->digest.sha1, sizeof fp->digest.sha1); p += sizeof fp->digest.sha1; break; default: return DNS_EILLEGAL; } /* switch() */ n = p - P->end - 2; P->data[P->end++] = 0xff & (n >> 8); P->data[P->end++] = 0xff & (n >> 0); P->end = p; return 0; } /* dns_sshfp_push() */ int dns_sshfp_cmp(const struct dns_sshfp *a, const struct dns_sshfp *b) { int cmp; if ((cmp = a->algo - b->algo) || (cmp = a->type - b->type)) return cmp; switch (a->type) { case DNS_SSHFP_SHA1: return memcmp(a->digest.sha1, b->digest.sha1, sizeof a->digest.sha1); default: return 0; } /* switch() */ /* NOT REACHED */ } /* dns_sshfp_cmp() */ size_t dns_sshfp_print(void *_dst, size_t lim, struct dns_sshfp *fp) { static const unsigned char hex[16] = "0123456789abcdef"; struct dns_buf dst = DNS_B_INTO(_dst, lim); size_t i; dns_b_fmtju(&dst, fp->algo, 0); dns_b_putc(&dst, ' '); dns_b_fmtju(&dst, fp->type, 0); dns_b_putc(&dst, ' '); switch (fp->type) { case DNS_SSHFP_SHA1: for (i = 0; i < sizeof fp->digest.sha1; i++) { dns_b_putc(&dst, hex[0x0f & (fp->digest.sha1[i] >> 4)]); dns_b_putc(&dst, hex[0x0f & (fp->digest.sha1[i] >> 0)]); } break; default: dns_b_putc(&dst, '0'); break; } /* switch() */ return dns_b_strllen(&dst); } /* dns_sshfp_print() */ struct dns_txt *dns_txt_init(struct dns_txt *txt, size_t size) { assert(size > offsetof(struct dns_txt, data)); txt->size = size - offsetof(struct dns_txt, data); txt->len = 0; return txt; } /* dns_txt_init() */ static union dns_any *dns_txt_initany(union dns_any *any, size_t size) { /* NB: union dns_any is already initialized as struct dns_txt */ (void)size; return any; } /* dns_txt_initany() */ int dns_txt_parse(struct dns_txt *txt, struct dns_rr *rr, struct dns_packet *P) { struct { unsigned char *b; size_t p, end; } dst, src; unsigned n; dst.b = txt->data; dst.p = 0; dst.end = txt->size; src.b = P->data; src.p = rr->rd.p; src.end = src.p + rr->rd.len; while (src.p < src.end) { n = 0xff & P->data[src.p++]; if (src.end - src.p < n || dst.end - dst.p < n) return DNS_EILLEGAL; memcpy(&dst.b[dst.p], &src.b[src.p], n); dst.p += n; src.p += n; } txt->len = dst.p; return 0; } /* dns_txt_parse() */ int dns_txt_push(struct dns_packet *P, struct dns_txt *txt) { struct { unsigned char *b; size_t p, end; } dst, src; unsigned n; dst.b = P->data; dst.p = P->end; dst.end = P->size; src.b = txt->data; src.p = 0; src.end = txt->len; if (dst.end - dst.p < 2) return DNS_ENOBUFS; n = txt->len + ((txt->len + 254) / 255); dst.b[dst.p++] = 0xff & (n >> 8); dst.b[dst.p++] = 0xff & (n >> 0); while (src.p < src.end) { n = DNS_PP_MIN(255, src.end - src.p); if (dst.p >= dst.end) return DNS_ENOBUFS; dst.b[dst.p++] = n; if (dst.end - dst.p < n) return DNS_ENOBUFS; memcpy(&dst.b[dst.p], &src.b[src.p], n); dst.p += n; src.p += n; } P->end = dst.p; return 0; } /* dns_txt_push() */ int dns_txt_cmp(const struct dns_txt *a, const struct dns_txt *b) { (void)a; (void)b; return -1; } /* dns_txt_cmp() */ size_t dns_txt_print(void *_dst, size_t lim, struct dns_txt *txt) { struct dns_buf src = DNS_B_FROM(txt->data, txt->len); struct dns_buf dst = DNS_B_INTO(_dst, lim); unsigned i; if (src.p < src.pe) { do { dns_b_putc(&dst, '"'); for (i = 0; i < 256 && src.p < src.pe; i++, src.p++) { if (*src.p < 32 || *src.p > 126 || *src.p == '"' || *src.p == '\\') { dns_b_putc(&dst, '\\'); dns_b_fmtju(&dst, *src.p, 3); } else { dns_b_putc(&dst, *src.p); } } dns_b_putc(&dst, '"'); dns_b_putc(&dst, ' '); } while (src.p < src.pe); dns_b_popc(&dst); } else { dns_b_putc(&dst, '"'); dns_b_putc(&dst, '"'); } return dns_b_strllen(&dst); } /* dns_txt_print() */ static const struct dns_rrtype { enum dns_type type; const char *name; union dns_any *(*init)(union dns_any *, size_t); int (*parse)(); int (*push)(); int (*cmp)(); size_t (*print)(); size_t (*cname)(); } dns_rrtypes[] = { { DNS_T_A, "A", 0, &dns_a_parse, &dns_a_push, &dns_a_cmp, &dns_a_print, 0, }, { DNS_T_AAAA, "AAAA", 0, &dns_aaaa_parse, &dns_aaaa_push, &dns_aaaa_cmp, &dns_aaaa_print, 0, }, { DNS_T_MX, "MX", 0, &dns_mx_parse, &dns_mx_push, &dns_mx_cmp, &dns_mx_print, &dns_mx_cname, }, { DNS_T_NS, "NS", 0, &dns_ns_parse, &dns_ns_push, &dns_ns_cmp, &dns_ns_print, &dns_ns_cname, }, { DNS_T_CNAME, "CNAME", 0, &dns_cname_parse, &dns_cname_push, &dns_cname_cmp, &dns_cname_print, &dns_cname_cname, }, { DNS_T_SOA, "SOA", 0, &dns_soa_parse, &dns_soa_push, &dns_soa_cmp, &dns_soa_print, 0, }, { DNS_T_SRV, "SRV", 0, &dns_srv_parse, &dns_srv_push, &dns_srv_cmp, &dns_srv_print, &dns_srv_cname, }, { DNS_T_OPT, "OPT", &dns_opt_initany, &dns_opt_parse, &dns_opt_push, &dns_opt_cmp, &dns_opt_print, 0, }, { DNS_T_PTR, "PTR", 0, &dns_ptr_parse, &dns_ptr_push, &dns_ptr_cmp, &dns_ptr_print, &dns_ptr_cname, }, { DNS_T_TXT, "TXT", &dns_txt_initany, &dns_txt_parse, &dns_txt_push, &dns_txt_cmp, &dns_txt_print, 0, }, { DNS_T_SPF, "SPF", &dns_txt_initany, &dns_txt_parse, &dns_txt_push, &dns_txt_cmp, &dns_txt_print, 0, }, { DNS_T_SSHFP, "SSHFP", 0, &dns_sshfp_parse, &dns_sshfp_push, &dns_sshfp_cmp, &dns_sshfp_print, 0, }, { DNS_T_AXFR, "AXFR", 0, 0, 0, 0, 0, 0, }, }; /* dns_rrtypes[] */ static const struct dns_rrtype *dns_rrtype(enum dns_type type) { const struct dns_rrtype *t; for (t = dns_rrtypes; t < endof(dns_rrtypes); t++) { if (t->type == type && t->parse) { return t; } } return NULL; } /* dns_rrtype() */ union dns_any *dns_any_init(union dns_any *any, size_t size) { dns_static_assert(dns_same_type(any->txt, any->rdata, 1), "unexpected rdata type"); return (union dns_any *)dns_txt_init(&any->rdata, size); } /* dns_any_init() */ static size_t dns_any_sizeof(union dns_any *any) { dns_static_assert(dns_same_type(any->txt, any->rdata, 1), "unexpected rdata type"); return offsetof(struct dns_txt, data) + any->rdata.size; } /* dns_any_sizeof() */ static union dns_any *dns_any_reinit(union dns_any *any, const struct dns_rrtype *t) { return (t->init)? t->init(any, dns_any_sizeof(any)) : any; } /* dns_any_reinit() */ int dns_any_parse(union dns_any *any, struct dns_rr *rr, struct dns_packet *P) { const struct dns_rrtype *t; if ((t = dns_rrtype(rr->type))) return t->parse(dns_any_reinit(any, t), rr, P); if (rr->rd.len > any->rdata.size) return DNS_EILLEGAL; memcpy(any->rdata.data, &P->data[rr->rd.p], rr->rd.len); any->rdata.len = rr->rd.len; return 0; } /* dns_any_parse() */ int dns_any_push(struct dns_packet *P, union dns_any *any, enum dns_type type) { const struct dns_rrtype *t; if ((t = dns_rrtype(type))) return t->push(P, any); if (P->size - P->end < any->rdata.len + 2) return DNS_ENOBUFS; P->data[P->end++] = 0xff & (any->rdata.len >> 8); P->data[P->end++] = 0xff & (any->rdata.len >> 0); memcpy(&P->data[P->end], any->rdata.data, any->rdata.len); P->end += any->rdata.len; return 0; } /* dns_any_push() */ int dns_any_cmp(const union dns_any *a, enum dns_type x, const union dns_any *b, enum dns_type y) { const struct dns_rrtype *t; int cmp; if ((cmp = x - y)) return cmp; if ((t = dns_rrtype(x))) return t->cmp(a, b); return -1; } /* dns_any_cmp() */ size_t dns_any_print(void *_dst, size_t lim, union dns_any *any, enum dns_type type) { const struct dns_rrtype *t; struct dns_buf src, dst; if ((t = dns_rrtype(type))) return t->print(_dst, lim, any); dns_b_from(&src, any->rdata.data, any->rdata.len); dns_b_into(&dst, _dst, lim); dns_b_putc(&dst, '"'); while (src.p < src.pe) { dns_b_putc(&dst, '\\'); dns_b_fmtju(&dst, *src.p++, 3); } dns_b_putc(&dst, '"'); return dns_b_strllen(&dst); } /* dns_any_print() */ size_t dns_any_cname(void *dst, size_t lim, union dns_any *any, enum dns_type type) { const struct dns_rrtype *t; if ((t = dns_rrtype(type)) && t->cname) return t->cname(dst, lim, any); return 0; } /* dns_any_cname() */ /* * H O S T S R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ struct dns_hosts { struct dns_hosts_entry { char host[DNS_D_MAXNAME + 1]; char arpa[73 + 1]; int af; union { struct in_addr a4; struct in6_addr a6; } addr; _Bool alias; struct dns_hosts_entry *next; } *head, **tail; dns_atomic_t refcount; }; /* struct dns_hosts */ struct dns_hosts *dns_hosts_open(int *error) { static const struct dns_hosts hosts_initializer = { .refcount = 1 }; struct dns_hosts *hosts; if (!(hosts = malloc(sizeof *hosts))) goto syerr; *hosts = hosts_initializer; hosts->tail = &hosts->head; return hosts; syerr: *error = dns_syerr(); free(hosts); return 0; } /* dns_hosts_open() */ void dns_hosts_close(struct dns_hosts *hosts) { struct dns_hosts_entry *ent, *xnt; if (!hosts || 1 != dns_hosts_release(hosts)) return; for (ent = hosts->head; ent; ent = xnt) { xnt = ent->next; free(ent); } free(hosts); return; } /* dns_hosts_close() */ dns_refcount_t dns_hosts_acquire(struct dns_hosts *hosts) { return dns_atomic_fetch_add(&hosts->refcount); } /* dns_hosts_acquire() */ dns_refcount_t dns_hosts_release(struct dns_hosts *hosts) { return dns_atomic_fetch_sub(&hosts->refcount); } /* dns_hosts_release() */ struct dns_hosts *dns_hosts_mortal(struct dns_hosts *hosts) { if (hosts) dns_hosts_release(hosts); return hosts; } /* dns_hosts_mortal() */ struct dns_hosts *dns_hosts_local(int *error_) { struct dns_hosts *hosts; int error; if (!(hosts = dns_hosts_open(&error))) goto error; if ((error = dns_hosts_loadpath(hosts, "/etc/hosts"))) goto error; return hosts; error: *error_ = error; dns_hosts_close(hosts); return 0; } /* dns_hosts_local() */ #define dns_hosts_issep(ch) (dns_isspace(ch)) #define dns_hosts_iscom(ch) ((ch) == '#' || (ch) == ';') int dns_hosts_loadfile(struct dns_hosts *hosts, FILE *fp) { struct dns_hosts_entry ent; char word[DNS_PP_MAX(INET6_ADDRSTRLEN, DNS_D_MAXNAME) + 1]; unsigned wp, wc, skip; int ch, error; rewind(fp); do { memset(&ent, '\0', sizeof ent); wc = 0; skip = 0; do { memset(word, '\0', sizeof word); wp = 0; while (EOF != (ch = fgetc(fp)) && ch != '\n') { skip |= !!dns_hosts_iscom(ch); if (skip) continue; if (dns_hosts_issep(ch)) break; if (wp < sizeof word - 1) word[wp] = ch; wp++; } if (!wp) continue; wc++; switch (wc) { case 0: break; case 1: ent.af = (strchr(word, ':'))? AF_INET6 : AF_INET; skip = (1 != dns_inet_pton(ent.af, word, &ent.addr)); break; default: if (!wp) break; dns_d_anchor(ent.host, sizeof ent.host, word, wp); if ((error = dns_hosts_insert(hosts, ent.af, &ent.addr, ent.host, (wc > 2)))) return error; break; } /* switch() */ } while (ch != EOF && ch != '\n'); } while (ch != EOF); return 0; } /* dns_hosts_loadfile() */ int dns_hosts_loadpath(struct dns_hosts *hosts, const char *path) { FILE *fp; int error; if (!(fp = dns_fopen(path, "rt", &error))) return error; error = dns_hosts_loadfile(hosts, fp); fclose(fp); return error; } /* dns_hosts_loadpath() */ int dns_hosts_dump(struct dns_hosts *hosts, FILE *fp) { struct dns_hosts_entry *ent, *xnt; char addr[INET6_ADDRSTRLEN + 1]; unsigned i; for (ent = hosts->head; ent; ent = xnt) { xnt = ent->next; dns_inet_ntop(ent->af, &ent->addr, addr, sizeof addr); fputs(addr, fp); for (i = strlen(addr); i < INET_ADDRSTRLEN; i++) fputc(' ', fp); fputc(' ', fp); fputs(ent->host, fp); fputc('\n', fp); } return 0; } /* dns_hosts_dump() */ int dns_hosts_insert(struct dns_hosts *hosts, int af, const void *addr, const void *host, _Bool alias) { struct dns_hosts_entry *ent; int error; if (!(ent = malloc(sizeof *ent))) goto syerr; dns_d_anchor(ent->host, sizeof ent->host, host, strlen(host)); switch ((ent->af = af)) { case AF_INET6: memcpy(&ent->addr.a6, addr, sizeof ent->addr.a6); dns_aaaa_arpa(ent->arpa, sizeof ent->arpa, addr); break; case AF_INET: memcpy(&ent->addr.a4, addr, sizeof ent->addr.a4); dns_a_arpa(ent->arpa, sizeof ent->arpa, addr); break; default: error = EINVAL; goto error; } /* switch() */ ent->alias = alias; ent->next = 0; *hosts->tail = ent; hosts->tail = &ent->next; return 0; syerr: error = dns_syerr(); error: free(ent); return error; } /* dns_hosts_insert() */ struct dns_packet *dns_hosts_query(struct dns_hosts *hosts, struct dns_packet *Q, int *error_) { struct dns_packet *P = dns_p_new(512); struct dns_packet *A = 0; struct dns_rr rr; struct dns_hosts_entry *ent; int error, af; char qname[DNS_D_MAXNAME + 1]; size_t qlen; if ((error = dns_rr_parse(&rr, 12, Q))) goto error; if (!(qlen = dns_d_expand(qname, sizeof qname, rr.dn.p, Q, &error))) goto error; else if (qlen >= sizeof qname) goto toolong; if ((error = dns_p_push(P, DNS_S_QD, qname, qlen, rr.type, rr.class, 0, 0))) goto error; switch (rr.type) { case DNS_T_PTR: for (ent = hosts->head; ent; ent = ent->next) { if (ent->alias || 0 != strcasecmp(qname, ent->arpa)) continue; if ((error = dns_p_push(P, DNS_S_AN, qname, qlen, rr.type, rr.class, 0, ent->host))) goto error; } break; case DNS_T_AAAA: af = AF_INET6; goto loop; case DNS_T_A: af = AF_INET; loop: for (ent = hosts->head; ent; ent = ent->next) { if (ent->af != af || 0 != strcasecmp(qname, ent->host)) continue; if ((error = dns_p_push(P, DNS_S_AN, qname, qlen, rr.type, rr.class, 0, &ent->addr))) goto error; } break; default: break; } /* switch() */ if (!(A = dns_p_copy(dns_p_make(P->end, &error), P))) goto error; return A; toolong: error = DNS_EILLEGAL; error: *error_ = error; dns_p_free(A); return 0; } /* dns_hosts_query() */ /* * R E S O L V . C O N F R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ struct dns_resolv_conf *dns_resconf_open(int *error) { static const struct dns_resolv_conf resconf_initializer = { .lookup = "bf", .family = { AF_INET, AF_INET6 }, .options = { .ndots = 1, .timeout = 5, .attempts = 2, .tcp = DNS_RESCONF_TCP_ENABLE, }, .iface = { .ss_family = AF_INET }, }; struct dns_resolv_conf *resconf; struct sockaddr_in *sin; if (!(resconf = malloc(sizeof *resconf))) goto syerr; *resconf = resconf_initializer; sin = (struct sockaddr_in *)&resconf->nameserver[0]; sin->sin_family = AF_INET; sin->sin_addr.s_addr = INADDR_ANY; sin->sin_port = htons(53); #if defined(SA_LEN) sin->sin_len = sizeof *sin; #endif if (0 != gethostname(resconf->search[0], sizeof resconf->search[0])) goto syerr; dns_d_anchor(resconf->search[0], sizeof resconf->search[0], resconf->search[0], strlen(resconf->search[0])); dns_d_cleave(resconf->search[0], sizeof resconf->search[0], resconf->search[0], strlen(resconf->search[0])); /* * XXX: If gethostname() returned a string without any label * separator, then search[0][0] should be NUL. */ dns_resconf_acquire(resconf); return resconf; syerr: *error = dns_syerr(); free(resconf); return 0; } /* dns_resconf_open() */ void dns_resconf_close(struct dns_resolv_conf *resconf) { if (!resconf || 1 != dns_resconf_release(resconf)) return /* void */; free(resconf); } /* dns_resconf_close() */ dns_refcount_t dns_resconf_acquire(struct dns_resolv_conf *resconf) { return dns_atomic_fetch_add(&resconf->_.refcount); } /* dns_resconf_acquire() */ dns_refcount_t dns_resconf_release(struct dns_resolv_conf *resconf) { return dns_atomic_fetch_sub(&resconf->_.refcount); } /* dns_resconf_release() */ struct dns_resolv_conf *dns_resconf_mortal(struct dns_resolv_conf *resconf) { if (resconf) dns_resconf_release(resconf); return resconf; } /* dns_resconf_mortal() */ struct dns_resolv_conf *dns_resconf_local(int *error_) { struct dns_resolv_conf *resconf; int error; if (!(resconf = dns_resconf_open(&error))) goto error; if ((error = dns_resconf_loadpath(resconf, "/etc/resolv.conf"))) { /* * NOTE: Both the glibc and BIND9 resolvers ignore a missing * /etc/resolv.conf, defaulting to a nameserver of * 127.0.0.1. See also dns_hints_insert_resconf, and the * default initialization of nameserver[0] in * dns_resconf_open. */ if (error != ENOENT) goto error; } if ((error = dns_nssconf_loadpath(resconf, "/etc/nsswitch.conf"))) { if (error != ENOENT) goto error; } return resconf; error: *error_ = error; dns_resconf_close(resconf); return 0; } /* dns_resconf_local() */ struct dns_resolv_conf *dns_resconf_root(int *error) { struct dns_resolv_conf *resconf; if ((resconf = dns_resconf_local(error))) resconf->options.recurse = 1; return resconf; } /* dns_resconf_root() */ static time_t dns_resconf_timeout(const struct dns_resolv_conf *resconf) { return (time_t)DNS_PP_MIN(INT_MAX, resconf->options.timeout); } /* dns_resconf_timeout() */ enum dns_resconf_keyword { DNS_RESCONF_NAMESERVER, DNS_RESCONF_DOMAIN, DNS_RESCONF_SEARCH, DNS_RESCONF_LOOKUP, DNS_RESCONF_FILE, DNS_RESCONF_BIND, DNS_RESCONF_CACHE, DNS_RESCONF_FAMILY, DNS_RESCONF_INET4, DNS_RESCONF_INET6, DNS_RESCONF_OPTIONS, DNS_RESCONF_EDNS0, DNS_RESCONF_NDOTS, DNS_RESCONF_TIMEOUT, DNS_RESCONF_ATTEMPTS, DNS_RESCONF_ROTATE, DNS_RESCONF_RECURSE, DNS_RESCONF_SMART, DNS_RESCONF_TCP, DNS_RESCONF_TCPx, DNS_RESCONF_INTERFACE, DNS_RESCONF_ZERO, DNS_RESCONF_ONE, DNS_RESCONF_ENABLE, DNS_RESCONF_ONLY, DNS_RESCONF_DISABLE, }; /* enum dns_resconf_keyword */ static enum dns_resconf_keyword dns_resconf_keyword(const char *word) { static const char *words[] = { [DNS_RESCONF_NAMESERVER] = "nameserver", [DNS_RESCONF_DOMAIN] = "domain", [DNS_RESCONF_SEARCH] = "search", [DNS_RESCONF_LOOKUP] = "lookup", [DNS_RESCONF_FILE] = "file", [DNS_RESCONF_BIND] = "bind", [DNS_RESCONF_CACHE] = "cache", [DNS_RESCONF_FAMILY] = "family", [DNS_RESCONF_INET4] = "inet4", [DNS_RESCONF_INET6] = "inet6", [DNS_RESCONF_OPTIONS] = "options", [DNS_RESCONF_EDNS0] = "edns0", [DNS_RESCONF_ROTATE] = "rotate", [DNS_RESCONF_RECURSE] = "recurse", [DNS_RESCONF_SMART] = "smart", [DNS_RESCONF_TCP] = "tcp", [DNS_RESCONF_INTERFACE] = "interface", [DNS_RESCONF_ZERO] = "0", [DNS_RESCONF_ONE] = "1", [DNS_RESCONF_ENABLE] = "enable", [DNS_RESCONF_ONLY] = "only", [DNS_RESCONF_DISABLE] = "disable", }; unsigned i; for (i = 0; i < lengthof(words); i++) { if (words[i] && 0 == strcasecmp(words[i], word)) return i; } if (0 == strncasecmp(word, "ndots:", sizeof "ndots:" - 1)) return DNS_RESCONF_NDOTS; if (0 == strncasecmp(word, "timeout:", sizeof "timeout:" - 1)) return DNS_RESCONF_TIMEOUT; if (0 == strncasecmp(word, "attempts:", sizeof "attempts:" - 1)) return DNS_RESCONF_ATTEMPTS; if (0 == strncasecmp(word, "tcp:", sizeof "tcp:" - 1)) return DNS_RESCONF_TCPx; return -1; } /* dns_resconf_keyword() */ /** OpenBSD-style "[1.2.3.4]:53" nameserver syntax */ int dns_resconf_pton(struct sockaddr_storage *ss, const char *src) { struct { char buf[128], *p; } addr = { "", addr.buf }; unsigned short port = 0; int ch, af = AF_INET, error; while ((ch = *src++)) { switch (ch) { case ' ': /* FALL THROUGH */ case '\t': break; case '[': break; case ']': while ((ch = *src++)) { if (dns_isdigit(ch)) { port *= 10; port += ch - '0'; } } goto inet; case ':': af = AF_INET6; /* FALL THROUGH */ default: if (addr.p < endof(addr.buf) - 1) *addr.p++ = ch; break; } /* switch() */ } /* while() */ inet: if ((error = dns_pton(af, addr.buf, dns_sa_addr(af, ss, NULL)))) return error; port = (!port)? 53 : port; *dns_sa_port(af, ss) = htons(port); dns_sa_family(ss) = af; return 0; } /* dns_resconf_pton() */ #define dns_resconf_issep(ch) (dns_isspace(ch) || (ch) == ',') #define dns_resconf_iscom(ch) ((ch) == '#' || (ch) == ';') int dns_resconf_loadfile(struct dns_resolv_conf *resconf, FILE *fp) { unsigned sa_count = 0; char words[6][DNS_D_MAXNAME + 1]; unsigned wp, wc, i, j, n; int ch, error; rewind(fp); do { memset(words, '\0', sizeof words); wp = 0; wc = 0; while (EOF != (ch = getc(fp)) && ch != '\n') { if (dns_resconf_issep(ch)) { if (wp > 0) { wp = 0; if (++wc >= lengthof(words)) goto skip; } } else if (dns_resconf_iscom(ch)) { skip: do { ch = getc(fp); } while (ch != EOF && ch != '\n'); break; } else if (wp < sizeof words[wc] - 1) { words[wc][wp++] = ch; } else { wp = 0; /* drop word */ goto skip; } } if (wp > 0) wc++; if (wc < 2) continue; switch (dns_resconf_keyword(words[0])) { case DNS_RESCONF_NAMESERVER: if (sa_count >= lengthof(resconf->nameserver)) continue; if ((error = dns_resconf_pton(&resconf->nameserver[sa_count], words[1]))) continue; sa_count++; break; case DNS_RESCONF_DOMAIN: case DNS_RESCONF_SEARCH: memset(resconf->search, '\0', sizeof resconf->search); for (i = 1, j = 0; i < wc && j < lengthof(resconf->search); i++, j++) dns_d_anchor(resconf->search[j], sizeof resconf->search[j], words[i], strlen(words[i])); break; case DNS_RESCONF_LOOKUP: for (i = 1, j = 0; i < wc && j < lengthof(resconf->lookup); i++) { switch (dns_resconf_keyword(words[i])) { case DNS_RESCONF_FILE: resconf->lookup[j++] = 'f'; break; case DNS_RESCONF_BIND: resconf->lookup[j++] = 'b'; break; case DNS_RESCONF_CACHE: resconf->lookup[j++] = 'c'; break; default: break; } /* switch() */ } /* for() */ break; case DNS_RESCONF_FAMILY: for (i = 1, j = 0; i < wc && j < lengthof(resconf->family); i++) { switch (dns_resconf_keyword(words[i])) { case DNS_RESCONF_INET4: resconf->family[j++] = AF_INET; break; case DNS_RESCONF_INET6: resconf->family[j++] = AF_INET6; break; default: break; } } break; case DNS_RESCONF_OPTIONS: for (i = 1; i < wc; i++) { switch (dns_resconf_keyword(words[i])) { case DNS_RESCONF_EDNS0: resconf->options.edns0 = 1; break; case DNS_RESCONF_NDOTS: for (j = sizeof "ndots:" - 1, n = 0; dns_isdigit(words[i][j]); j++) { n *= 10; n += words[i][j] - '0'; } /* for() */ resconf->options.ndots = n; break; case DNS_RESCONF_TIMEOUT: for (j = sizeof "timeout:" - 1, n = 0; dns_isdigit(words[i][j]); j++) { n *= 10; n += words[i][j] - '0'; } /* for() */ resconf->options.timeout = n; break; case DNS_RESCONF_ATTEMPTS: for (j = sizeof "attempts:" - 1, n = 0; dns_isdigit(words[i][j]); j++) { n *= 10; n += words[i][j] - '0'; } /* for() */ resconf->options.attempts = n; break; case DNS_RESCONF_ROTATE: resconf->options.rotate = 1; break; case DNS_RESCONF_RECURSE: resconf->options.recurse = 1; break; case DNS_RESCONF_SMART: resconf->options.smart = 1; break; case DNS_RESCONF_TCP: resconf->options.tcp = DNS_RESCONF_TCP_ONLY; break; case DNS_RESCONF_TCPx: switch (dns_resconf_keyword(&words[i][sizeof "tcp:" - 1])) { case DNS_RESCONF_ENABLE: resconf->options.tcp = DNS_RESCONF_TCP_ENABLE; break; case DNS_RESCONF_ONE: case DNS_RESCONF_ONLY: resconf->options.tcp = DNS_RESCONF_TCP_ONLY; break; case DNS_RESCONF_ZERO: case DNS_RESCONF_DISABLE: resconf->options.tcp = DNS_RESCONF_TCP_DISABLE; break; default: break; } /* switch() */ break; default: break; } /* switch() */ } /* for() */ break; case DNS_RESCONF_INTERFACE: for (i = 0, n = 0; dns_isdigit(words[2][i]); i++) { n *= 10; n += words[2][i] - '0'; } dns_resconf_setiface(resconf, words[1], n); break; default: break; } /* switch() */ } while (ch != EOF); return 0; } /* dns_resconf_loadfile() */ int dns_resconf_loadpath(struct dns_resolv_conf *resconf, const char *path) { FILE *fp; int error; if (!(fp = dns_fopen(path, "rt", &error))) return error; error = dns_resconf_loadfile(resconf, fp); fclose(fp); return error; } /* dns_resconf_loadpath() */ struct dns_anyconf { char *token[16]; unsigned count; char buffer[1024], *tp, *cp; }; /* struct dns_anyconf */ static void dns_anyconf_reset(struct dns_anyconf *cf) { cf->count = 0; cf->tp = cf->cp = cf->buffer; } /* dns_anyconf_reset() */ static int dns_anyconf_push(struct dns_anyconf *cf) { if (!(cf->cp < endof(cf->buffer) && cf->count < lengthof(cf->token))) return ENOMEM; *cf->cp++ = '\0'; cf->token[cf->count++] = cf->tp; cf->tp = cf->cp; return 0; } /* dns_anyconf_push() */ static void dns_anyconf_pop(struct dns_anyconf *cf) { if (cf->count > 0) { --cf->count; cf->tp = cf->cp = cf->token[cf->count]; cf->token[cf->count] = 0; } } /* dns_anyconf_pop() */ static int dns_anyconf_addc(struct dns_anyconf *cf, int ch) { if (!(cf->cp < endof(cf->buffer))) return ENOMEM; *cf->cp++ = ch; return 0; } /* dns_anyconf_addc() */ static _Bool dns_anyconf_match(const char *pat, int mc) { _Bool match; int pc; if (*pat == '^') { match = 0; ++pat; } else { match = 1; } while ((pc = *(const unsigned char *)pat++)) { switch (pc) { case '%': if (!(pc = *(const unsigned char *)pat++)) return !match; switch (pc) { case 'a': if (dns_isalpha(mc)) return match; break; case 'd': if (dns_isdigit(mc)) return match; break; case 'w': if (dns_isalnum(mc)) return match; break; case 's': if (dns_isspace(mc)) return match; break; default: if (mc == pc) return match; break; } /* switch() */ break; default: if (mc == pc) return match; break; } /* switch() */ } /* while() */ return !match; } /* dns_anyconf_match() */ static int dns_anyconf_peek(FILE *fp) { int ch; ch = getc(fp); ungetc(ch, fp); return ch; } /* dns_anyconf_peek() */ static size_t dns_anyconf_skip(const char *pat, FILE *fp) { size_t count = 0; int ch; while (EOF != (ch = getc(fp))) { if (dns_anyconf_match(pat, ch)) { count++; continue; } ungetc(ch, fp); break; } return count; } /* dns_anyconf_skip() */ static size_t dns_anyconf_scan(struct dns_anyconf *cf, const char *pat, FILE *fp, int *error) { size_t len; int ch; while (EOF != (ch = getc(fp))) { if (dns_anyconf_match(pat, ch)) { if ((*error = dns_anyconf_addc(cf, ch))) return 0; continue; } else { ungetc(ch, fp); break; } } if ((len = cf->cp - cf->tp)) { if ((*error = dns_anyconf_push(cf))) return 0; return len; } else { *error = 0; return 0; } } /* dns_anyconf_scan() */ DNS_NOTUSED static void dns_anyconf_dump(struct dns_anyconf *cf, FILE *fp) { unsigned i; fprintf(fp, "tokens:"); for (i = 0; i < cf->count; i++) { fprintf(fp, " %s", cf->token[i]); } fputc('\n', fp); } /* dns_anyconf_dump() */ enum dns_nssconf_keyword { DNS_NSSCONF_INVALID = 0, DNS_NSSCONF_HOSTS = 1, DNS_NSSCONF_SUCCESS, DNS_NSSCONF_NOTFOUND, DNS_NSSCONF_UNAVAIL, DNS_NSSCONF_TRYAGAIN, DNS_NSSCONF_CONTINUE, DNS_NSSCONF_RETURN, DNS_NSSCONF_FILES, DNS_NSSCONF_DNS, DNS_NSSCONF_MDNS, DNS_NSSCONF_LAST, }; /* enum dns_nssconf_keyword */ static enum dns_nssconf_keyword dns_nssconf_keyword(const char *word) { static const char *list[] = { [DNS_NSSCONF_HOSTS] = "hosts", [DNS_NSSCONF_SUCCESS] = "success", [DNS_NSSCONF_NOTFOUND] = "notfound", [DNS_NSSCONF_UNAVAIL] = "unavail", [DNS_NSSCONF_TRYAGAIN] = "tryagain", [DNS_NSSCONF_CONTINUE] = "continue", [DNS_NSSCONF_RETURN] = "return", [DNS_NSSCONF_FILES] = "files", [DNS_NSSCONF_DNS] = "dns", [DNS_NSSCONF_MDNS] = "mdns", }; unsigned i; for (i = 1; i < lengthof(list); i++) { if (list[i] && 0 == strcasecmp(list[i], word)) return i; } return DNS_NSSCONF_INVALID; } /* dns_nssconf_keyword() */ static enum dns_nssconf_keyword dns_nssconf_c2k(int ch) { static const char map[] = { ['S'] = DNS_NSSCONF_SUCCESS, ['N'] = DNS_NSSCONF_NOTFOUND, ['U'] = DNS_NSSCONF_UNAVAIL, ['T'] = DNS_NSSCONF_TRYAGAIN, ['C'] = DNS_NSSCONF_CONTINUE, ['R'] = DNS_NSSCONF_RETURN, ['f'] = DNS_NSSCONF_FILES, ['F'] = DNS_NSSCONF_FILES, ['d'] = DNS_NSSCONF_DNS, ['D'] = DNS_NSSCONF_DNS, ['b'] = DNS_NSSCONF_DNS, ['B'] = DNS_NSSCONF_DNS, ['m'] = DNS_NSSCONF_MDNS, ['M'] = DNS_NSSCONF_MDNS, }; return (ch >= 0 && ch < (int)lengthof(map))? map[ch] : DNS_NSSCONF_INVALID; } /* dns_nssconf_c2k() */ DNS_PRAGMA_PUSH DNS_PRAGMA_QUIET static int dns_nssconf_k2c(int k) { static const char map[DNS_NSSCONF_LAST] = { [DNS_NSSCONF_SUCCESS] = 'S', [DNS_NSSCONF_NOTFOUND] = 'N', [DNS_NSSCONF_UNAVAIL] = 'U', [DNS_NSSCONF_TRYAGAIN] = 'T', [DNS_NSSCONF_CONTINUE] = 'C', [DNS_NSSCONF_RETURN] = 'R', [DNS_NSSCONF_FILES] = 'f', [DNS_NSSCONF_DNS] = 'b', [DNS_NSSCONF_MDNS] = 'm', }; return (k >= 0 && k < (int)lengthof(map))? (map[k]? map[k] : '?') : '?'; } /* dns_nssconf_k2c() */ static const char *dns_nssconf_k2s(int k) { static const char *const map[DNS_NSSCONF_LAST] = { [DNS_NSSCONF_SUCCESS] = "SUCCESS", [DNS_NSSCONF_NOTFOUND] = "NOTFOUND", [DNS_NSSCONF_UNAVAIL] = "UNAVAIL", [DNS_NSSCONF_TRYAGAIN] = "TRYAGAIN", [DNS_NSSCONF_CONTINUE] = "continue", [DNS_NSSCONF_RETURN] = "return", [DNS_NSSCONF_FILES] = "files", [DNS_NSSCONF_DNS] = "dns", [DNS_NSSCONF_MDNS] = "mdns", }; return (k >= 0 && k < (int)lengthof(map))? (map[k]? map[k] : "") : ""; } /* dns_nssconf_k2s() */ DNS_PRAGMA_POP int dns_nssconf_loadfile(struct dns_resolv_conf *resconf, FILE *fp) { enum dns_nssconf_keyword source, status, action; char lookup[sizeof resconf->lookup] = "", *lp; struct dns_anyconf cf; size_t i; int error; while (!feof(fp) && !ferror(fp)) { dns_anyconf_reset(&cf); dns_anyconf_skip("%s", fp); if (!dns_anyconf_scan(&cf, "%w_", fp, &error)) goto nextent; if (DNS_NSSCONF_HOSTS != dns_nssconf_keyword(cf.token[0])) goto nextent; dns_anyconf_pop(&cf); if (!dns_anyconf_skip(": \t", fp)) goto nextent; *(lp = lookup) = '\0'; while (dns_anyconf_scan(&cf, "%w_", fp, &error)) { dns_anyconf_skip(" \t", fp); if ('[' == dns_anyconf_peek(fp)) { dns_anyconf_skip("[! \t", fp); while (dns_anyconf_scan(&cf, "%w_", fp, &error)) { dns_anyconf_skip("= \t", fp); if (!dns_anyconf_scan(&cf, "%w_", fp, &error)) { dns_anyconf_pop(&cf); /* discard status */ dns_anyconf_skip("^#;]\n", fp); /* skip to end of criteria */ break; } dns_anyconf_skip(" \t", fp); } dns_anyconf_skip("] \t", fp); } if ((size_t)(endof(lookup) - lp) < cf.count + 1) /* +1 for '\0' */ goto nextsrc; source = dns_nssconf_keyword(cf.token[0]); switch (source) { case DNS_NSSCONF_DNS: case DNS_NSSCONF_MDNS: case DNS_NSSCONF_FILES: *lp++ = dns_nssconf_k2c(source); break; default: goto nextsrc; } for (i = 1; i + 1 < cf.count; i += 2) { status = dns_nssconf_keyword(cf.token[i]); action = dns_nssconf_keyword(cf.token[i + 1]); switch (status) { case DNS_NSSCONF_SUCCESS: case DNS_NSSCONF_NOTFOUND: case DNS_NSSCONF_UNAVAIL: case DNS_NSSCONF_TRYAGAIN: *lp++ = dns_nssconf_k2c(status); break; default: continue; } switch (action) { case DNS_NSSCONF_CONTINUE: case DNS_NSSCONF_RETURN: break; default: action = (status == DNS_NSSCONF_SUCCESS) ? DNS_NSSCONF_RETURN : DNS_NSSCONF_CONTINUE; break; } *lp++ = dns_nssconf_k2c(action); } nextsrc: *lp = '\0'; dns_anyconf_reset(&cf); } nextent: dns_anyconf_skip("^\n", fp); } if (*lookup) strncpy(resconf->lookup, lookup, sizeof resconf->lookup); return 0; } /* dns_nssconf_loadfile() */ int dns_nssconf_loadpath(struct dns_resolv_conf *resconf, const char *path) { FILE *fp; int error; if (!(fp = dns_fopen(path, "rt", &error))) return error; error = dns_nssconf_loadfile(resconf, fp); fclose(fp); return error; } /* dns_nssconf_loadpath() */ struct dns_nssconf_source { enum dns_nssconf_keyword source, success, notfound, unavail, tryagain; }; /* struct dns_nssconf_source */ typedef unsigned dns_nssconf_i; static inline int dns_nssconf_peek(const struct dns_resolv_conf *resconf, dns_nssconf_i state) { return (state < lengthof(resconf->lookup) && resconf->lookup[state])? resconf->lookup[state] : 0; } /* dns_nssconf_peek() */ static _Bool dns_nssconf_next(struct dns_nssconf_source *src, const struct dns_resolv_conf *resconf, dns_nssconf_i *state) { int source, status, action; src->source = DNS_NSSCONF_INVALID; src->success = DNS_NSSCONF_RETURN; src->notfound = DNS_NSSCONF_CONTINUE; src->unavail = DNS_NSSCONF_CONTINUE; src->tryagain = DNS_NSSCONF_CONTINUE; while ((source = dns_nssconf_peek(resconf, *state))) { source = dns_nssconf_c2k(source); ++*state; switch (source) { case DNS_NSSCONF_FILES: case DNS_NSSCONF_DNS: case DNS_NSSCONF_MDNS: src->source = source; break; default: continue; } while ((status = dns_nssconf_peek(resconf, *state)) && (action = dns_nssconf_peek(resconf, *state + 1))) { status = dns_nssconf_c2k(status); action = dns_nssconf_c2k(action); switch (action) { case DNS_NSSCONF_RETURN: case DNS_NSSCONF_CONTINUE: break; default: goto done; } switch (status) { case DNS_NSSCONF_SUCCESS: src->success = action; break; case DNS_NSSCONF_NOTFOUND: src->notfound = action; break; case DNS_NSSCONF_UNAVAIL: src->unavail = action; break; case DNS_NSSCONF_TRYAGAIN: src->tryagain = action; break; default: goto done; } *state += 2; } break; } done: return src->source != DNS_NSSCONF_INVALID; } /* dns_nssconf_next() */ static int dns_nssconf_dump_status(int status, int action, unsigned *count, FILE *fp) { switch (status) { case DNS_NSSCONF_SUCCESS: if (action == DNS_NSSCONF_RETURN) return 0; break; default: if (action == DNS_NSSCONF_CONTINUE) return 0; break; } fputc(' ', fp); if (!*count) fputc('[', fp); fprintf(fp, "%s=%s", dns_nssconf_k2s(status), dns_nssconf_k2s(action)); ++*count; return 0; } /* dns_nssconf_dump_status() */ int dns_nssconf_dump(struct dns_resolv_conf *resconf, FILE *fp) { struct dns_nssconf_source src; dns_nssconf_i i = 0; fputs("hosts:", fp); while (dns_nssconf_next(&src, resconf, &i)) { unsigned n = 0; fprintf(fp, " %s", dns_nssconf_k2s(src.source)); dns_nssconf_dump_status(DNS_NSSCONF_SUCCESS, src.success, &n, fp); dns_nssconf_dump_status(DNS_NSSCONF_NOTFOUND, src.notfound, &n, fp); dns_nssconf_dump_status(DNS_NSSCONF_UNAVAIL, src.unavail, &n, fp); dns_nssconf_dump_status(DNS_NSSCONF_TRYAGAIN, src.tryagain, &n, fp); if (n) fputc(']', fp); } fputc('\n', fp); return 0; } /* dns_nssconf_dump() */ int dns_resconf_setiface(struct dns_resolv_conf *resconf, const char *addr, unsigned short port) { int af = (strchr(addr, ':'))? AF_INET6 : AF_INET; int error; if ((error = dns_pton(af, addr, dns_sa_addr(af, &resconf->iface, NULL)))) return error; *dns_sa_port(af, &resconf->iface) = htons(port); resconf->iface.ss_family = af; return 0; } /* dns_resconf_setiface() */ #define DNS_SM_RESTORE \ do { \ pc = 0xff & (*state >> 0); \ srchi = 0xff & (*state >> 8); \ ndots = 0xff & (*state >> 16); \ } while (0) #define DNS_SM_SAVE \ do { \ *state = ((0xff & pc) << 0) \ | ((0xff & srchi) << 8) \ | ((0xff & ndots) << 16); \ } while (0) size_t dns_resconf_search(void *dst, size_t lim, const void *qname, size_t qlen, struct dns_resolv_conf *resconf, dns_resconf_i_t *state) { unsigned pc, srchi, ndots, len; DNS_SM_ENTER; /* if FQDN then return as-is and finish */ if (dns_d_isanchored(qname, qlen)) { len = dns_d_anchor(dst, lim, qname, qlen); DNS_SM_YIELD(len); DNS_SM_EXIT; } ndots = dns_d_ndots(qname, qlen); if (ndots >= resconf->options.ndots) { len = dns_d_anchor(dst, lim, qname, qlen); DNS_SM_YIELD(len); } while (srchi < lengthof(resconf->search) && resconf->search[srchi][0]) { struct dns_buf buf = DNS_B_INTO(dst, lim); const char *dn = resconf->search[srchi++]; dns_b_put(&buf, qname, qlen); dns_b_putc(&buf, '.'); dns_b_puts(&buf, dn); if (!dns_d_isanchored(dn, strlen(dn))) dns_b_putc(&buf, '.'); len = dns_b_strllen(&buf); DNS_SM_YIELD(len); } if (ndots < resconf->options.ndots) { len = dns_d_anchor(dst, lim, qname, qlen); DNS_SM_YIELD(len); } DNS_SM_LEAVE; return dns_strlcpy(dst, "", lim); } /* dns_resconf_search() */ #undef DNS_SM_SAVE #undef DNS_SM_RESTORE int dns_resconf_dump(struct dns_resolv_conf *resconf, FILE *fp) { unsigned i; int af; for (i = 0; i < lengthof(resconf->nameserver) && (af = resconf->nameserver[i].ss_family) != AF_UNSPEC; i++) { char addr[INET6_ADDRSTRLEN + 1] = "[INVALID]"; unsigned short port; dns_inet_ntop(af, dns_sa_addr(af, &resconf->nameserver[i], NULL), addr, sizeof addr); port = ntohs(*dns_sa_port(af, &resconf->nameserver[i])); if (port == 53) fprintf(fp, "nameserver %s\n", addr); else fprintf(fp, "nameserver [%s]:%hu\n", addr, port); } fprintf(fp, "search"); for (i = 0; i < lengthof(resconf->search) && resconf->search[i][0]; i++) fprintf(fp, " %s", resconf->search[i]); fputc('\n', fp); fputs("; ", fp); dns_nssconf_dump(resconf, fp); fprintf(fp, "lookup"); for (i = 0; i < lengthof(resconf->lookup) && resconf->lookup[i]; i++) { switch (resconf->lookup[i]) { case 'b': fprintf(fp, " bind"); break; case 'f': fprintf(fp, " file"); break; case 'c': fprintf(fp, " cache"); break; } } fputc('\n', fp); fprintf(fp, "options ndots:%u timeout:%u attempts:%u", resconf->options.ndots, resconf->options.timeout, resconf->options.attempts); if (resconf->options.edns0) fprintf(fp, " edns0"); if (resconf->options.rotate) fprintf(fp, " rotate"); if (resconf->options.recurse) fprintf(fp, " recurse"); if (resconf->options.smart) fprintf(fp, " smart"); switch (resconf->options.tcp) { case DNS_RESCONF_TCP_ENABLE: break; case DNS_RESCONF_TCP_ONLY: fprintf(fp, " tcp"); break; case DNS_RESCONF_TCP_DISABLE: fprintf(fp, " tcp:disable"); break; } fputc('\n', fp); if ((af = resconf->iface.ss_family) != AF_UNSPEC) { char addr[INET6_ADDRSTRLEN + 1] = "[INVALID]"; dns_inet_ntop(af, dns_sa_addr(af, &resconf->iface, NULL), addr, sizeof addr); fprintf(fp, "interface %s %hu\n", addr, ntohs(*dns_sa_port(af, &resconf->iface))); } return 0; } /* dns_resconf_dump() */ /* * H I N T S E R V E R R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ struct dns_hints_soa { unsigned char zone[DNS_D_MAXNAME + 1]; struct { struct sockaddr_storage ss; unsigned priority; } addrs[16]; unsigned count; struct dns_hints_soa *next; }; /* struct dns_hints_soa */ struct dns_hints { dns_atomic_t refcount; struct dns_hints_soa *head; }; /* struct dns_hints */ struct dns_hints *dns_hints_open(struct dns_resolv_conf *resconf, int *error) { static const struct dns_hints H_initializer; struct dns_hints *H; (void)resconf; if (!(H = malloc(sizeof *H))) goto syerr; *H = H_initializer; dns_hints_acquire(H); return H; syerr: *error = dns_syerr(); free(H); return 0; } /* dns_hints_open() */ void dns_hints_close(struct dns_hints *H) { struct dns_hints_soa *soa, *nxt; if (!H || 1 != dns_hints_release(H)) return /* void */; for (soa = H->head; soa; soa = nxt) { nxt = soa->next; free(soa); } free(H); return /* void */; } /* dns_hints_close() */ dns_refcount_t dns_hints_acquire(struct dns_hints *H) { return dns_atomic_fetch_add(&H->refcount); } /* dns_hints_acquire() */ dns_refcount_t dns_hints_release(struct dns_hints *H) { return dns_atomic_fetch_sub(&H->refcount); } /* dns_hints_release() */ struct dns_hints *dns_hints_mortal(struct dns_hints *hints) { if (hints) dns_hints_release(hints); return hints; } /* dns_hints_mortal() */ struct dns_hints *dns_hints_local(struct dns_resolv_conf *resconf, int *error_) { struct dns_hints *hints = 0; int error; if (resconf) dns_resconf_acquire(resconf); else if (!(resconf = dns_resconf_local(&error))) goto error; if (!(hints = dns_hints_open(resconf, &error))) goto error; error = 0; if (0 == dns_hints_insert_resconf(hints, ".", resconf, &error) && error) goto error; dns_resconf_close(resconf); return hints; error: *error_ = error; dns_resconf_close(resconf); dns_hints_close(hints); return 0; } /* dns_hints_local() */ struct dns_hints *dns_hints_root(struct dns_resolv_conf *resconf, int *error_) { static const struct { int af; char addr[INET6_ADDRSTRLEN]; } root_hints[] = { { AF_INET, "198.41.0.4" }, /* A.ROOT-SERVERS.NET. */ { AF_INET6, "2001:503:ba3e::2:30" }, /* A.ROOT-SERVERS.NET. */ { AF_INET, "192.228.79.201" }, /* B.ROOT-SERVERS.NET. */ { AF_INET6, "2001:500:84::b" }, /* B.ROOT-SERVERS.NET. */ { AF_INET, "192.33.4.12" }, /* C.ROOT-SERVERS.NET. */ { AF_INET6, "2001:500:2::c" }, /* C.ROOT-SERVERS.NET. */ { AF_INET, "199.7.91.13" }, /* D.ROOT-SERVERS.NET. */ { AF_INET6, "2001:500:2d::d" }, /* D.ROOT-SERVERS.NET. */ { AF_INET, "192.203.230.10" }, /* E.ROOT-SERVERS.NET. */ { AF_INET, "192.5.5.241" }, /* F.ROOT-SERVERS.NET. */ { AF_INET6, "2001:500:2f::f" }, /* F.ROOT-SERVERS.NET. */ { AF_INET, "192.112.36.4" }, /* G.ROOT-SERVERS.NET. */ { AF_INET, "128.63.2.53" }, /* H.ROOT-SERVERS.NET. */ { AF_INET6, "2001:500:1::803f:235" }, /* H.ROOT-SERVERS.NET. */ { AF_INET, "192.36.148.17" }, /* I.ROOT-SERVERS.NET. */ { AF_INET6, "2001:7FE::53" }, /* I.ROOT-SERVERS.NET. */ { AF_INET, "192.58.128.30" }, /* J.ROOT-SERVERS.NET. */ { AF_INET6, "2001:503:c27::2:30" }, /* J.ROOT-SERVERS.NET. */ { AF_INET, "193.0.14.129" }, /* K.ROOT-SERVERS.NET. */ { AF_INET6, "2001:7FD::1" }, /* K.ROOT-SERVERS.NET. */ { AF_INET, "199.7.83.42" }, /* L.ROOT-SERVERS.NET. */ { AF_INET6, "2001:500:3::42" }, /* L.ROOT-SERVERS.NET. */ { AF_INET, "202.12.27.33" }, /* M.ROOT-SERVERS.NET. */ { AF_INET6, "2001:DC3::35" }, /* M.ROOT-SERVERS.NET. */ }; struct dns_hints *hints = 0; struct sockaddr_storage ss; unsigned i; int error, af; if (!(hints = dns_hints_open(resconf, &error))) goto error; for (i = 0; i < lengthof(root_hints); i++) { af = root_hints[i].af; if ((error = dns_pton(af, root_hints[i].addr, dns_sa_addr(af, &ss, NULL)))) goto error; *dns_sa_port(af, &ss) = htons(53); ss.ss_family = af; if ((error = dns_hints_insert(hints, ".", (struct sockaddr *)&ss, 1))) goto error; } return hints; error: *error_ = error; dns_hints_close(hints); return 0; } /* dns_hints_root() */ static struct dns_hints_soa *dns_hints_fetch(struct dns_hints *H, const char *zone) { struct dns_hints_soa *soa; for (soa = H->head; soa; soa = soa->next) { if (0 == strcasecmp(zone, (char *)soa->zone)) return soa; } return 0; } /* dns_hints_fetch() */ int dns_hints_insert(struct dns_hints *H, const char *zone, const struct sockaddr *sa, unsigned priority) { static const struct dns_hints_soa soa_initializer; struct dns_hints_soa *soa; unsigned i; if (!(soa = dns_hints_fetch(H, zone))) { if (!(soa = malloc(sizeof *soa))) return dns_syerr(); *soa = soa_initializer; dns_strlcpy((char *)soa->zone, zone, sizeof soa->zone); soa->next = H->head; H->head = soa; } i = soa->count % lengthof(soa->addrs); memcpy(&soa->addrs[i].ss, sa, dns_sa_len(sa)); soa->addrs[i].priority = DNS_PP_MAX(1, priority); if (soa->count < lengthof(soa->addrs)) soa->count++; return 0; } /* dns_hints_insert() */ static _Bool dns_hints_isinaddr_any(const void *sa) { struct in_addr *addr; if (dns_sa_family(sa) != AF_INET) return 0; addr = dns_sa_addr(AF_INET, sa, NULL); return addr->s_addr == htonl(INADDR_ANY); } unsigned dns_hints_insert_resconf(struct dns_hints *H, const char *zone, const struct dns_resolv_conf *resconf, int *error_) { unsigned i, n, p; int error; for (i = 0, n = 0, p = 1; i < lengthof(resconf->nameserver) && resconf->nameserver[i].ss_family != AF_UNSPEC; i++, n++) { union { struct sockaddr_in sin; } tmp; struct sockaddr *ns; /* * dns_resconf_open initializes nameserver[0] to INADDR_ANY. * * Traditionally the semantics of 0.0.0.0 meant the default * interface, which evolved to mean the loopback interface. * See comment block preceding resolv/res_init.c:res_init in * glibc 2.23. As of 2.23, glibc no longer translates * 0.0.0.0 despite the code comment, but it does default to * 127.0.0.1 when no nameservers are present. * * BIND9 as of 9.10.3 still translates 0.0.0.0 to 127.0.0.1. * See lib/lwres/lwconfig.c:lwres_create_addr and the * convert_zero flag. 127.0.0.1 is also the default when no * nameservers are present. */ if (dns_hints_isinaddr_any(&resconf->nameserver[i])) { memcpy(&tmp.sin, &resconf->nameserver[i], sizeof tmp.sin); tmp.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); ns = (struct sockaddr *)&tmp.sin; } else { ns = (struct sockaddr *)&resconf->nameserver[i]; } if ((error = dns_hints_insert(H, zone, ns, p))) goto error; p += !resconf->options.rotate; } return n; error: *error_ = error; return n; } /* dns_hints_insert_resconf() */ static int dns_hints_i_cmp(unsigned a, unsigned b, struct dns_hints_i *i, struct dns_hints_soa *soa) { int cmp; if ((cmp = soa->addrs[a].priority - soa->addrs[b].priority)) return cmp; return dns_k_shuffle16(a, i->state.seed) - dns_k_shuffle16(b, i->state.seed); } /* dns_hints_i_cmp() */ static unsigned dns_hints_i_start(struct dns_hints_i *i, struct dns_hints_soa *soa) { unsigned p0, p; p0 = 0; for (p = 1; p < soa->count; p++) { if (dns_hints_i_cmp(p, p0, i, soa) < 0) p0 = p; } return p0; } /* dns_hints_i_start() */ static unsigned dns_hints_i_skip(unsigned p0, struct dns_hints_i *i, struct dns_hints_soa *soa) { unsigned pZ, p; for (pZ = 0; pZ < soa->count; pZ++) { if (dns_hints_i_cmp(pZ, p0, i, soa) > 0) goto cont; } return soa->count; cont: for (p = pZ + 1; p < soa->count; p++) { if (dns_hints_i_cmp(p, p0, i, soa) <= 0) continue; if (dns_hints_i_cmp(p, pZ, i, soa) >= 0) continue; pZ = p; } return pZ; } /* dns_hints_i_skip() */ static struct dns_hints_i *dns_hints_i_init(struct dns_hints_i *i, struct dns_hints *hints) { static const struct dns_hints_i i_initializer; struct dns_hints_soa *soa; i->state = i_initializer.state; do { i->state.seed = dns_random(); } while (0 == i->state.seed); if ((soa = dns_hints_fetch(hints, i->zone))) { i->state.next = dns_hints_i_start(i, soa); } return i; } /* dns_hints_i_init() */ unsigned dns_hints_grep(struct sockaddr **sa, socklen_t *sa_len, unsigned lim, struct dns_hints_i *i, struct dns_hints *H) { struct dns_hints_soa *soa; unsigned n; if (!(soa = dns_hints_fetch(H, i->zone))) return 0; n = 0; while (i->state.next < soa->count && n < lim) { *sa = (struct sockaddr *)&soa->addrs[i->state.next].ss; *sa_len = dns_sa_len(*sa); sa++; sa_len++; n++; i->state.next = dns_hints_i_skip(i->state.next, i, soa); } return n; } /* dns_hints_grep() */ struct dns_packet *dns_hints_query(struct dns_hints *hints, struct dns_packet *Q, int *error_) { struct dns_packet *A, *P; struct dns_rr rr; char zone[DNS_D_MAXNAME + 1]; size_t zlen; struct dns_hints_i i; struct sockaddr *sa; socklen_t slen; int error; if (!dns_rr_grep(&rr, 1, dns_rr_i_new(Q, .section = DNS_S_QUESTION), Q, &error)) goto error; if (!(zlen = dns_d_expand(zone, sizeof zone, rr.dn.p, Q, &error))) goto error; else if (zlen >= sizeof zone) goto toolong; P = dns_p_new(512); dns_header(P)->qr = 1; if ((error = dns_rr_copy(P, &rr, Q))) goto error; if ((error = dns_p_push(P, DNS_S_AUTHORITY, ".", strlen("."), DNS_T_NS, DNS_C_IN, 0, "hints.local."))) goto error; do { i.zone = zone; dns_hints_i_init(&i, hints); while (dns_hints_grep(&sa, &slen, 1, &i, hints)) { int af = sa->sa_family; int rtype = (af == AF_INET6)? DNS_T_AAAA : DNS_T_A; if ((error = dns_p_push(P, DNS_S_ADDITIONAL, "hints.local.", strlen("hints.local."), rtype, DNS_C_IN, 0, dns_sa_addr(af, sa, NULL)))) goto error; } } while ((zlen = dns_d_cleave(zone, sizeof zone, zone, zlen))); if (!(A = dns_p_copy(dns_p_make(P->end, &error), P))) goto error; return A; toolong: error = DNS_EILLEGAL; error: *error_ = error; return 0; } /* dns_hints_query() */ /** ugly hack to support specifying ports other than 53 in resolv.conf. */ static unsigned short dns_hints_port(struct dns_hints *hints, int af, void *addr) { struct dns_hints_soa *soa; void *addrsoa; socklen_t addrlen; unsigned short port; unsigned i; for (soa = hints->head; soa; soa = soa->next) { for (i = 0; i < soa->count; i++) { if (af != soa->addrs[i].ss.ss_family) continue; if (!(addrsoa = dns_sa_addr(af, &soa->addrs[i].ss, &addrlen))) continue; if (memcmp(addr, addrsoa, addrlen)) continue; port = *dns_sa_port(af, &soa->addrs[i].ss); return (port)? port : htons(53); } } return htons(53); } /* dns_hints_port() */ int dns_hints_dump(struct dns_hints *hints, FILE *fp) { struct dns_hints_soa *soa; char addr[INET6_ADDRSTRLEN]; unsigned i; int af, error; for (soa = hints->head; soa; soa = soa->next) { fprintf(fp, "ZONE \"%s\"\n", soa->zone); for (i = 0; i < soa->count; i++) { af = soa->addrs[i].ss.ss_family; if ((error = dns_ntop(af, dns_sa_addr(af, &soa->addrs[i].ss, NULL), addr, sizeof addr))) return error; fprintf(fp, "\t(%d) [%s]:%hu\n", (int)soa->addrs[i].priority, addr, ntohs(*dns_sa_port(af, &soa->addrs[i].ss))); } } return 0; } /* dns_hints_dump() */ /* * C A C H E R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ static dns_refcount_t dns_cache_acquire(struct dns_cache *cache) { return dns_atomic_fetch_add(&cache->_.refcount); } /* dns_cache_acquire() */ static dns_refcount_t dns_cache_release(struct dns_cache *cache) { return dns_atomic_fetch_sub(&cache->_.refcount); } /* dns_cache_release() */ static struct dns_packet *dns_cache_query(struct dns_packet *query, struct dns_cache *cache, int *error) { (void)query; (void)cache; (void)error; return NULL; } /* dns_cache_query() */ static int dns_cache_submit(struct dns_packet *query, struct dns_cache *cache) { (void)query; (void)cache; return 0; } /* dns_cache_submit() */ static int dns_cache_check(struct dns_cache *cache) { (void)cache; return 0; } /* dns_cache_check() */ static struct dns_packet *dns_cache_fetch(struct dns_cache *cache, int *error) { (void)cache; (void)error; return NULL; } /* dns_cache_fetch() */ static int dns_cache_pollfd(struct dns_cache *cache) { (void)cache; return -1; } /* dns_cache_pollfd() */ static short dns_cache_events(struct dns_cache *cache) { (void)cache; return 0; } /* dns_cache_events() */ static void dns_cache_clear(struct dns_cache *cache) { (void)cache; return; } /* dns_cache_clear() */ struct dns_cache *dns_cache_init(struct dns_cache *cache) { static const struct dns_cache c_init = { .acquire = &dns_cache_acquire, .release = &dns_cache_release, .query = &dns_cache_query, .submit = &dns_cache_submit, .check = &dns_cache_check, .fetch = &dns_cache_fetch, .pollfd = &dns_cache_pollfd, .events = &dns_cache_events, .clear = &dns_cache_clear, ._ = { .refcount = 1, }, }; *cache = c_init; return cache; } /* dns_cache_init() */ void dns_cache_close(struct dns_cache *cache) { if (cache) cache->release(cache); } /* dns_cache_close() */ /* * S O C K E T R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ static void dns_socketclose(int *fd, const struct dns_options *opts) { if (opts && opts->closefd.cb) opts->closefd.cb(fd, opts->closefd.arg); if (*fd != -1) { #if _WIN32 closesocket(*fd); #else close(*fd); #endif *fd = -1; } } /* dns_socketclose() */ #ifndef HAVE_IOCTLSOCKET #define HAVE_IOCTLSOCKET (_WIN32 || _WIN64) #endif #ifndef HAVE_SOCK_CLOEXEC #define HAVE_SOCK_CLOEXEC (defined SOCK_CLOEXEC) #endif #ifndef HAVE_SOCK_NONBLOCK #define HAVE_SOCK_NONBLOCK (defined SOCK_NONBLOCK) #endif #define DNS_SO_MAXTRY 7 static int dns_socket(struct sockaddr *local, int type, int *error_) { int fd = -1, flags, error; #if defined FIONBIO unsigned long opt; #endif flags = 0; #if HAVE_SOCK_CLOEXEC flags |= SOCK_CLOEXEC; #endif #if HAVE_SOCK_NONBLOCK flags |= SOCK_NONBLOCK; #endif if (-1 == (fd = socket(local->sa_family, type|flags, 0))) goto soerr; #if defined F_SETFD && !HAVE_SOCK_CLOEXEC if (-1 == fcntl(fd, F_SETFD, 1)) goto syerr; #endif #if defined O_NONBLOCK && !HAVE_SOCK_NONBLOCK if (-1 == (flags = fcntl(fd, F_GETFL))) goto syerr; if (-1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK)) goto syerr; #elif defined FIONBIO && HAVE_IOCTLSOCKET opt = 1; if (0 != ioctlsocket(fd, FIONBIO, &opt)) goto soerr; #endif #if defined SO_NOSIGPIPE if (type != SOCK_DGRAM) { if (0 != setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &(int){ 1 }, sizeof (int))) goto soerr; } #endif if (local->sa_family != AF_INET && local->sa_family != AF_INET6) return fd; if (type != SOCK_DGRAM) return fd; /* * FreeBSD, Linux, OpenBSD, OS X, and Solaris use random ports by * default. Though the ephemeral range is quite small on OS X * (49152-65535 on 10.10) and Linux (32768-60999 on 4.4.0, Ubuntu * Xenial). See also RFC 6056. * * TODO: Optionally rely on the kernel to select a random port. */ if (*dns_sa_port(local->sa_family, local) == 0) { struct sockaddr_storage tmp; unsigned i, port; memcpy(&tmp, local, dns_sa_len(local)); for (i = 0; i < DNS_SO_MAXTRY; i++) { port = 1025 + (dns_random() % 64510); *dns_sa_port(tmp.ss_family, &tmp) = htons(port); if (0 == bind(fd, (struct sockaddr *)&tmp, dns_sa_len(&tmp))) return fd; } /* NB: continue to next bind statement */ } if (0 == bind(fd, local, dns_sa_len(local))) return fd; /* FALL THROUGH */ soerr: error = dns_soerr(); goto error; #if (defined F_SETFD && !HAVE_SOCK_CLOEXEC) || (defined O_NONBLOCK && !HAVE_SOCK_NONBLOCK) syerr: error = dns_syerr(); goto error; #endif error: *error_ = error; dns_socketclose(&fd, NULL); return -1; } /* dns_socket() */ enum { DNS_SO_UDP_INIT = 1, DNS_SO_UDP_CONN, DNS_SO_UDP_SEND, DNS_SO_UDP_RECV, DNS_SO_UDP_DONE, DNS_SO_TCP_INIT, DNS_SO_TCP_CONN, DNS_SO_TCP_SEND, DNS_SO_TCP_RECV, DNS_SO_TCP_DONE, }; struct dns_socket { struct dns_options opts; int udp; int tcp; int *old; unsigned onum, olim; int type; struct sockaddr_storage local, remote; struct dns_k_permutor qids; struct dns_stat stat; /* * NOTE: dns_so_reset() zeroes everything from here down. */ int state; unsigned short qid; char qname[DNS_D_MAXNAME + 1]; size_t qlen; enum dns_type qtype; enum dns_class qclass; struct dns_packet *query; size_t qout; struct dns_clock elapsed; struct dns_packet *answer; size_t alen, apos; }; /* struct dns_socket */ /* * NOTE: Actual closure delayed so that kqueue(2) and epoll(2) callers have * a chance to recognize a state change after installing a persistent event * and where sequential descriptors with the same integer value returned * from _pollfd() would be ambiguous. See dns_so_closefds(). */ static int dns_so_closefd(struct dns_socket *so, int *fd) { int error; if (*fd == -1) return 0; if (so->opts.closefd.cb) { if ((error = so->opts.closefd.cb(fd, so->opts.closefd.arg))) { return error; } else if (*fd == -1) return 0; } if (!(so->onum < so->olim)) { unsigned olim = DNS_PP_MAX(4, so->olim * 2); void *old; if (!(old = realloc(so->old, sizeof so->old[0] * olim))) return dns_syerr(); so->old = old; so->olim = olim; } so->old[so->onum++] = *fd; *fd = -1; return 0; } /* dns_so_closefd() */ #define DNS_SO_CLOSE_UDP 0x01 #define DNS_SO_CLOSE_TCP 0x02 #define DNS_SO_CLOSE_OLD 0x04 #define DNS_SO_CLOSE_ALL (DNS_SO_CLOSE_UDP|DNS_SO_CLOSE_TCP|DNS_SO_CLOSE_OLD) static void dns_so_closefds(struct dns_socket *so, int which) { if (DNS_SO_CLOSE_UDP & which) dns_socketclose(&so->udp, &so->opts); if (DNS_SO_CLOSE_TCP & which) dns_socketclose(&so->tcp, &so->opts); if (DNS_SO_CLOSE_OLD & which) { unsigned i; for (i = 0; i < so->onum; i++) dns_socketclose(&so->old[i], &so->opts); so->onum = 0; free(so->old); so->old = 0; so->olim = 0; } } /* dns_so_closefds() */ static void dns_so_destroy(struct dns_socket *); static struct dns_socket *levee_dns_so_init(int fd, struct dns_socket *so, const struct sockaddr *local, int type, const struct dns_options *opts, int *error) { static const struct dns_socket so_initializer = { .opts = DNS_OPTS_INITIALIZER, .udp = -1, .tcp = -1, }; *so = so_initializer; so->type = type; if (opts) so->opts = *opts; if (local) memcpy(&so->local, local, dns_sa_len(local)); if (fd != -1) so->udp = fd; else if (-1 == (so->udp = dns_socket((struct sockaddr *)&so->local, SOCK_DGRAM, error))) goto error; dns_k_permutor_init(&so->qids, 1, 65535); return so; error: dns_so_destroy(so); return 0; } /* levee_dns_so_init() */ struct dns_socket *levee_dns_so_open(int fd, const struct sockaddr *local, int type, const struct dns_options *opts, int *error) { struct dns_socket *so; if (!(so = malloc(sizeof *so))) goto syerr; if (!levee_dns_so_init(fd, so, local, type, opts, error)) goto error; return so; syerr: *error = dns_syerr(); error: dns_so_close(so); return 0; } /* levee_dns_so_open() */ struct dns_socket *dns_so_open(const struct sockaddr *local, int type, const struct dns_options *opts, int *error) { return levee_dns_so_open(-1, local, type, opts, error); } /* dns_so_open() */ static void dns_so_destroy(struct dns_socket *so) { dns_so_reset(so); dns_so_closefds(so, DNS_SO_CLOSE_ALL); } /* dns_so_destroy() */ void dns_so_close(struct dns_socket *so) { if (!so) return; dns_so_destroy(so); free(so); } /* dns_so_close() */ void dns_so_reset(struct dns_socket *so) { dns_p_setptr(&so->answer, NULL); memset(&so->state, '\0', sizeof *so - offsetof(struct dns_socket, state)); } /* dns_so_reset() */ unsigned short dns_so_mkqid(struct dns_socket *so) { return dns_k_permutor_step(&so->qids); } /* dns_so_mkqid() */ #define DNS_SO_MINBUF 768 static int dns_so_newanswer(struct dns_socket *so, size_t len) { size_t size = offsetof(struct dns_packet, data) + DNS_PP_MAX(len, DNS_SO_MINBUF); void *p; if (!(p = realloc(so->answer, size))) return dns_syerr(); so->answer = dns_p_init(p, size); return 0; } /* dns_so_newanswer() */ int dns_so_submit(struct dns_socket *so, struct dns_packet *Q, struct sockaddr *host) { struct dns_rr rr; int error = DNS_EUNKNOWN; dns_so_reset(so); if ((error = dns_rr_parse(&rr, 12, Q))) goto error; if (!(so->qlen = dns_d_expand(so->qname, sizeof so->qname, rr.dn.p, Q, &error))) goto error; /* * NOTE: Don't bail if expansion is too long; caller may be * intentionally sending long names. However, we won't be able to * verify it on return. */ so->qtype = rr.type; so->qclass = rr.class; if ((error = dns_so_newanswer(so, (Q->memo.opt.maxudp)? Q->memo.opt.maxudp : DNS_SO_MINBUF))) goto syerr; memcpy(&so->remote, host, dns_sa_len(host)); so->query = Q; so->qout = 0; dns_begin(&so->elapsed); if (dns_header(so->query)->qid == 0) dns_header(so->query)->qid = dns_so_mkqid(so); so->qid = dns_header(so->query)->qid; so->state = (so->type == SOCK_STREAM)? DNS_SO_TCP_INIT : DNS_SO_UDP_INIT; so->stat.queries++; return 0; syerr: error = dns_syerr(); error: dns_so_reset(so); return error; } /* dns_so_submit() */ static int dns_so_verify(struct dns_socket *so, struct dns_packet *P) { char qname[DNS_D_MAXNAME + 1]; size_t qlen; struct dns_rr rr; int error = -1; if (so->qid != dns_header(so->answer)->qid) goto reject; if (!dns_p_count(so->answer, DNS_S_QD)) goto reject; if (0 != dns_rr_parse(&rr, 12, so->answer)) goto reject; if (rr.type != so->qtype || rr.class != so->qclass) goto reject; if (!(qlen = dns_d_expand(qname, sizeof qname, rr.dn.p, P, &error))) goto error; else if (qlen >= sizeof qname || qlen != so->qlen) goto reject; if (0 != strcasecmp(so->qname, qname)) goto reject; return 0; reject: error = DNS_EUNKNOWN; error: DNS_SHOW(P, "rejecting packet (%s)", dns_strerror(error)); return error; } /* dns_so_verify() */ static _Bool dns_so_tcp_keep(struct dns_socket *so) { struct sockaddr_storage remote; if (so->tcp == -1) return 0; if (0 != getpeername(so->tcp, (struct sockaddr *)&remote, &(socklen_t){ sizeof remote })) return 0; return 0 == dns_sa_cmp(&remote, &so->remote); } /* dns_so_tcp_keep() */ #if defined __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warray-bounds" #endif static int dns_so_tcp_send(struct dns_socket *so) { unsigned char *qsrc; size_t qend; long n; so->query->data[-2] = 0xff & (so->query->end >> 8); so->query->data[-1] = 0xff & (so->query->end >> 0); qsrc = &so->query->data[-2] + so->qout; qend = so->query->end + 2; while (so->qout < qend) { if (0 > (n = dns_send(so->tcp, (void *)&qsrc[so->qout], qend - so->qout, 0))) return dns_soerr(); so->qout += n; so->stat.tcp.sent.bytes += n; } so->stat.tcp.sent.count++; return 0; } /* dns_so_tcp_send() */ static int dns_so_tcp_recv(struct dns_socket *so) { unsigned char *asrc; size_t aend, alen; int error; long n; aend = so->alen + 2; while (so->apos < aend) { asrc = &so->answer->data[-2]; if (0 > (n = recv(so->tcp, (void *)&asrc[so->apos], aend - so->apos, 0))) return dns_soerr(); else if (n == 0) return DNS_EUNKNOWN; /* FIXME */ so->apos += n; so->stat.tcp.rcvd.bytes += n; if (so->alen == 0 && so->apos >= 2) { alen = ((0xff & so->answer->data[-2]) << 8) | ((0xff & so->answer->data[-1]) << 0); if ((error = dns_so_newanswer(so, alen))) return error; so->alen = alen; aend = alen + 2; } } so->answer->end = so->alen; so->stat.tcp.rcvd.count++; return 0; } /* dns_so_tcp_recv() */ #if __clang__ #pragma clang diagnostic pop #endif int dns_so_check(struct dns_socket *so) { int error; long n; retry: switch (so->state) { case DNS_SO_UDP_INIT: so->state++; case DNS_SO_UDP_CONN: if (0 != connect(so->udp, (struct sockaddr *)&so->remote, dns_sa_len(&so->remote))) goto soerr; so->state++; case DNS_SO_UDP_SEND: if (0 > (n = send(so->udp, (void *)so->query->data, so->query->end, 0))) goto soerr; so->stat.udp.sent.bytes += n; so->stat.udp.sent.count++; so->state++; case DNS_SO_UDP_RECV: if (0 > (n = recv(so->udp, (void *)so->answer->data, so->answer->size, 0))) goto soerr; so->stat.udp.rcvd.bytes += n; so->stat.udp.rcvd.count++; if ((so->answer->end = n) < 12) goto trash; if ((error = dns_so_verify(so, so->answer))) goto trash; so->state++; case DNS_SO_UDP_DONE: if (!dns_header(so->answer)->tc || so->type == SOCK_DGRAM) return 0; so->state++; case DNS_SO_TCP_INIT: if (dns_so_tcp_keep(so)) { so->state = DNS_SO_TCP_SEND; goto retry; } if ((error = dns_so_closefd(so, &so->tcp))) goto error; if (-1 == (so->tcp = dns_socket((struct sockaddr *)&so->local, SOCK_STREAM, &error))) goto error; so->state++; case DNS_SO_TCP_CONN: if (0 != connect(so->tcp, (struct sockaddr *)&so->remote, dns_sa_len(&so->remote))) { if (dns_soerr() != DNS_EISCONN) goto soerr; } so->state++; case DNS_SO_TCP_SEND: if ((error = dns_so_tcp_send(so))) goto error; so->state++; case DNS_SO_TCP_RECV: if ((error = dns_so_tcp_recv(so))) goto error; so->state++; case DNS_SO_TCP_DONE: /* close unless DNS_RESCONF_TCP_ONLY (see dns_res_tcp2type) */ if (so->type != SOCK_STREAM) { if ((error = dns_so_closefd(so, &so->tcp))) goto error; } if (so->answer->end < 12) return DNS_EILLEGAL; if ((error = dns_so_verify(so, so->answer))) goto error; return 0; default: error = DNS_EUNKNOWN; goto error; } /* switch() */ trash: DNS_CARP("discarding packet"); goto retry; soerr: error = dns_soerr(); goto error; error: switch (error) { case DNS_EINTR: goto retry; case DNS_EINPROGRESS: /* FALL THROUGH */ case DNS_EALREADY: /* FALL THROUGH */ #if DNS_EWOULDBLOCK != DNS_EAGAIN case DNS_EWOULDBLOCK: /* FALL THROUGH */ #endif error = DNS_EAGAIN; break; } /* switch() */ return error; } /* dns_so_check() */ struct dns_packet *dns_so_fetch(struct dns_socket *so, int *error) { struct dns_packet *answer; switch (so->state) { case DNS_SO_UDP_DONE: case DNS_SO_TCP_DONE: answer = so->answer; so->answer = 0; return answer; default: *error = DNS_EUNKNOWN; return 0; } } /* dns_so_fetch() */ struct dns_packet *dns_so_query(struct dns_socket *so, struct dns_packet *Q, struct sockaddr *host, int *error_) { struct dns_packet *A; int error; if (!so->state) { if ((error = dns_so_submit(so, Q, host))) goto error; } if ((error = dns_so_check(so))) goto error; if (!(A = dns_so_fetch(so, &error))) goto error; dns_so_reset(so); return A; error: *error_ = error; return 0; } /* dns_so_query() */ time_t dns_so_elapsed(struct dns_socket *so) { return dns_elapsed(&so->elapsed); } /* dns_so_elapsed() */ void dns_so_clear(struct dns_socket *so) { dns_so_closefds(so, DNS_SO_CLOSE_OLD); } /* dns_so_clear() */ static int dns_so_events2(struct dns_socket *so, enum dns_events type) { int events = 0; switch (so->state) { case DNS_SO_UDP_CONN: case DNS_SO_UDP_SEND: events |= DNS_POLLOUT; break; case DNS_SO_UDP_RECV: events |= DNS_POLLIN; break; case DNS_SO_TCP_CONN: case DNS_SO_TCP_SEND: events |= DNS_POLLOUT; break; case DNS_SO_TCP_RECV: events |= DNS_POLLIN; break; } /* switch() */ switch (type) { case DNS_LIBEVENT: return DNS_POLL2EV(events); default: return events; } /* switch() */ } /* dns_so_events2() */ int dns_so_events(struct dns_socket *so) { return dns_so_events2(so, so->opts.events); } /* dns_so_events() */ int dns_so_pollfd(struct dns_socket *so) { switch (so->state) { case DNS_SO_UDP_CONN: case DNS_SO_UDP_SEND: case DNS_SO_UDP_RECV: return so->udp; case DNS_SO_TCP_CONN: case DNS_SO_TCP_SEND: case DNS_SO_TCP_RECV: return so->tcp; } /* switch() */ return -1; } /* dns_so_pollfd() */ int dns_so_poll(struct dns_socket *so, int timeout) { return dns_poll(dns_so_pollfd(so), dns_so_events2(so, DNS_SYSPOLL), timeout); } /* dns_so_poll() */ const struct dns_stat *dns_so_stat(struct dns_socket *so) { return &so->stat; } /* dns_so_stat() */ /* * R E S O L V E R R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ enum dns_res_state { DNS_R_INIT, DNS_R_GLUE, DNS_R_SWITCH, /* (B)IND, (F)ILE, (C)ACHE */ DNS_R_FILE, /* Lookup in local hosts database */ DNS_R_CACHE, /* Lookup in application cache */ DNS_R_SUBMIT, DNS_R_CHECK, DNS_R_FETCH, DNS_R_BIND, /* Lookup in the network */ DNS_R_SEARCH, DNS_R_HINTS, DNS_R_ITERATE, DNS_R_FOREACH_NS, DNS_R_RESOLV0_NS, /* Prologue: Setup next frame and recurse */ DNS_R_RESOLV1_NS, /* Epilog: Inspect answer */ DNS_R_FOREACH_A, DNS_R_QUERY_A, DNS_R_CNAME0_A, DNS_R_CNAME1_A, DNS_R_FINISH, DNS_R_SMART0_A, DNS_R_SMART1_A, DNS_R_DONE, DNS_R_SERVFAIL, }; /* enum dns_res_state */ #define DNS_R_MAXDEPTH 8 #define DNS_R_ENDFRAME (DNS_R_MAXDEPTH - 1) struct dns_resolver { struct dns_socket so; struct dns_resolv_conf *resconf; struct dns_hosts *hosts; struct dns_hints *hints; struct dns_cache *cache; dns_atomic_t refcount; /* Reset zeroes everything below here. */ char qname[DNS_D_MAXNAME + 1]; size_t qlen; enum dns_type qtype; enum dns_class qclass; struct dns_clock elapsed; dns_resconf_i_t search; struct dns_rr_i smart; struct dns_packet *nodata; /* answer if nothing better */ unsigned sp; struct dns_res_frame { enum dns_res_state state; int error; int which; /* (B)IND, (F)ILE; index into resconf->lookup */ int qflags; unsigned attempts; struct dns_packet *query, *answer, *hints; struct dns_rr_i hints_i, hints_j; struct dns_rr hints_ns, ans_cname; } stack[DNS_R_MAXDEPTH]; }; /* struct dns_resolver */ static int dns_res_tcp2type(int tcp) { switch (tcp) { case DNS_RESCONF_TCP_ONLY: return SOCK_STREAM; case DNS_RESCONF_TCP_DISABLE: return SOCK_DGRAM; default: return 0; } } /* dns_res_tcp2type() */ struct dns_resolver *levee_dns_res_open(int fd, struct dns_resolv_conf *resconf, struct dns_hosts *hosts, struct dns_hints *hints, struct dns_cache *cache, const struct dns_options *opts, int *_error) { static const struct dns_resolver R_initializer = { .refcount = 1, }; struct dns_resolver *R = 0; int type, error; /* * Grab ref count early because the caller may have passed us a mortal * reference, and we want to do the right thing if we return early * from an error. */ if (resconf) dns_resconf_acquire(resconf); if (hosts) dns_hosts_acquire(hosts); if (hints) dns_hints_acquire(hints); if (cache) dns_cache_acquire(cache); /* * Don't try to load it ourselves because a NULL object might be an * error from, say, dns_resconf_root(), and loading * dns_resconf_local() by default would create undesirable surpises. */ if (!resconf || !hosts || !hints) { if (!*_error) *_error = EINVAL; goto _error; } if (!(R = malloc(sizeof *R))) goto syerr; *R = R_initializer; type = dns_res_tcp2type(resconf->options.tcp); if (!levee_dns_so_init(fd, &R->so, (struct sockaddr *)&resconf->iface, type, opts, &error)) goto error; R->resconf = resconf; R->hosts = hosts; R->hints = hints; R->cache = cache; return R; syerr: error = dns_syerr(); error: *_error = error; _error: dns_res_close(R); dns_resconf_close(resconf); dns_hosts_close(hosts); dns_hints_close(hints); dns_cache_close(cache); return 0; } /* levee_dns_res_open */ struct dns_resolver *dns_res_open(struct dns_resolv_conf *resconf, struct dns_hosts *hosts, struct dns_hints *hints, struct dns_cache *cache, const struct dns_options *opts, int *_error) { return levee_dns_res_open(-1, resconf, hosts, hints, cache, opts, _error); } /* dns_res_open() */ struct dns_resolver *dns_res_stub(const struct dns_options *opts, int *error) { struct dns_resolv_conf *resconf = 0; struct dns_hosts *hosts = 0; struct dns_hints *hints = 0; struct dns_resolver *res = 0; if (!(resconf = dns_resconf_local(error))) goto epilog; if (!(hosts = dns_hosts_local(error))) goto epilog; if (!(hints = dns_hints_local(resconf, error))) goto epilog; if (!(res = dns_res_open(resconf, hosts, hints, NULL, opts, error))) goto epilog; epilog: dns_resconf_close(resconf); dns_hosts_close(hosts); dns_hints_close(hints); return res; } /* dns_res_stub() */ static void dns_res_frame_destroy(struct dns_resolver *R, struct dns_res_frame *frame) { (void)R; dns_p_setptr(&frame->query, NULL); dns_p_setptr(&frame->answer, NULL); dns_p_setptr(&frame->hints, NULL); } /* dns_res_frame_destroy() */ static void dns_res_frame_init(struct dns_resolver *R, struct dns_res_frame *frame) { memset(frame, '\0', sizeof *frame); /* * NB: Can be invoked from dns_res_open, before R->resconf has been * initialized. */ if (R->resconf) { if (!R->resconf->options.recurse) frame->qflags |= DNS_Q_RD; if (R->resconf->options.edns0) frame->qflags |= DNS_Q_EDNS0; } } /* dns_res_frame_init() */ static void dns_res_frame_reset(struct dns_resolver *R, struct dns_res_frame *frame) { dns_res_frame_destroy(R, frame); dns_res_frame_init(R, frame); } /* dns_res_frame_reset() */ static dns_error_t dns_res_frame_prepare(struct dns_resolver *R, struct dns_res_frame *F, const char *qname, enum dns_type qtype, enum dns_class qclass) { struct dns_packet *P = NULL; if (!(F < endof(R->stack))) return DNS_EUNKNOWN; dns_p_movptr(&P, &F->query); dns_res_frame_reset(R, F); dns_p_movptr(&F->query, &P); return dns_q_make(&F->query, qname, qtype, qclass, F->qflags); } /* dns_res_frame_prepare() */ void dns_res_reset(struct dns_resolver *R) { unsigned i; dns_so_reset(&R->so); dns_p_setptr(&R->nodata, NULL); for (i = 0; i < lengthof(R->stack); i++) dns_res_frame_destroy(R, &R->stack[i]); memset(&R->qname, '\0', sizeof *R - offsetof(struct dns_resolver, qname)); for (i = 0; i < lengthof(R->stack); i++) dns_res_frame_init(R, &R->stack[i]); } /* dns_res_reset() */ void dns_res_close(struct dns_resolver *R) { if (!R || 1 < dns_res_release(R)) return; dns_res_reset(R); dns_so_destroy(&R->so); dns_hints_close(R->hints); dns_hosts_close(R->hosts); dns_resconf_close(R->resconf); dns_cache_close(R->cache); free(R); } /* dns_res_close() */ dns_refcount_t dns_res_acquire(struct dns_resolver *R) { return dns_atomic_fetch_add(&R->refcount); } /* dns_res_acquire() */ dns_refcount_t dns_res_release(struct dns_resolver *R) { return dns_atomic_fetch_sub(&R->refcount); } /* dns_res_release() */ struct dns_resolver *dns_res_mortal(struct dns_resolver *res) { if (res) dns_res_release(res); return res; } /* dns_res_mortal() */ static struct dns_packet *dns_res_merge(struct dns_packet *P0, struct dns_packet *P1, int *error_) { size_t bufsiz = P0->end + P1->end; struct dns_packet *P[3] = { P0, P1, 0 }; struct dns_rr rr[3]; int error, copy, i; enum dns_section section; retry: if (!(P[2] = dns_p_make(bufsiz, &error))) goto error; dns_rr_foreach(&rr[0], P[0], .section = DNS_S_QD) { if ((error = dns_rr_copy(P[2], &rr[0], P[0]))) goto error; } for (section = DNS_S_AN; (DNS_S_ALL & section); section <<= 1) { for (i = 0; i < 2; i++) { dns_rr_foreach(&rr[i], P[i], .section = section) { copy = 1; dns_rr_foreach(&rr[2], P[2], .type = rr[i].type, .section = (DNS_S_ALL & ~DNS_S_QD)) { if (0 == dns_rr_cmp(&rr[i], P[i], &rr[2], P[2])) { copy = 0; break; } } if (copy && (error = dns_rr_copy(P[2], &rr[i], P[i]))) { if (error == DNS_ENOBUFS && bufsiz < 65535) { dns_p_setptr(&P[2], NULL); bufsiz = DNS_PP_MAX(65535, bufsiz * 2); goto retry; } goto error; } } /* foreach(rr) */ } /* foreach(packet) */ } /* foreach(section) */ return P[2]; error: *error_ = error; dns_p_free(P[2]); return 0; } /* dns_res_merge() */ static struct dns_packet *dns_res_glue(struct dns_resolver *R, struct dns_packet *Q) { struct dns_packet *P = dns_p_new(512); char qname[DNS_D_MAXNAME + 1]; size_t qlen; enum dns_type qtype; struct dns_rr rr; unsigned sp; int error; if (!(qlen = dns_d_expand(qname, sizeof qname, 12, Q, &error)) || qlen >= sizeof qname) return 0; if (!(qtype = dns_rr_type(12, Q))) return 0; if ((error = dns_p_push(P, DNS_S_QD, qname, strlen(qname), qtype, DNS_C_IN, 0, 0))) return 0; for (sp = 0; sp <= R->sp; sp++) { if (!R->stack[sp].answer) continue; dns_rr_foreach(&rr, R->stack[sp].answer, .name = qname, .type = qtype, .section = (DNS_S_ALL & ~DNS_S_QD)) { rr.section = DNS_S_AN; if ((error = dns_rr_copy(P, &rr, R->stack[sp].answer))) return 0; } } if (dns_p_count(P, DNS_S_AN) > 0) goto copy; /* Otherwise, look for a CNAME */ for (sp = 0; sp <= R->sp; sp++) { if (!R->stack[sp].answer) continue; dns_rr_foreach(&rr, R->stack[sp].answer, .name = qname, .type = DNS_T_CNAME, .section = (DNS_S_ALL & ~DNS_S_QD)) { rr.section = DNS_S_AN; if ((error = dns_rr_copy(P, &rr, R->stack[sp].answer))) return 0; } } if (!dns_p_count(P, DNS_S_AN)) return 0; copy: return dns_p_copy(dns_p_make(P->end, &error), P); } /* dns_res_glue() */ /* * Sort NS records by three criteria: * * 1) Whether glue is present. * 2) Whether glue record is original or of recursive lookup. * 3) Randomly shuffle records which share the above criteria. * * NOTE: Assumes only NS records passed, AND ASSUMES no new NS records will * be added during an iteration. * * FIXME: Only groks A glue, not AAAA glue. */ static int dns_res_nameserv_cmp(struct dns_rr *a, struct dns_rr *b, struct dns_rr_i *i, struct dns_packet *P) { _Bool glued[2] = { 0 }; struct dns_rr x = { 0 }, y = { 0 }; struct dns_ns ns; int cmp, error; if (!(error = dns_ns_parse(&ns, a, P))) glued[0] = !!dns_rr_grep(&x, 1, dns_rr_i_new(P, .section = (DNS_S_ALL & ~DNS_S_QD), .name = ns.host, .type = DNS_T_A), P, &error); if (!(error = dns_ns_parse(&ns, b, P))) glued[1] = !!dns_rr_grep(&y, 1, dns_rr_i_new(P, .section = (DNS_S_ALL & ~DNS_S_QD), .name = ns.host, .type = DNS_T_A), P, &error); if ((cmp = glued[1] - glued[0])) { return cmp; } else if ((cmp = (dns_rr_offset(&y) < i->args[0]) - (dns_rr_offset(&x) < i->args[0]))) { return cmp; } else { return dns_rr_i_shuffle(a, b, i, P); } } /* dns_res_nameserv_cmp() */ #define dgoto(sp, i) \ do { R->stack[(sp)].state = (i); goto exec; } while (0) static int dns_res_exec(struct dns_resolver *R) { struct dns_res_frame *F; struct dns_packet *P; union { char host[DNS_D_MAXNAME + 1]; char name[DNS_D_MAXNAME + 1]; struct dns_ns ns; struct dns_cname cname; } u; size_t len; struct dns_rr rr; int error; exec: F = &R->stack[R->sp]; switch (F->state) { case DNS_R_INIT: F->state++; case DNS_R_GLUE: if (R->sp == 0) dgoto(R->sp, DNS_R_SWITCH); if (!F->query) goto noquery; if (!(F->answer = dns_res_glue(R, F->query))) dgoto(R->sp, DNS_R_SWITCH); if (!(len = dns_d_expand(u.name, sizeof u.name, 12, F->query, &error))) goto error; else if (len >= sizeof u.name) goto toolong; dns_rr_foreach(&rr, F->answer, .name = u.name, .type = dns_rr_type(12, F->query), .section = DNS_S_AN) { dgoto(R->sp, DNS_R_FINISH); } dns_rr_foreach(&rr, F->answer, .name = u.name, .type = DNS_T_CNAME, .section = DNS_S_AN) { F->ans_cname = rr; dgoto(R->sp, DNS_R_CNAME0_A); } F->state++; case DNS_R_SWITCH: while (F->which < (int)sizeof R->resconf->lookup && R->resconf->lookup[F->which]) { switch (R->resconf->lookup[F->which++]) { case 'b': case 'B': dgoto(R->sp, DNS_R_BIND); case 'f': case 'F': dgoto(R->sp, DNS_R_FILE); case 'c': case 'C': if (R->cache) dgoto(R->sp, DNS_R_CACHE); break; default: break; } } /* * FIXME: Examine more closely whether our logic is correct * and DNS_R_SERVFAIL is the correct default response. * * Case 1: We got here because we never got an answer on the * wire. All queries timed-out and we reached maximum * attempts count. See DNS_R_FOREACH_NS. In that case * DNS_R_SERVFAIL is the correct state, unless we want to * return DNS_ETIMEDOUT. * * Case 2: We were a stub resolver and got an unsatisfactory * answer (empty ANSWER section) which caused us to jump * back to DNS_R_SEARCH and ultimately to DNS_R_SWITCH. We * return the answer returned from the wire, which we * stashed in R->nodata. * * Case 3: We reached maximum attempts count as in case #1, * but never got an authoritative response which caused us * to short-circuit. See end of DNS_R_QUERY_A case. We * should probably prepare R->nodata as in case #2. */ if (R->sp == 0 && R->nodata) { /* XXX: can we just return nodata regardless? */ dns_p_movptr(&F->answer, &R->nodata); dgoto(R->sp, DNS_R_FINISH); } dgoto(R->sp, DNS_R_SERVFAIL); case DNS_R_FILE: if (R->sp > 0) { if (!dns_p_setptr(&F->answer, dns_hosts_query(R->hosts, F->query, &error))) goto error; if (dns_p_count(F->answer, DNS_S_AN) > 0) dgoto(R->sp, DNS_R_FINISH); dns_p_setptr(&F->answer, NULL); } else { R->search = 0; while ((len = dns_resconf_search(u.name, sizeof u.name, R->qname, R->qlen, R->resconf, &R->search))) { if ((error = dns_q_make2(&F->query, u.name, len, R->qtype, R->qclass, F->qflags))) goto error; if (!dns_p_setptr(&F->answer, dns_hosts_query(R->hosts, F->query, &error))) goto error; if (dns_p_count(F->answer, DNS_S_AN) > 0) dgoto(R->sp, DNS_R_FINISH); dns_p_setptr(&F->answer, NULL); } } dgoto(R->sp, DNS_R_SWITCH); case DNS_R_CACHE: error = 0; if (!F->query && (error = dns_q_make(&F->query, R->qname, R->qtype, R->qclass, F->qflags))) goto error; if (dns_p_setptr(&F->answer, R->cache->query(F->query, R->cache, &error))) { if (dns_p_count(F->answer, DNS_S_AN) > 0) dgoto(R->sp, DNS_R_FINISH); dns_p_setptr(&F->answer, NULL); dgoto(R->sp, DNS_R_SWITCH); } else if (error) goto error; F->state++; case DNS_R_SUBMIT: if ((error = R->cache->submit(F->query, R->cache))) goto error; F->state++; case DNS_R_CHECK: if ((error = R->cache->check(R->cache))) goto error; F->state++; case DNS_R_FETCH: error = 0; if (dns_p_setptr(&F->answer, R->cache->fetch(R->cache, &error))) { if (dns_p_count(F->answer, DNS_S_AN) > 0) dgoto(R->sp, DNS_R_FINISH); dns_p_setptr(&F->answer, NULL); dgoto(R->sp, DNS_R_SWITCH); } else if (error) goto error; dgoto(R->sp, DNS_R_SWITCH); case DNS_R_BIND: if (R->sp > 0) { if (!F->query) goto noquery; dgoto(R->sp, DNS_R_HINTS); } R->search = 0; F->state++; case DNS_R_SEARCH: /* * XXX: We probably should only apply the domain search * algorithm if R->sp == 0. */ if (!(len = dns_resconf_search(u.name, sizeof u.name, R->qname, R->qlen, R->resconf, &R->search))) dgoto(R->sp, DNS_R_SWITCH); if ((error = dns_q_make2(&F->query, u.name, len, R->qtype, R->qclass, F->qflags))) goto error; F->state++; case DNS_R_HINTS: if (!dns_p_setptr(&F->hints, dns_hints_query(R->hints, F->query, &error))) goto error; F->state++; case DNS_R_ITERATE: dns_rr_i_init(&F->hints_i, F->hints); F->hints_i.section = DNS_S_AUTHORITY; F->hints_i.type = DNS_T_NS; F->hints_i.sort = &dns_res_nameserv_cmp; F->hints_i.args[0] = F->hints->end; F->state++; case DNS_R_FOREACH_NS: dns_rr_i_save(&F->hints_i); /* Load our next nameserver host. */ if (!dns_rr_grep(&F->hints_ns, 1, &F->hints_i, F->hints, &error)) { if (++F->attempts < R->resconf->options.attempts) dgoto(R->sp, DNS_R_ITERATE); dgoto(R->sp, DNS_R_SWITCH); } dns_rr_i_init(&F->hints_j, F->hints); /* Assume there are glue records */ dgoto(R->sp, DNS_R_FOREACH_A); case DNS_R_RESOLV0_NS: /* Have we reached our max depth? */ if (&F[1] >= endof(R->stack)) dgoto(R->sp, DNS_R_FOREACH_NS); if ((error = dns_ns_parse(&u.ns, &F->hints_ns, F->hints))) goto error; if ((error = dns_res_frame_prepare(R, &F[1], u.ns.host, DNS_T_A, DNS_C_IN))) goto error; F->state++; dgoto(++R->sp, DNS_R_INIT); case DNS_R_RESOLV1_NS: if (!(len = dns_d_expand(u.host, sizeof u.host, 12, F[1].query, &error))) goto error; else if (len >= sizeof u.host) goto toolong; dns_rr_foreach(&rr, F[1].answer, .name = u.host, .type = DNS_T_A, .section = (DNS_S_ALL & ~DNS_S_QD)) { rr.section = DNS_S_AR; if ((error = dns_rr_copy(F->hints, &rr, F[1].answer))) goto error; dns_rr_i_rewind(&F->hints_i); /* Now there's glue. */ } dgoto(R->sp, DNS_R_FOREACH_NS); case DNS_R_FOREACH_A: { struct dns_a a; struct sockaddr_in sin; /* * NOTE: Iterator initialized in DNS_R_FOREACH_NS because * this state is re-entrant, but we need to reset * .name to a valid pointer each time. */ if ((error = dns_ns_parse(&u.ns, &F->hints_ns, F->hints))) goto error; F->hints_j.name = u.ns.host; F->hints_j.type = DNS_T_A; F->hints_j.section = DNS_S_ALL & ~DNS_S_QD; if (!dns_rr_grep(&rr, 1, &F->hints_j, F->hints, &error)) { if (!dns_rr_i_count(&F->hints_j)) dgoto(R->sp, DNS_R_RESOLV0_NS); dgoto(R->sp, DNS_R_FOREACH_NS); } if ((error = dns_a_parse(&a, &rr, F->hints))) goto error; sin.sin_family = AF_INET; sin.sin_addr = a.addr; if (R->sp == 0) sin.sin_port = dns_hints_port(R->hints, AF_INET, &sin.sin_addr); else sin.sin_port = htons(53); if (DNS_DEBUG) { char addr[INET_ADDRSTRLEN + 1]; dns_a_print(addr, sizeof addr, &a); dns_header(F->query)->qid = dns_so_mkqid(&R->so); DNS_SHOW(F->query, "ASKING: %s/%s @ DEPTH: %u)", u.ns.host, addr, R->sp); } if ((error = dns_so_submit(&R->so, F->query, (struct sockaddr *)&sin))) goto error; F->state++; } case DNS_R_QUERY_A: if (dns_so_elapsed(&R->so) >= dns_resconf_timeout(R->resconf)) dgoto(R->sp, DNS_R_FOREACH_A); if ((error = dns_so_check(&R->so))) goto error; if (!dns_p_setptr(&F->answer, dns_so_fetch(&R->so, &error))) goto error; if (DNS_DEBUG) { DNS_SHOW(F->answer, "ANSWER @ DEPTH: %u)", R->sp); } if (dns_p_rcode(F->answer) == DNS_RC_FORMERR || dns_p_rcode(F->answer) == DNS_RC_NOTIMP || dns_p_rcode(F->answer) == DNS_RC_BADVERS) { /* Temporarily disable EDNS0 and try again. */ if (F->qflags & DNS_Q_EDNS0) { F->qflags &= ~DNS_Q_EDNS0; if ((error = dns_q_remake(&F->query, F->qflags))) goto error; dgoto(R->sp, DNS_R_FOREACH_A); } } if ((error = dns_rr_parse(&rr, 12, F->query))) goto error; if (!(len = dns_d_expand(u.name, sizeof u.name, rr.dn.p, F->query, &error))) goto error; else if (len >= sizeof u.name) goto toolong; dns_rr_foreach(&rr, F->answer, .section = DNS_S_AN, .name = u.name, .type = rr.type) { dgoto(R->sp, DNS_R_FINISH); /* Found */ } dns_rr_foreach(&rr, F->answer, .section = DNS_S_AN, .name = u.name, .type = DNS_T_CNAME) { F->ans_cname = rr; dgoto(R->sp, DNS_R_CNAME0_A); } /* * XXX: The condition here should probably check whether * R->sp == 0, because DNS_R_SEARCH runs regardless of * options.recurse. See DNS_R_BIND. */ if (!R->resconf->options.recurse) { /* Make first answer our tentative answer */ if (!R->nodata) dns_p_movptr(&R->nodata, &F->answer); dgoto(R->sp, DNS_R_SEARCH); } dns_rr_foreach(&rr, F->answer, .section = DNS_S_NS, .type = DNS_T_NS) { dns_p_movptr(&F->hints, &F->answer); dgoto(R->sp, DNS_R_ITERATE); } /* XXX: Should this go further up? */ if (dns_header(F->answer)->aa) dgoto(R->sp, DNS_R_FINISH); /* XXX: Should we copy F->answer to R->nodata? */ dgoto(R->sp, DNS_R_FOREACH_A); case DNS_R_CNAME0_A: if (&F[1] >= endof(R->stack)) dgoto(R->sp, DNS_R_FINISH); if ((error = dns_cname_parse(&u.cname, &F->ans_cname, F->answer))) goto error; if ((error = dns_res_frame_prepare(R, &F[1], u.cname.host, dns_rr_type(12, F->query), DNS_C_IN))) goto error; F->state++; dgoto(++R->sp, DNS_R_INIT); case DNS_R_CNAME1_A: if (!(P = dns_res_merge(F->answer, F[1].answer, &error))) goto error; dns_p_setptr(&F->answer, P); dgoto(R->sp, DNS_R_FINISH); case DNS_R_FINISH: if (!F->answer) goto noanswer; if (!R->resconf->options.smart || R->sp > 0) dgoto(R->sp, DNS_R_DONE); R->smart.section = DNS_S_AN; R->smart.type = R->qtype; dns_rr_i_init(&R->smart, F->answer); F->state++; case DNS_R_SMART0_A: if (&F[1] >= endof(R->stack)) dgoto(R->sp, DNS_R_DONE); while (dns_rr_grep(&rr, 1, &R->smart, F->answer, &error)) { union { struct dns_ns ns; struct dns_mx mx; struct dns_srv srv; } rd; const char *qname; enum dns_type qtype; enum dns_class qclass; switch (rr.type) { case DNS_T_NS: if ((error = dns_ns_parse(&rd.ns, &rr, F->answer))) goto error; qname = rd.ns.host; qtype = DNS_T_A; qclass = DNS_C_IN; break; case DNS_T_MX: if ((error = dns_mx_parse(&rd.mx, &rr, F->answer))) goto error; qname = rd.mx.host; qtype = DNS_T_A; qclass = DNS_C_IN; break; case DNS_T_SRV: if ((error = dns_srv_parse(&rd.srv, &rr, F->answer))) goto error; qname = rd.srv.target; qtype = DNS_T_A; qclass = DNS_C_IN; break; default: continue; } /* switch() */ if ((error = dns_res_frame_prepare(R, &F[1], qname, qtype, qclass))) goto error; F->state++; dgoto(++R->sp, DNS_R_INIT); } /* while() */ /* * NOTE: SMTP specification says to fallback to A record. * * XXX: Should we add a mock MX answer? */ if (R->qtype == DNS_T_MX && R->smart.state.count == 0) { if ((error = dns_res_frame_prepare(R, &F[1], R->qname, DNS_T_A, DNS_C_IN))) goto error; R->smart.state.count++; F->state++; dgoto(++R->sp, DNS_R_INIT); } dgoto(R->sp, DNS_R_DONE); case DNS_R_SMART1_A: if (!F[1].answer) goto noanswer; /* * FIXME: For CNAME chains (which are typically illegal in * this context), we should rewrite the record host name * to the original smart qname. All the user cares about * is locating that A/AAAA record. */ dns_rr_foreach(&rr, F[1].answer, .section = DNS_S_AN, .type = DNS_T_A) { rr.section = DNS_S_AR; if (dns_rr_exists(&rr, F[1].answer, F->answer)) continue; while ((error = dns_rr_copy(F->answer, &rr, F[1].answer))) { if (error != DNS_ENOBUFS) goto error; if ((error = dns_p_grow(&F->answer))) goto error; } } dgoto(R->sp, DNS_R_SMART0_A); case DNS_R_DONE: if (!F->answer) goto noanswer; if (R->sp > 0) dgoto(--R->sp, F[-1].state); break; case DNS_R_SERVFAIL: if (!dns_p_setptr(&F->answer, dns_p_make(DNS_P_QBUFSIZ, &error))) goto error; dns_header(F->answer)->qr = 1; dns_header(F->answer)->rcode = DNS_RC_SERVFAIL; if ((error = dns_p_push(F->answer, DNS_S_QD, R->qname, strlen(R->qname), R->qtype, R->qclass, 0, 0))) goto error; dgoto(R->sp, DNS_R_DONE); default: error = EINVAL; goto error; } /* switch () */ return 0; noquery: error = DNS_ENOQUERY; goto error; noanswer: error = DNS_ENOANSWER; goto error; toolong: error = DNS_EILLEGAL; /* FALL THROUGH */ error: return error; } /* dns_res_exec() */ #undef goto void dns_res_clear(struct dns_resolver *R) { switch (R->stack[R->sp].state) { case DNS_R_CHECK: R->cache->clear(R->cache); break; default: dns_so_clear(&R->so); break; } } /* dns_res_clear() */ static int dns_res_events2(struct dns_resolver *R, enum dns_events type) { int events; switch (R->stack[R->sp].state) { case DNS_R_CHECK: events = R->cache->events(R->cache); return (type == DNS_LIBEVENT)? DNS_POLL2EV(events) : events; default: return dns_so_events2(&R->so, type); } } /* dns_res_events2() */ int dns_res_events(struct dns_resolver *R) { return dns_res_events2(R, R->so.opts.events); } /* dns_res_events() */ int dns_res_pollfd(struct dns_resolver *R) { switch (R->stack[R->sp].state) { case DNS_R_CHECK: return R->cache->pollfd(R->cache); default: return dns_so_pollfd(&R->so); } } /* dns_res_pollfd() */ time_t dns_res_timeout(struct dns_resolver *R) { time_t elapsed; switch (R->stack[R->sp].state) { #if 0 case DNS_R_QUERY_AAAA: #endif case DNS_R_QUERY_A: elapsed = dns_so_elapsed(&R->so); if (elapsed <= dns_resconf_timeout(R->resconf)) return R->resconf->options.timeout - elapsed; break; default: break; } /* switch() */ /* * NOTE: We're not in a pollable state, or the user code hasn't * called dns_res_check properly. The calling code is probably * broken. Put them into a slow-burn pattern. */ return 1; } /* dns_res_timeout() */ time_t dns_res_elapsed(struct dns_resolver *R) { return dns_elapsed(&R->elapsed); } /* dns_res_elapsed() */ int dns_res_poll(struct dns_resolver *R, int timeout) { return dns_poll(dns_res_pollfd(R), dns_res_events2(R, DNS_SYSPOLL), timeout); } /* dns_res_poll() */ int dns_res_submit2(struct dns_resolver *R, const char *qname, size_t qlen, enum dns_type qtype, enum dns_class qclass) { dns_res_reset(R); /* Don't anchor; that can conflict with searchlist generation. */ dns_d_init(R->qname, sizeof R->qname, qname, (R->qlen = qlen), 0); R->qtype = qtype; R->qclass = qclass; dns_begin(&R->elapsed); return 0; } /* dns_res_submit2() */ int dns_res_submit(struct dns_resolver *R, const char *qname, enum dns_type qtype, enum dns_class qclass) { return dns_res_submit2(R, qname, strlen(qname), qtype, qclass); } /* dns_res_submit() */ int dns_res_check(struct dns_resolver *R) { int error; if (R->stack[0].state != DNS_R_DONE) { if ((error = dns_res_exec(R))) return error; } return 0; } /* dns_res_check() */ struct dns_packet *dns_res_fetch(struct dns_resolver *R, int *error) { struct dns_packet *P = NULL; if (R->stack[0].state != DNS_R_DONE) return *error = DNS_EUNKNOWN, (void *)0; if (!dns_p_movptr(&P, &R->stack[0].answer)) return *error = DNS_EFETCHED, (void *)0; return P; } /* dns_res_fetch() */ static struct dns_packet *dns_res_fetch_and_study(struct dns_resolver *R, int *_error) { struct dns_packet *P = NULL; int error; if (!(P = dns_res_fetch(R, &error))) goto error; if ((error = dns_p_study(P))) goto error; return P; error: *_error = error; dns_p_free(P); return NULL; } /* dns_res_fetch_and_study() */ struct dns_packet *dns_res_query(struct dns_resolver *res, const char *qname, enum dns_type qtype, enum dns_class qclass, int timeout, int *error_) { int error; if ((error = dns_res_submit(res, qname, qtype, qclass))) goto error; while ((error = dns_res_check(res))) { if (dns_res_elapsed(res) > timeout) error = DNS_ETIMEDOUT; if (error != DNS_EAGAIN) goto error; if ((error = dns_res_poll(res, 1))) goto error; } return dns_res_fetch(res, error_); error: *error_ = error; return 0; } /* dns_res_query() */ const struct dns_stat *dns_res_stat(struct dns_resolver *res) { return dns_so_stat(&res->so); } /* dns_res_stat() */ void dns_res_sethints(struct dns_resolver *res, struct dns_hints *hints) { dns_hints_acquire(hints); /* acquire first in case same hints object */ dns_hints_close(res->hints); res->hints = hints; } /* dns_res_sethints() */ /* * A D D R I N F O R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ struct dns_addrinfo { struct addrinfo hints; struct dns_resolver *res; char qname[DNS_D_MAXNAME + 1]; enum dns_type qtype; unsigned short qport, port; struct { unsigned long todo; int state; int atype; enum dns_type qtype; } af; struct dns_packet *answer; struct dns_packet *glue; struct dns_rr_i i, g; struct dns_rr rr; char cname[DNS_D_MAXNAME + 1]; char i_cname[DNS_D_MAXNAME + 1], g_cname[DNS_D_MAXNAME + 1]; int g_depth; int state; int found; struct dns_stat st; }; /* struct dns_addrinfo */ #define DNS_AI_AFMAX 32 #define DNS_AI_AF2INDEX(af) (1UL << ((af) - 1)) static inline unsigned long dns_ai_af2index(int af) { dns_static_assert(dns_same_type(unsigned long, DNS_AI_AF2INDEX(1), 1), "internal type mismatch"); dns_static_assert(dns_same_type(unsigned long, ((struct dns_addrinfo *)0)->af.todo, 1), "internal type mismatch"); return (af > 0 && af <= DNS_AI_AFMAX)? DNS_AI_AF2INDEX(af) : 0; } static int dns_ai_setaf(struct dns_addrinfo *ai, int af, int qtype) { ai->af.atype = af; ai->af.qtype = qtype; ai->af.todo &= ~dns_ai_af2index(af); return af; } /* dns_ai_setaf() */ #define DNS_SM_RESTORE \ do { pc = 0xff & (ai->af.state >> 0); i = 0xff & (ai->af.state >> 8); } while (0) #define DNS_SM_SAVE \ do { ai->af.state = ((0xff & pc) << 0) | ((0xff & i) << 8); } while (0) static int dns_ai_nextaf(struct dns_addrinfo *ai) { int i, pc; dns_static_assert(AF_UNSPEC == 0, "AF_UNSPEC constant not 0"); dns_static_assert(AF_INET <= DNS_AI_AFMAX, "AF_INET constant too large"); dns_static_assert(AF_INET6 <= DNS_AI_AFMAX, "AF_INET6 constant too large"); DNS_SM_ENTER; if (ai->res) { /* * NB: On OpenBSD, at least, the types of entries resolved * is the intersection of the /etc/resolv.conf families and * the families permitted by the .ai_type hint. So if * /etc/resolv.conf has "family inet4" and .ai_type * is AF_INET6, then the address ::1 will return 0 entries * even if AI_NUMERICHOST is specified in .ai_flags. */ while (i < (int)lengthof(ai->res->resconf->family)) { int af = ai->res->resconf->family[i++]; if (af == AF_UNSPEC) { DNS_SM_EXIT; } else if (af < 0 || af > DNS_AI_AFMAX) { continue; } else if (!(DNS_AI_AF2INDEX(af) & ai->af.todo)) { continue; } else if (af == AF_INET) { DNS_SM_YIELD(dns_ai_setaf(ai, AF_INET, DNS_T_A)); } else if (af == AF_INET6) { DNS_SM_YIELD(dns_ai_setaf(ai, AF_INET6, DNS_T_AAAA)); } } } else { /* * NB: If we get here than AI_NUMERICFLAGS should be set and * order shouldn't matter. */ if (DNS_AI_AF2INDEX(AF_INET) & ai->af.todo) DNS_SM_YIELD(dns_ai_setaf(ai, AF_INET, DNS_T_A)); if (DNS_AI_AF2INDEX(AF_INET6) & ai->af.todo) DNS_SM_YIELD(dns_ai_setaf(ai, AF_INET6, DNS_T_AAAA)); } DNS_SM_LEAVE; return dns_ai_setaf(ai, AF_UNSPEC, 0); } /* dns_ai_nextaf() */ #undef DNS_SM_RESTORE #undef DNS_SM_SAVE static enum dns_type dns_ai_qtype(struct dns_addrinfo *ai) { return (ai->qtype)? ai->qtype : ai->af.qtype; } /* dns_ai_qtype() */ static dns_error_t dns_ai_parseport(unsigned short *port, const char *serv, const struct addrinfo *hints) { const char *cp = serv; unsigned long n = 0; while (*cp >= '0' && *cp <= '9' && n < 65536) { n *= 10; n += *cp++ - '0'; } if (*cp == '\0') { if (cp == serv || n >= 65536) return DNS_ESERVICE; *port = n; return 0; } if (hints->ai_flags & AI_NUMERICSERV) return DNS_ESERVICE; /* TODO: try getaddrinfo(NULL, serv, { .ai_flags = AI_NUMERICSERV }) */ return DNS_ESERVICE; } /* dns_ai_parseport() */ struct dns_addrinfo *dns_ai_open(const char *host, const char *serv, enum dns_type qtype, const struct addrinfo *hints, struct dns_resolver *res, int *_error) { static const struct dns_addrinfo ai_initializer; struct dns_addrinfo *ai; int error; if (res) { dns_res_acquire(res); } else if (!(hints->ai_flags & AI_NUMERICHOST)) { /* * NOTE: it's assumed that *_error is set from a previous * API function call, such as dns_res_stub(). Should change * this semantic, but it's applied elsewhere, too. */ if (!*_error) *_error = EINVAL; return NULL; } if (!(ai = malloc(sizeof *ai))) goto syerr; *ai = ai_initializer; ai->hints = *hints; ai->res = res; res = NULL; if (sizeof ai->qname <= dns_strlcpy(ai->qname, host, sizeof ai->qname)) { error = ENAMETOOLONG; goto error; } ai->qtype = qtype; ai->qport = 0; if (serv && (error = dns_ai_parseport(&ai->qport, serv, hints))) goto error; ai->port = ai->qport; /* * FIXME: If an explicit A or AAAA record type conflicts with * .ai_family or with resconf.family (i.e. AAAA specified but * AF_INET6 not in interection of .ai_family and resconf.family), * then what? */ switch (ai->qtype) { case DNS_T_A: ai->af.todo = DNS_AI_AF2INDEX(AF_INET); break; case DNS_T_AAAA: ai->af.todo = DNS_AI_AF2INDEX(AF_INET6); break; default: /* 0, MX, SRV, etc */ switch (ai->hints.ai_family) { case AF_UNSPEC: ai->af.todo = DNS_AI_AF2INDEX(AF_INET) | DNS_AI_AF2INDEX(AF_INET6); break; case AF_INET: ai->af.todo = DNS_AI_AF2INDEX(AF_INET); break; case AF_INET6: ai->af.todo = DNS_AI_AF2INDEX(AF_INET6); break; default: break; } } return ai; syerr: error = dns_syerr(); error: *_error = error; dns_ai_close(ai); dns_res_close(res); return NULL; } /* dns_ai_open() */ void dns_ai_close(struct dns_addrinfo *ai) { if (!ai) return; dns_res_close(ai->res); if (ai->answer != ai->glue) dns_p_free(ai->glue); dns_p_free(ai->answer); free(ai); } /* dns_ai_close() */ static int dns_ai_setent(struct addrinfo **ent, union dns_any *any, enum dns_type type, struct dns_addrinfo *ai) { struct sockaddr *saddr; struct sockaddr_in sin; struct sockaddr_in6 sin6; const char *cname; size_t clen; switch (type) { case DNS_T_A: saddr = memset(&sin, '\0', sizeof sin); sin.sin_family = AF_INET; sin.sin_port = htons(ai->port); memcpy(&sin.sin_addr, any, sizeof sin.sin_addr); break; case DNS_T_AAAA: saddr = memset(&sin6, '\0', sizeof sin6); sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(ai->port); memcpy(&sin6.sin6_addr, any, sizeof sin6.sin6_addr); break; default: return EINVAL; } /* switch() */ if (ai->hints.ai_flags & AI_CANONNAME) { cname = (*ai->cname)? ai->cname : ai->qname; clen = strlen(cname); } else { cname = NULL; clen = 0; } if (!(*ent = malloc(sizeof **ent + dns_sa_len(saddr) + ((ai->hints.ai_flags & AI_CANONNAME)? clen + 1 : 0)))) return dns_syerr(); memset(*ent, '\0', sizeof **ent); (*ent)->ai_family = saddr->sa_family; (*ent)->ai_socktype = ai->hints.ai_socktype; (*ent)->ai_protocol = ai->hints.ai_protocol; (*ent)->ai_addr = memcpy((unsigned char *)*ent + sizeof **ent, saddr, dns_sa_len(saddr)); (*ent)->ai_addrlen = dns_sa_len(saddr); if (ai->hints.ai_flags & AI_CANONNAME) (*ent)->ai_canonname = memcpy((unsigned char *)*ent + sizeof **ent + dns_sa_len(saddr), cname, clen + 1); ai->found++; return 0; } /* dns_ai_setent() */ enum dns_ai_state { DNS_AI_S_INIT, DNS_AI_S_NEXTAF, DNS_AI_S_NUMERIC, DNS_AI_S_SUBMIT, DNS_AI_S_CHECK, DNS_AI_S_FETCH, DNS_AI_S_FOREACH_I, DNS_AI_S_INIT_G, DNS_AI_S_ITERATE_G, DNS_AI_S_FOREACH_G, DNS_AI_S_SUBMIT_G, DNS_AI_S_CHECK_G, DNS_AI_S_FETCH_G, DNS_AI_S_DONE, }; /* enum dns_ai_state */ #define dns_ai_goto(which) do { ai->state = (which); goto exec; } while (0) int dns_ai_nextent(struct addrinfo **ent, struct dns_addrinfo *ai) { struct dns_packet *ans, *glue; struct dns_rr rr; char qname[DNS_D_MAXNAME + 1]; union dns_any any; size_t qlen, clen; int error; *ent = 0; exec: switch (ai->state) { case DNS_AI_S_INIT: ai->state++; case DNS_AI_S_NEXTAF: if (!dns_ai_nextaf(ai)) dns_ai_goto(DNS_AI_S_DONE); ai->state++; case DNS_AI_S_NUMERIC: if (1 == dns_inet_pton(AF_INET, ai->qname, &any.a)) { if (ai->af.atype == AF_INET) { ai->state = DNS_AI_S_NEXTAF; return dns_ai_setent(ent, &any, DNS_T_A, ai); } else { dns_ai_goto(DNS_AI_S_NEXTAF); } } if (1 == dns_inet_pton(AF_INET6, ai->qname, &any.aaaa)) { if (ai->af.atype == AF_INET6) { ai->state = DNS_AI_S_NEXTAF; return dns_ai_setent(ent, &any, DNS_T_AAAA, ai); } else { dns_ai_goto(DNS_AI_S_NEXTAF); } } if (ai->hints.ai_flags & AI_NUMERICHOST) dns_ai_goto(DNS_AI_S_NEXTAF); ai->state++; case DNS_AI_S_SUBMIT: assert(ai->res); if ((error = dns_res_submit(ai->res, ai->qname, dns_ai_qtype(ai), DNS_C_IN))) return error; ai->state++; case DNS_AI_S_CHECK: if ((error = dns_res_check(ai->res))) return error; ai->state++; case DNS_AI_S_FETCH: if (!(ans = dns_res_fetch_and_study(ai->res, &error))) return error; if (ai->glue != ai->answer) dns_p_free(ai->glue); ai->glue = dns_p_movptr(&ai->answer, &ans); /* Search generator may have changed the qname. */ if (!(qlen = dns_d_expand(qname, sizeof qname, 12, ai->answer, &error))) return error; else if (qlen >= sizeof qname) return DNS_EILLEGAL; if (!dns_d_cname(ai->cname, sizeof ai->cname, qname, qlen, ai->answer, &error)) return error; dns_strlcpy(ai->i_cname, ai->cname, sizeof ai->i_cname); dns_rr_i_init(&ai->i, ai->answer); ai->i.section = DNS_S_AN; ai->i.name = ai->i_cname; ai->i.type = dns_ai_qtype(ai); ai->i.sort = &dns_rr_i_order; ai->state++; case DNS_AI_S_FOREACH_I: if (!dns_rr_grep(&rr, 1, &ai->i, ai->answer, &error)) dns_ai_goto(DNS_AI_S_NEXTAF); if ((error = dns_any_parse(&any, &rr, ai->answer))) return error; ai->port = ai->qport; switch (rr.type) { case DNS_T_A: case DNS_T_AAAA: return dns_ai_setent(ent, &any, rr.type, ai); default: if (!(clen = dns_any_cname(ai->cname, sizeof ai->cname, &any, rr.type))) dns_ai_goto(DNS_AI_S_FOREACH_I); /* * Find the "real" canonical name. Some authorities * publish aliases where an RFC defines a canonical * name. We trust that the resolver followed any * CNAME chains on it's own, regardless of whether * the "smart" option is enabled. */ if (!dns_d_cname(ai->cname, sizeof ai->cname, ai->cname, clen, ai->answer, &error)) return error; if (rr.type == DNS_T_SRV) ai->port = any.srv.port; break; } /* switch() */ ai->state++; case DNS_AI_S_INIT_G: ai->g_depth = 0; ai->state++; case DNS_AI_S_ITERATE_G: dns_strlcpy(ai->g_cname, ai->cname, sizeof ai->g_cname); dns_rr_i_init(&ai->g, ai->glue); ai->g.section = DNS_S_ALL & ~DNS_S_QD; ai->g.name = ai->g_cname; ai->g.type = ai->af.qtype; ai->state++; case DNS_AI_S_FOREACH_G: if (!dns_rr_grep(&rr, 1, &ai->g, ai->glue, &error)) { if (dns_rr_i_count(&ai->g) > 0) dns_ai_goto(DNS_AI_S_FOREACH_I); else dns_ai_goto(DNS_AI_S_SUBMIT_G); } if ((error = dns_any_parse(&any, &rr, ai->glue))) return error; return dns_ai_setent(ent, &any, rr.type, ai); case DNS_AI_S_SUBMIT_G: /* skip if already queried */ if (dns_rr_grep(&rr, 1, dns_rr_i_new(ai->glue, .section = DNS_S_QD, .name = ai->g.name, .type = ai->g.type), ai->glue, &error)) dns_ai_goto(DNS_AI_S_FOREACH_I); /* skip if we recursed (CNAME chains should have been handled in the resolver) */ if (++ai->g_depth > 1) dns_ai_goto(DNS_AI_S_FOREACH_I); if ((error = dns_res_submit(ai->res, ai->g.name, ai->g.type, DNS_C_IN))) return error; ai->state++; case DNS_AI_S_CHECK_G: if ((error = dns_res_check(ai->res))) return error; ai->state++; case DNS_AI_S_FETCH_G: if (!(ans = dns_res_fetch_and_study(ai->res, &error))) return error; glue = dns_p_merge(ai->glue, DNS_S_ALL, ans, DNS_S_ALL, &error); dns_p_setptr(&ans, NULL); if (!glue) return error; if (ai->glue != ai->answer) dns_p_free(ai->glue); ai->glue = glue; if (!dns_d_cname(ai->cname, sizeof ai->cname, ai->g.name, strlen(ai->g.name), ai->glue, &error)) dns_ai_goto(DNS_AI_S_FOREACH_I); dns_ai_goto(DNS_AI_S_ITERATE_G); case DNS_AI_S_DONE: if (ai->found) { return ENOENT; /* TODO: Just return 0 */ } else if (ai->answer) { switch (dns_p_rcode(ai->answer)) { case DNS_RC_NOERROR: /* FALL THROUGH */ case DNS_RC_NXDOMAIN: return DNS_ENONAME; default: return DNS_EFAIL; } } else { return DNS_EFAIL; } default: return EINVAL; } /* switch() */ } /* dns_ai_nextent() */ time_t dns_ai_elapsed(struct dns_addrinfo *ai) { return (ai->res)? dns_res_elapsed(ai->res) : 0; } /* dns_ai_elapsed() */ void dns_ai_clear(struct dns_addrinfo *ai) { if (ai->res) dns_res_clear(ai->res); } /* dns_ai_clear() */ int dns_ai_events(struct dns_addrinfo *ai) { return (ai->res)? dns_res_events(ai->res) : 0; } /* dns_ai_events() */ int dns_ai_pollfd(struct dns_addrinfo *ai) { return (ai->res)? dns_res_pollfd(ai->res) : -1; } /* dns_ai_pollfd() */ time_t dns_ai_timeout(struct dns_addrinfo *ai) { return (ai->res)? dns_res_timeout(ai->res) : 0; } /* dns_ai_timeout() */ int dns_ai_poll(struct dns_addrinfo *ai, int timeout) { return (ai->res)? dns_res_poll(ai->res, timeout) : 0; } /* dns_ai_poll() */ size_t dns_ai_print(void *_dst, size_t lim, struct addrinfo *ent, struct dns_addrinfo *ai) { struct dns_buf dst = DNS_B_INTO(_dst, lim); char addr[DNS_PP_MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1]; dns_b_puts(&dst, "[ "); dns_b_puts(&dst, ai->qname); dns_b_puts(&dst, " IN "); if (ai->qtype) { dns_b_puts(&dst, dns_strtype(ai->qtype)); } else if (ent->ai_family == AF_INET) { dns_b_puts(&dst, dns_strtype(DNS_T_A)); } else if (ent->ai_family == AF_INET6) { dns_b_puts(&dst, dns_strtype(DNS_T_AAAA)); } else { dns_b_puts(&dst, "0"); } dns_b_puts(&dst, " ]\n"); dns_b_puts(&dst, ".ai_family = "); switch (ent->ai_family) { case AF_INET: dns_b_puts(&dst, "AF_INET"); break; case AF_INET6: dns_b_puts(&dst, "AF_INET6"); break; default: dns_b_fmtju(&dst, ent->ai_family, 0); break; } dns_b_putc(&dst, '\n'); dns_b_puts(&dst, ".ai_socktype = "); switch (ent->ai_socktype) { case SOCK_STREAM: dns_b_puts(&dst, "SOCK_STREAM"); break; case SOCK_DGRAM: dns_b_puts(&dst, "SOCK_DGRAM"); break; default: dns_b_fmtju(&dst, ent->ai_socktype, 0); break; } dns_b_putc(&dst, '\n'); dns_inet_ntop(dns_sa_family(ent->ai_addr), dns_sa_addr(dns_sa_family(ent->ai_addr), ent->ai_addr, NULL), addr, sizeof addr); dns_b_puts(&dst, ".ai_addr = ["); dns_b_puts(&dst, addr); dns_b_puts(&dst, "]:"); dns_b_fmtju(&dst, ntohs(*dns_sa_port(dns_sa_family(ent->ai_addr), ent->ai_addr)), 0); dns_b_putc(&dst, '\n'); dns_b_puts(&dst, ".ai_canonname = "); dns_b_puts(&dst, (ent->ai_canonname)? ent->ai_canonname : "[NULL]"); dns_b_putc(&dst, '\n'); return dns_b_strllen(&dst); } /* dns_ai_print() */ const struct dns_stat *dns_ai_stat(struct dns_addrinfo *ai) { return (ai->res)? dns_res_stat(ai->res) : &ai->st; } /* dns_ai_stat() */ /* * M I S C E L L A N E O U S R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ static const struct { char name[16]; enum dns_section type; } dns_sections[] = { { "QUESTION", DNS_S_QUESTION }, { "QD", DNS_S_QUESTION }, { "ANSWER", DNS_S_ANSWER }, { "AN", DNS_S_ANSWER }, { "AUTHORITY", DNS_S_AUTHORITY }, { "NS", DNS_S_AUTHORITY }, { "ADDITIONAL", DNS_S_ADDITIONAL }, { "AR", DNS_S_ADDITIONAL }, }; const char *(dns_strsection)(enum dns_section section, void *_dst, size_t lim) { struct dns_buf dst = DNS_B_INTO(_dst, lim); unsigned i; for (i = 0; i < lengthof(dns_sections); i++) { if (dns_sections[i].type & section) { dns_b_puts(&dst, dns_sections[i].name); section &= ~dns_sections[i].type; if (section) dns_b_putc(&dst, '|'); } } if (section || dst.p == dst.base) dns_b_fmtju(&dst, (0xffff & section), 0); return dns_b_tostring(&dst); } /* dns_strsection() */ enum dns_section dns_isection(const char *src) { enum dns_section section = 0; char sbuf[128]; char *name, *next; unsigned i; dns_strlcpy(sbuf, src, sizeof sbuf); next = sbuf; while ((name = dns_strsep(&next, "|+, \t"))) { for (i = 0; i < lengthof(dns_sections); i++) { if (!strcasecmp(dns_sections[i].name, name)) { section |= dns_sections[i].type; break; } } } return section; } /* dns_isection() */ static const struct { char name[8]; enum dns_class type; } dns_classes[] = { { "IN", DNS_C_IN }, }; const char *(dns_strclass)(enum dns_class type, void *_dst, size_t lim) { struct dns_buf dst = DNS_B_INTO(_dst, lim); unsigned i; for (i = 0; i < lengthof(dns_classes); i++) { if (dns_classes[i].type == type) { dns_b_puts(&dst, dns_classes[i].name); break; } } if (dst.p == dst.base) dns_b_fmtju(&dst, (0xffff & type), 0); return dns_b_tostring(&dst); } /* dns_strclass() */ enum dns_class dns_iclass(const char *name) { unsigned i, class; for (i = 0; i < lengthof(dns_classes); i++) { if (!strcasecmp(dns_classes[i].name, name)) return dns_classes[i].type; } class = 0; while (dns_isdigit(*name)) { class *= 10; class += *name++ - '0'; } return DNS_PP_MIN(class, 0xffff); } /* dns_iclass() */ const char *(dns_strtype)(enum dns_type type, void *_dst, size_t lim) { struct dns_buf dst = DNS_B_INTO(_dst, lim); unsigned i; for (i = 0; i < lengthof(dns_rrtypes); i++) { if (dns_rrtypes[i].type == type) { dns_b_puts(&dst, dns_rrtypes[i].name); break; } } if (dst.p == dst.base) dns_b_fmtju(&dst, (0xffff & type), 0); return dns_b_tostring(&dst); } /* dns_strtype() */ enum dns_type dns_itype(const char *name) { unsigned i, type; for (i = 0; i < lengthof(dns_rrtypes); i++) { if (!strcasecmp(dns_rrtypes[i].name, name)) return dns_rrtypes[i].type; } type = 0; while (dns_isdigit(*name)) { type *= 10; type += *name++ - '0'; } return DNS_PP_MIN(type, 0xffff); } /* dns_itype() */ static char dns_opcodes[16][16] = { [DNS_OP_QUERY] = "QUERY", [DNS_OP_IQUERY] = "IQUERY", [DNS_OP_STATUS] = "STATUS", [DNS_OP_NOTIFY] = "NOTIFY", [DNS_OP_UPDATE] = "UPDATE", }; static const char *dns__strcode(int code, volatile char *dst, size_t lim) { char _tmp[48] = ""; struct dns_buf tmp; size_t p; assert(lim > 0); dns_b_fmtju(dns_b_into(&tmp, _tmp, DNS_PP_MIN(sizeof _tmp, lim - 1)), code, 0); /* copy downwards so first byte is copied last (see below) */ p = (size_t)(tmp.p - tmp.base); dst[p] = '\0'; while (p--) dst[p] = _tmp[p]; return (const char *)dst; } const char *dns_stropcode(enum dns_opcode opcode) { opcode = (unsigned)opcode % lengthof(dns_opcodes); if ('\0' == dns_opcodes[opcode][0]) return dns__strcode(opcode, dns_opcodes[opcode], sizeof dns_opcodes[opcode]); return dns_opcodes[opcode]; } /* dns_stropcode() */ enum dns_opcode dns_iopcode(const char *name) { unsigned opcode; for (opcode = 0; opcode < lengthof(dns_opcodes); opcode++) { if (!strcasecmp(name, dns_opcodes[opcode])) return opcode; } opcode = 0; while (dns_isdigit(*name)) { opcode *= 10; opcode += *name++ - '0'; } return DNS_PP_MIN(opcode, 0x0f); } /* dns_iopcode() */ static char dns_rcodes[32][16] = { [DNS_RC_NOERROR] = "NOERROR", [DNS_RC_FORMERR] = "FORMERR", [DNS_RC_SERVFAIL] = "SERVFAIL", [DNS_RC_NXDOMAIN] = "NXDOMAIN", [DNS_RC_NOTIMP] = "NOTIMP", [DNS_RC_REFUSED] = "REFUSED", [DNS_RC_YXDOMAIN] = "YXDOMAIN", [DNS_RC_YXRRSET] = "YXRRSET", [DNS_RC_NXRRSET] = "NXRRSET", [DNS_RC_NOTAUTH] = "NOTAUTH", [DNS_RC_NOTZONE] = "NOTZONE", /* EDNS(0) extended RCODEs ... */ [DNS_RC_BADVERS] = "BADVERS", }; const char *dns_strrcode(enum dns_rcode rcode) { rcode = (unsigned)rcode % lengthof(dns_rcodes); if ('\0' == dns_rcodes[rcode][0]) return dns__strcode(rcode, dns_rcodes[rcode], sizeof dns_rcodes[rcode]); return dns_rcodes[rcode]; } /* dns_strrcode() */ enum dns_rcode dns_ircode(const char *name) { unsigned rcode; for (rcode = 0; rcode < lengthof(dns_rcodes); rcode++) { if (!strcasecmp(name, dns_rcodes[rcode])) return rcode; } rcode = 0; while (dns_isdigit(*name)) { rcode *= 10; rcode += *name++ - '0'; } return DNS_PP_MIN(rcode, 0xfff); } /* dns_ircode() */ /* * C O M M A N D - L I N E / R E G R E S S I O N R O U T I N E S * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #if DNS_MAIN #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #if _WIN32 #include <getopt.h> #endif #if !_WIN32 #include <err.h> #endif struct { struct { const char *path[8]; unsigned count; } resconf, nssconf, hosts, cache; const char *qname; enum dns_type qtype; int (*sort)(); int verbose; } MAIN = { .sort = &dns_rr_i_packet, }; static void hexdump(const unsigned char *src, size_t len, FILE *fp) { static const unsigned char hex[] = "0123456789abcdef"; static const unsigned char tmpl[] = " | |\n"; unsigned char ln[sizeof tmpl]; const unsigned char *sp, *se; unsigned char *h, *g; unsigned i, n; sp = src; se = sp + len; while (sp < se) { memcpy(ln, tmpl, sizeof ln); h = &ln[2]; g = &ln[53]; for (n = 0; n < 2; n++) { for (i = 0; i < 8 && se - sp > 0; i++, sp++) { h[0] = hex[0x0f & (*sp >> 4)]; h[1] = hex[0x0f & (*sp >> 0)]; h += 3; *g++ = (isgraph(*sp))? *sp : '.'; } h++; } fputs((char *)ln, fp); } return /* void */; } /* hexdump() */ DNS_NORETURN static void panic(const char *fmt, ...) { va_list ap; va_start(ap, fmt); #if _WIN32 vfprintf(stderr, fmt, ap); exit(EXIT_FAILURE); #else verrx(EXIT_FAILURE, fmt, ap); #endif } /* panic() */ #define panic_(fn, ln, fmt, ...) \ panic(fmt "%0s", (fn), (ln), __VA_ARGS__) #define panic(...) \ panic_(__func__, __LINE__, "(%s:%d) " __VA_ARGS__, "") static void *grow(unsigned char *p, size_t size) { void *tmp; if (!(tmp = realloc(p, size))) panic("realloc(%"PRIuZ"): %s", size, dns_strerror(errno)); return tmp; } /* grow() */ static size_t add(size_t a, size_t b) { if (~a < b) panic("%"PRIuZ" + %"PRIuZ": integer overflow", a, b); return a + b; } /* add() */ static size_t append(unsigned char **dst, size_t osize, const void *src, size_t len) { size_t size = add(osize, len); *dst = grow(*dst, size); memcpy(*dst + osize, src, len); return size; } /* append() */ static size_t slurp(unsigned char **dst, size_t osize, FILE *fp, const char *path) { size_t size = osize; unsigned char buf[1024]; size_t count; while ((count = fread(buf, 1, sizeof buf, fp))) size = append(dst, size, buf, count); if (ferror(fp)) panic("%s: %s", path, dns_strerror(errno)); return size; } /* slurp() */ static struct dns_resolv_conf *resconf(void) { static struct dns_resolv_conf *resconf; const char *path; unsigned i; int error; if (resconf) return resconf; if (!(resconf = dns_resconf_open(&error))) panic("dns_resconf_open: %s", dns_strerror(error)); if (!MAIN.resconf.count) MAIN.resconf.path[MAIN.resconf.count++] = "/etc/resolv.conf"; for (i = 0; i < MAIN.resconf.count; i++) { path = MAIN.resconf.path[i]; if (0 == strcmp(path, "-")) error = dns_resconf_loadfile(resconf, stdin); else error = dns_resconf_loadpath(resconf, path); if (error) panic("%s: %s", path, dns_strerror(error)); } for (i = 0; i < MAIN.nssconf.count; i++) { path = MAIN.nssconf.path[i]; if (0 == strcmp(path, "-")) error = dns_nssconf_loadfile(resconf, stdin); else error = dns_nssconf_loadpath(resconf, path); if (error) panic("%s: %s", path, dns_strerror(error)); } if (!MAIN.nssconf.count) { path = "/etc/nsswitch.conf"; if (!(error = dns_nssconf_loadpath(resconf, path))) MAIN.nssconf.path[MAIN.nssconf.count++] = path; else if (error != ENOENT) panic("%s: %s", path, dns_strerror(error)); } return resconf; } /* resconf() */ static struct dns_hosts *hosts(void) { static struct dns_hosts *hosts; const char *path; unsigned i; int error; if (hosts) return hosts; if (!MAIN.hosts.count) { MAIN.hosts.path[MAIN.hosts.count++] = "/etc/hosts"; /* Explicitly test dns_hosts_local() */ if (!(hosts = dns_hosts_local(&error))) panic("%s: %s", "/etc/hosts", dns_strerror(error)); return hosts; } if (!(hosts = dns_hosts_open(&error))) panic("dns_hosts_open: %s", dns_strerror(error)); for (i = 0; i < MAIN.hosts.count; i++) { path = MAIN.hosts.path[i]; if (0 == strcmp(path, "-")) error = dns_hosts_loadfile(hosts, stdin); else error = dns_hosts_loadpath(hosts, path); if (error) panic("%s: %s", path, dns_strerror(error)); } return hosts; } /* hosts() */ #if DNS_CACHE #include "cache.h" static struct dns_cache *cache(void) { static struct cache *cache; const char *path; unsigned i; int error; if (cache) return cache_resi(cache); if (!MAIN.cache.count) return NULL; if (!(cache = cache_open(&error))) panic("%s: %s", MAIN.cache.path[0], dns_strerror(error)); for (i = 0; i < MAIN.cache.count; i++) { path = MAIN.cache.path[i]; if (!strcmp(path, "-")) { if ((error = cache_loadfile(cache, stdin, NULL, 0))) panic("%s: %s", path, dns_strerror(error)); } else if ((error = cache_loadpath(cache, path, NULL, 0))) panic("%s: %s", path, dns_strerror(error)); } return cache_resi(cache); } /* cache() */ #else static struct dns_cache *cache(void) { return NULL; } #endif static void print_packet(struct dns_packet *P, FILE *fp) { dns_p_dump3(P, dns_rr_i_new(P, .sort = MAIN.sort), fp); if (MAIN.verbose > 2) hexdump(P->data, P->end, fp); } /* print_packet() */ static int parse_packet(int argc DNS_NOTUSED, char *argv[] DNS_NOTUSED) { struct dns_packet *P = dns_p_new(512); struct dns_packet *Q = dns_p_new(512); enum dns_section section; struct dns_rr rr; int error; union dns_any any; char pretty[sizeof any * 2]; size_t len; P->end = fread(P->data, 1, P->size, stdin); fputs(";; [HEADER]\n", stdout); fprintf(stdout, ";; qr : %s(%d)\n", (dns_header(P)->qr)? "RESPONSE" : "QUERY", dns_header(P)->qr); fprintf(stdout, ";; opcode : %s(%d)\n", dns_stropcode(dns_header(P)->opcode), dns_header(P)->opcode); fprintf(stdout, ";; aa : %s(%d)\n", (dns_header(P)->aa)? "AUTHORITATIVE" : "NON-AUTHORITATIVE", dns_header(P)->aa); fprintf(stdout, ";; tc : %s(%d)\n", (dns_header(P)->tc)? "TRUNCATED" : "NOT-TRUNCATED", dns_header(P)->tc); fprintf(stdout, ";; rd : %s(%d)\n", (dns_header(P)->rd)? "RECURSION-DESIRED" : "RECURSION-NOT-DESIRED", dns_header(P)->rd); fprintf(stdout, ";; ra : %s(%d)\n", (dns_header(P)->ra)? "RECURSION-ALLOWED" : "RECURSION-NOT-ALLOWED", dns_header(P)->ra); fprintf(stdout, ";; rcode : %s(%d)\n", dns_strrcode(dns_p_rcode(P)), dns_p_rcode(P)); section = 0; dns_rr_foreach(&rr, P, .sort = MAIN.sort) { if (section != rr.section) fprintf(stdout, "\n;; [%s:%d]\n", dns_strsection(rr.section), dns_p_count(P, rr.section)); if ((len = dns_rr_print(pretty, sizeof pretty, &rr, P, &error))) fprintf(stdout, "%s\n", pretty); dns_rr_copy(Q, &rr, P); section = rr.section; } fputs("; ; ; ; ; ; ; ;\n\n", stdout); section = 0; #if 0 dns_rr_foreach(&rr, Q, .name = "ns8.yahoo.com.") { #else struct dns_rr rrset[32]; struct dns_rr_i *rri = dns_rr_i_new(Q, .name = dns_d_new("ns8.yahoo.com", DNS_D_ANCHOR), .sort = MAIN.sort); unsigned rrcount = dns_rr_grep(rrset, lengthof(rrset), rri, Q, &error); for (unsigned i = 0; i < rrcount; i++) { rr = rrset[i]; #endif if (section != rr.section) fprintf(stdout, "\n;; [%s:%d]\n", dns_strsection(rr.section), dns_p_count(Q, rr.section)); if ((len = dns_rr_print(pretty, sizeof pretty, &rr, Q, &error))) fprintf(stdout, "%s\n", pretty); section = rr.section; } if (MAIN.verbose > 1) { fprintf(stderr, "orig:%"PRIuZ"\n", P->end); hexdump(P->data, P->end, stdout); fprintf(stderr, "copy:%"PRIuZ"\n", Q->end); hexdump(Q->data, Q->end, stdout); } return 0; } /* parse_packet() */ static int parse_domain(int argc, char *argv[]) { char *dn; dn = (argc > 1)? argv[1] : "f.l.google.com"; printf("[%s]\n", dn); dn = dns_d_new(dn); do { puts(dn); } while (dns_d_cleave(dn, strlen(dn) + 1, dn, strlen(dn))); return 0; } /* parse_domain() */ static int trim_domain(int argc, char **argv) { for (argc--, argv++; argc > 0; argc--, argv++) { char name[DNS_D_MAXNAME + 1]; dns_d_trim(name, sizeof name, *argv, strlen(*argv), DNS_D_ANCHOR); puts(name); } return 0; } /* trim_domain() */ static int expand_domain(int argc, char *argv[]) { unsigned short rp = 0; unsigned char *src = NULL; unsigned char *dst; struct dns_packet *pkt; size_t lim = 0, len; int error; if (argc > 1) rp = atoi(argv[1]); len = slurp(&src, 0, stdin, "-"); if (!(pkt = dns_p_make(len, &error))) panic("malloc(%"PRIuZ"): %s", len, dns_strerror(error)); memcpy(pkt->data, src, len); pkt->end = len; lim = 1; dst = grow(NULL, lim); while (lim <= (len = dns_d_expand(dst, lim, rp, pkt, &error))) { lim = add(len, 1); dst = grow(dst, lim); } if (!len) panic("expand: %s", dns_strerror(error)); fwrite(dst, 1, len, stdout); fflush(stdout); free(src); free(dst); free(pkt); return 0; } /* expand_domain() */ static int show_resconf(int argc DNS_NOTUSED, char *argv[] DNS_NOTUSED) { unsigned i; resconf(); /* load it */ fputs("; SOURCES\n", stdout); for (i = 0; i < MAIN.resconf.count; i++) fprintf(stdout, "; %s\n", MAIN.resconf.path[i]); for (i = 0; i < MAIN.nssconf.count; i++) fprintf(stdout, "; %s\n", MAIN.nssconf.path[i]); fputs(";\n", stdout); dns_resconf_dump(resconf(), stdout); return 0; } /* show_resconf() */ static int show_nssconf(int argc DNS_NOTUSED, char *argv[] DNS_NOTUSED) { unsigned i; resconf(); fputs("# SOURCES\n", stdout); for (i = 0; i < MAIN.resconf.count; i++) fprintf(stdout, "# %s\n", MAIN.resconf.path[i]); for (i = 0; i < MAIN.nssconf.count; i++) fprintf(stdout, "# %s\n", MAIN.nssconf.path[i]); fputs("#\n", stdout); dns_nssconf_dump(resconf(), stdout); return 0; } /* show_nssconf() */ static int show_hosts(int argc DNS_NOTUSED, char *argv[] DNS_NOTUSED) { unsigned i; hosts(); fputs("# SOURCES\n", stdout); for (i = 0; i < MAIN.hosts.count; i++) fprintf(stdout, "# %s\n", MAIN.hosts.path[i]); fputs("#\n", stdout); dns_hosts_dump(hosts(), stdout); return 0; } /* show_hosts() */ static int query_hosts(int argc, char *argv[]) { struct dns_packet *Q = dns_p_new(512); struct dns_packet *A; char qname[DNS_D_MAXNAME + 1]; size_t qlen; int error; if (!MAIN.qname) MAIN.qname = (argc > 1)? argv[1] : "localhost"; if (!MAIN.qtype) MAIN.qtype = DNS_T_A; hosts(); if (MAIN.qtype == DNS_T_PTR && !strstr(MAIN.qname, "arpa")) { union { struct in_addr a; struct in6_addr a6; } addr; int af = (strchr(MAIN.qname, ':'))? AF_INET6 : AF_INET; if ((error = dns_pton(af, MAIN.qname, &addr))) panic("%s: %s", MAIN.qname, dns_strerror(error)); qlen = dns_ptr_qname(qname, sizeof qname, af, &addr); } else qlen = dns_strlcpy(qname, MAIN.qname, sizeof qname); if ((error = dns_p_push(Q, DNS_S_QD, qname, qlen, MAIN.qtype, DNS_C_IN, 0, 0))) panic("%s: %s", qname, dns_strerror(error)); if (!(A = dns_hosts_query(hosts(), Q, &error))) panic("%s: %s", qname, dns_strerror(error)); print_packet(A, stdout); free(A); return 0; } /* query_hosts() */ static int search_list(int argc, char *argv[]) { const char *qname = (argc > 1)? argv[1] : "f.l.google.com"; unsigned long i = 0; char name[DNS_D_MAXNAME + 1]; printf("[%s]\n", qname); while (dns_resconf_search(name, sizeof name, qname, strlen(qname), resconf(), &i)) puts(name); return 0; } /* search_list() */ static int permute_set(int argc, char *argv[]) { unsigned lo, hi, i; struct dns_k_permutor p; hi = (--argc > 0)? atoi(argv[argc]) : 8; lo = (--argc > 0)? atoi(argv[argc]) : 0; fprintf(stderr, "[%u .. %u]\n", lo, hi); dns_k_permutor_init(&p, lo, hi); for (i = lo; i <= hi; i++) fprintf(stdout, "%u\n", dns_k_permutor_step(&p)); // printf("%u -> %u -> %u\n", i, dns_k_permutor_E(&p, i), dns_k_permutor_D(&p, dns_k_permutor_E(&p, i))); return 0; } /* permute_set() */ static int shuffle_16(int argc, char *argv[]) { unsigned n, r; if (--argc > 0) { n = 0xffff & atoi(argv[argc]); r = (--argc > 0)? (unsigned)atoi(argv[argc]) : dns_random(); fprintf(stdout, "%hu\n", dns_k_shuffle16(n, r)); } else { r = dns_random(); for (n = 0; n < 65536; n++) fprintf(stdout, "%hu\n", dns_k_shuffle16(n, r)); } return 0; } /* shuffle_16() */ static int dump_random(int argc, char *argv[]) { unsigned char b[32]; unsigned i, j, n, r; n = (argc > 1)? atoi(argv[1]) : 32; while (n) { i = 0; do { r = dns_random(); for (j = 0; j < sizeof r && i < n && i < sizeof b; i++, j++) { b[i] = 0xff & r; r >>= 8; } } while (i < n && i < sizeof b); hexdump(b, i, stdout); n -= i; } return 0; } /* dump_random() */ static int send_query(int argc, char *argv[]) { struct dns_packet *A, *Q = dns_p_new(512); char host[INET6_ADDRSTRLEN + 1]; struct sockaddr_storage ss; struct dns_socket *so; int error, type; if (argc > 1) { ss.ss_family = (strchr(argv[1], ':'))? AF_INET6 : AF_INET; if ((error = dns_pton(ss.ss_family, argv[1], dns_sa_addr(ss.ss_family, &ss, NULL)))) panic("%s: %s", argv[1], dns_strerror(error)); *dns_sa_port(ss.ss_family, &ss) = htons(53); } else memcpy(&ss, &resconf()->nameserver[0], dns_sa_len(&resconf()->nameserver[0])); if (!dns_inet_ntop(ss.ss_family, dns_sa_addr(ss.ss_family, &ss, NULL), host, sizeof host)) panic("bad host address, or none provided"); if (!MAIN.qname) MAIN.qname = "ipv6.google.com"; if (!MAIN.qtype) MAIN.qtype = DNS_T_AAAA; if ((error = dns_p_push(Q, DNS_S_QD, MAIN.qname, strlen(MAIN.qname), MAIN.qtype, DNS_C_IN, 0, 0))) panic("dns_p_push: %s", dns_strerror(error)); dns_header(Q)->rd = 1; if (strstr(argv[0], "udp")) type = SOCK_DGRAM; else if (strstr(argv[0], "tcp")) type = SOCK_STREAM; else type = dns_res_tcp2type(resconf()->options.tcp); fprintf(stderr, "querying %s for %s IN %s\n", host, MAIN.qname, dns_strtype(MAIN.qtype)); if (!(so = dns_so_open((struct sockaddr *)&resconf()->iface, type, dns_opts(), &error))) panic("dns_so_open: %s", dns_strerror(error)); while (!(A = dns_so_query(so, Q, (struct sockaddr *)&ss, &error))) { if (error != DNS_EAGAIN) panic("dns_so_query: %s (%d)", dns_strerror(error), error); if (dns_so_elapsed(so) > 10) panic("query timed-out"); dns_so_poll(so, 1); } print_packet(A, stdout); dns_so_close(so); return 0; } /* send_query() */ static int print_arpa(int argc, char *argv[]) { const char *ip = (argc > 1)? argv[1] : "::1"; int af = (strchr(ip, ':'))? AF_INET6 : AF_INET; union { struct in_addr a4; struct in6_addr a6; } addr; char host[DNS_D_MAXNAME + 1]; if (1 != dns_inet_pton(af, ip, &addr) || 0 == dns_ptr_qname(host, sizeof host, af, &addr)) panic("%s: invalid address", ip); fprintf(stdout, "%s\n", host); return 0; } /* print_arpa() */ static int show_hints(int argc, char *argv[]) { struct dns_hints *(*load)(struct dns_resolv_conf *, int *); const char *which, *how, *who; struct dns_hints *hints; int error; which = (argc > 1)? argv[1] : "local"; how = (argc > 2)? argv[2] : "plain"; who = (argc > 3)? argv[3] : "google.com"; load = (0 == strcmp(which, "local")) ? &dns_hints_local : &dns_hints_root; if (!(hints = load(resconf(), &error))) panic("%s: %s", argv[0], dns_strerror(error)); if (0 == strcmp(how, "plain")) { dns_hints_dump(hints, stdout); } else { struct dns_packet *query, *answer; query = dns_p_new(512); if ((error = dns_p_push(query, DNS_S_QUESTION, who, strlen(who), DNS_T_A, DNS_C_IN, 0, 0))) panic("%s: %s", who, dns_strerror(error)); if (!(answer = dns_hints_query(hints, query, &error))) panic("%s: %s", who, dns_strerror(error)); print_packet(answer, stdout); free(answer); } dns_hints_close(hints); return 0; } /* show_hints() */ static int resolve_query(int argc DNS_NOTUSED, char *argv[]) { _Bool recurse = !!strstr(argv[0], "recurse"); struct dns_hints *(*hints)() = (recurse)? &dns_hints_root : &dns_hints_local; struct dns_resolver *R; struct dns_packet *ans; const struct dns_stat *st; int error; if (!MAIN.qname) MAIN.qname = "www.google.com"; if (!MAIN.qtype) MAIN.qtype = DNS_T_A; resconf()->options.recurse = recurse; if (!(R = dns_res_open(resconf(), hosts(), dns_hints_mortal(hints(resconf(), &error)), cache(), dns_opts(), &error))) panic("%s: %s", MAIN.qname, dns_strerror(error)); if ((error = dns_res_submit(R, MAIN.qname, MAIN.qtype, DNS_C_IN))) panic("%s: %s", MAIN.qname, dns_strerror(error)); while ((error = dns_res_check(R))) { if (error != DNS_EAGAIN) panic("dns_res_check: %s (%d)", dns_strerror(error), error); if (dns_res_elapsed(R) > 30) panic("query timed-out"); dns_res_poll(R, 1); } ans = dns_res_fetch(R, &error); print_packet(ans, stdout); free(ans); st = dns_res_stat(R); putchar('\n'); printf(";; queries: %"PRIuZ"\n", st->queries); printf(";; udp sent: %"PRIuZ" in %"PRIuZ" bytes\n", st->udp.sent.count, st->udp.sent.bytes); printf(";; udp rcvd: %"PRIuZ" in %"PRIuZ" bytes\n", st->udp.rcvd.count, st->udp.rcvd.bytes); printf(";; tcp sent: %"PRIuZ" in %"PRIuZ" bytes\n", st->tcp.sent.count, st->tcp.sent.bytes); printf(";; tcp rcvd: %"PRIuZ" in %"PRIuZ" bytes\n", st->tcp.rcvd.count, st->tcp.rcvd.bytes); dns_res_close(R); return 0; } /* resolve_query() */ static int resolve_addrinfo(int argc DNS_NOTUSED, char *argv[]) { _Bool recurse = !!strstr(argv[0], "recurse"); struct dns_hints *(*hints)() = (recurse)? &dns_hints_root : &dns_hints_local; struct dns_resolver *res = NULL; struct dns_addrinfo *ai = NULL; struct addrinfo ai_hints = { .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_flags = AI_CANONNAME }; struct addrinfo *ent; char pretty[512]; int error; if (!MAIN.qname) MAIN.qname = "www.google.com"; /* NB: MAIN.qtype of 0 means obey hints.ai_family */ resconf()->options.recurse = recurse; if (!(res = dns_res_open(resconf(), hosts(), dns_hints_mortal(hints(resconf(), &error)), cache(), dns_opts(), &error))) panic("%s: %s", MAIN.qname, dns_strerror(error)); if (!(ai = dns_ai_open(MAIN.qname, "80", MAIN.qtype, &ai_hints, res, &error))) panic("%s: %s", MAIN.qname, dns_strerror(error)); do { switch (error = dns_ai_nextent(&ent, ai)) { case 0: dns_ai_print(pretty, sizeof pretty, ent, ai); fputs(pretty, stdout); free(ent); break; case ENOENT: break; case DNS_EAGAIN: if (dns_ai_elapsed(ai) > 30) panic("query timed-out"); dns_ai_poll(ai, 1); break; default: panic("dns_ai_nextent: %s (%d)", dns_strerror(error), error); } } while (error != ENOENT); dns_res_close(res); dns_ai_close(ai); return 0; } /* resolve_addrinfo() */ static int echo_port(int argc DNS_NOTUSED, char *argv[] DNS_NOTUSED) { union { struct sockaddr sa; struct sockaddr_in sin; } port; int fd; memset(&port, 0, sizeof port); port.sin.sin_family = AF_INET; port.sin.sin_port = htons(5354); port.sin.sin_addr.s_addr = inet_addr("127.0.0.1"); if (-1 == (fd = socket(PF_INET, SOCK_DGRAM, 0))) panic("socket: %s", strerror(errno)); if (0 != bind(fd, &port.sa, sizeof port.sa)) panic("127.0.0.1:5353: %s", dns_strerror(errno)); for (;;) { struct dns_packet *pkt = dns_p_new(512); struct sockaddr_storage ss; socklen_t slen = sizeof ss; ssize_t count; #if defined(MSG_WAITALL) /* MinGW issue */ int rflags = MSG_WAITALL; #else int rflags = 0; #endif count = recvfrom(fd, (char *)pkt->data, pkt->size, rflags, (struct sockaddr *)&ss, &slen); if (!count || count < 0) panic("recvfrom: %s", strerror(errno)); pkt->end = count; dns_p_dump(pkt, stdout); (void)sendto(fd, (char *)pkt->data, pkt->end, 0, (struct sockaddr *)&ss, slen); } return 0; } /* echo_port() */ static int isection(int argc, char *argv[]) { const char *name = (argc > 1)? argv[1] : ""; int type; type = dns_isection(name); name = dns_strsection(type); printf("%s (%d)\n", name, type); return 0; } /* isection() */ static int iclass(int argc, char *argv[]) { const char *name = (argc > 1)? argv[1] : ""; int type; type = dns_iclass(name); name = dns_strclass(type); printf("%s (%d)\n", name, type); return 0; } /* iclass() */ static int itype(int argc, char *argv[]) { const char *name = (argc > 1)? argv[1] : ""; int type; type = dns_itype(name); name = dns_strtype(type); printf("%s (%d)\n", name, type); return 0; } /* itype() */ static int iopcode(int argc, char *argv[]) { const char *name = (argc > 1)? argv[1] : ""; int type; type = dns_iopcode(name); name = dns_stropcode(type); printf("%s (%d)\n", name, type); return 0; } /* iopcode() */ static int ircode(int argc, char *argv[]) { const char *name = (argc > 1)? argv[1] : ""; int type; type = dns_ircode(name); name = dns_strrcode(type); printf("%s (%d)\n", name, type); return 0; } /* ircode() */ #define SIZE1(x) { DNS_PP_STRINGIFY(x), sizeof (x) } #define SIZE2(x, ...) SIZE1(x), SIZE1(__VA_ARGS__) #define SIZE3(x, ...) SIZE1(x), SIZE2(__VA_ARGS__) #define SIZE4(x, ...) SIZE1(x), SIZE3(__VA_ARGS__) #define SIZE(...) DNS_PP_CALL(DNS_PP_XPASTE(SIZE, DNS_PP_NARG(__VA_ARGS__)), __VA_ARGS__) static int sizes(int argc DNS_NOTUSED, char *argv[] DNS_NOTUSED) { static const struct { const char *name; size_t size; } type[] = { SIZE(struct dns_header, struct dns_packet, struct dns_rr, struct dns_rr_i), SIZE(struct dns_a, struct dns_aaaa, struct dns_mx, struct dns_ns), SIZE(struct dns_cname, struct dns_soa, struct dns_ptr, struct dns_srv), SIZE(struct dns_sshfp, struct dns_txt, union dns_any), SIZE(struct dns_resolv_conf, struct dns_hosts, struct dns_hints, struct dns_hints_i), SIZE(struct dns_options, struct dns_socket, struct dns_resolver, struct dns_addrinfo), SIZE(struct dns_cache), SIZE(size_t), SIZE(void *), SIZE(long) }; unsigned i, max; for (i = 0, max = 0; i < lengthof(type); i++) max = DNS_PP_MAX(max, strlen(type[i].name)); for (i = 0; i < lengthof(type); i++) printf("%*s : %"PRIuZ"\n", max, type[i].name, type[i].size); return 0; } /* sizes() */ static const struct { const char *cmd; int (*run)(); const char *help; } cmds[] = { { "parse-packet", &parse_packet, "parse binary packet from stdin" }, { "parse-domain", &parse_domain, "anchor and iteratively cleave domain" }, { "trim-domain", &trim_domain, "trim and anchor domain name" }, { "expand-domain", &expand_domain, "expand domain at offset NN in packet from stdin" }, { "show-resconf", &show_resconf, "show resolv.conf data" }, { "show-hosts", &show_hosts, "show hosts data" }, { "show-nssconf", &show_nssconf, "show nsswitch.conf data" }, { "query-hosts", &query_hosts, "query A, AAAA or PTR in hosts data" }, { "search-list", &search_list, "generate query search list from domain" }, { "permute-set", &permute_set, "generate random permutation -> (0 .. N or N .. M)" }, { "shuffle-16", &shuffle_16, "simple 16-bit permutation" }, { "dump-random", &dump_random, "generate random bytes" }, { "send-query", &send_query, "send query to host" }, { "send-query-udp", &send_query, "send udp query to host" }, { "send-query-tcp", &send_query, "send tcp query to host" }, { "print-arpa", &print_arpa, "print arpa. zone name of address" }, { "show-hints", &show_hints, "print hints: show-hints [local|root] [plain|packet]" }, { "resolve-stub", &resolve_query, "resolve as stub resolver" }, { "resolve-recurse", &resolve_query, "resolve as recursive resolver" }, { "addrinfo-stub", &resolve_addrinfo, "resolve through getaddrinfo clone" }, { "addrinfo-recurse", &resolve_addrinfo, "resolve through getaddrinfo clone" }, /* { "resolve-nameinfo", &resolve_query, "resolve as recursive resolver" }, */ { "echo", &echo_port, "server echo mode, for nmap fuzzing" }, { "isection", &isection, "parse section string" }, { "iclass", &iclass, "parse class string" }, { "itype", &itype, "parse type string" }, { "iopcode", &iopcode, "parse opcode string" }, { "ircode", &ircode, "parse rcode string" }, { "sizes", &sizes, "print data structure sizes" }, }; static void print_usage(const char *progname, FILE *fp) { static const char *usage = " [OPTIONS] COMMAND [ARGS]\n" " -c PATH Path to resolv.conf\n" " -n PATH Path to nsswitch.conf\n" " -l PATH Path to local hosts\n" " -z PATH Path to zone cache\n" " -q QNAME Query name\n" " -t QTYPE Query type\n" " -s HOW Sort records\n" " -v Be more verbose (-vv show packets; -vvv hexdump packets)\n" " -V Print version info\n" " -h Print this usage message\n" "\n"; unsigned i, n, m; fputs(progname, fp); fputs(usage, fp); for (i = 0, m = 0; i < lengthof(cmds); i++) { if (strlen(cmds[i].cmd) > m) m = strlen(cmds[i].cmd); } for (i = 0; i < lengthof(cmds); i++) { fprintf(fp, " %s ", cmds[i].cmd); for (n = strlen(cmds[i].cmd); n < m; n++) putc(' ', fp); fputs(cmds[i].help, fp); putc('\n', fp); } fputs("\nReport bugs to William Ahern <william@25thandClement.com>\n", fp); } /* print_usage() */ static void print_version(const char *progname, FILE *fp) { fprintf(fp, "%s (dns.c) %.8X\n", progname, dns_v_rel()); fprintf(fp, "vendor %s\n", dns_vendor()); fprintf(fp, "release %.8X\n", dns_v_rel()); fprintf(fp, "abi %.8X\n", dns_v_abi()); fprintf(fp, "api %.8X\n", dns_v_api()); } /* print_version() */ int main(int argc, char **argv) { extern int optind; extern char *optarg; const char *progname = argv[0]; unsigned i; int ch; while (-1 != (ch = getopt(argc, argv, "q:t:c:n:l:z:s:vVh"))) { switch (ch) { case 'c': assert(MAIN.resconf.count < lengthof(MAIN.resconf.path)); MAIN.resconf.path[MAIN.resconf.count++] = optarg; break; case 'n': assert(MAIN.nssconf.count < lengthof(MAIN.nssconf.path)); MAIN.nssconf.path[MAIN.nssconf.count++] = optarg; break; case 'l': assert(MAIN.hosts.count < lengthof(MAIN.hosts.path)); MAIN.hosts.path[MAIN.hosts.count++] = optarg; break; case 'z': assert(MAIN.cache.count < lengthof(MAIN.cache.path)); MAIN.cache.path[MAIN.cache.count++] = optarg; break; case 'q': MAIN.qname = optarg; break; case 't': for (i = 0; i < lengthof(dns_rrtypes); i++) { if (0 == strcasecmp(dns_rrtypes[i].name, optarg)) { MAIN.qtype = dns_rrtypes[i].type; break; } } if (MAIN.qtype) break; for (i = 0; dns_isdigit(optarg[i]); i++) { MAIN.qtype *= 10; MAIN.qtype += optarg[i] - '0'; } if (!MAIN.qtype) panic("%s: invalid query type", optarg); break; case 's': if (0 == strcasecmp(optarg, "packet")) MAIN.sort = &dns_rr_i_packet; else if (0 == strcasecmp(optarg, "shuffle")) MAIN.sort = &dns_rr_i_shuffle; else if (0 == strcasecmp(optarg, "order")) MAIN.sort = &dns_rr_i_order; else panic("%s: invalid sort method", optarg); break; case 'v': dns_debug = ++MAIN.verbose; break; case 'V': print_version(progname, stdout); return 0; case 'h': print_usage(progname, stdout); return 0; default: print_usage(progname, stderr); return EXIT_FAILURE; } /* switch() */ } /* while() */ argc -= optind; argv += optind; for (i = 0; i < lengthof(cmds) && argv[0]; i++) { if (0 == strcmp(cmds[i].cmd, argv[0])) return cmds[i].run(argc, argv); } print_usage(progname, stderr); return EXIT_FAILURE; } /* main() */ #endif /* DNS_MAIN */ /* * pop file-scoped compiler annotations */ #if __clang__ #pragma clang diagnostic pop #elif DNS_GNUC_PREREQ(4,6,0) #pragma GCC diagnostic pop #endif
22.786626
202
0.628728
[ "object" ]
e783e11f77f3e5b95523cdc08824d8070bdb7fc7
1,640
h
C
src/builtins/builtins-constructor.h
radimkohout/v8-new
f6dc1d17efcc695a6f2dd7bcc50c0c6321747613
[ "BSD-3-Clause" ]
16
2017-08-24T14:53:25.000Z
2021-08-19T04:49:23.000Z
src/builtins/builtins-constructor.h
Acidburn0zzz/v8-1
0dd6885de60fdba36532e068a31693c870d8b50b
[ "BSD-3-Clause" ]
2
2019-03-22T11:02:32.000Z
2019-04-05T19:03:41.000Z
src/builtins/builtins-constructor.h
Acidburn0zzz/v8-1
0dd6885de60fdba36532e068a31693c870d8b50b
[ "BSD-3-Clause" ]
10
2017-09-21T07:40:42.000Z
2020-03-31T05:53:42.000Z
// Copyright 2016 the V8 project 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 V8_BUILTINS_BUILTINS_CONSTRUCTOR_H_ #define V8_BUILTINS_BUILTINS_CONSTRUCTOR_H_ #include "src/contexts.h" #include "src/objects.h" #include "src/objects/dictionary.h" namespace v8 { namespace internal { class ConstructorBuiltins { public: static int MaximumFunctionContextSlots() { return FLAG_test_small_max_function_context_stub_size ? kSmallMaximumSlots : kMaximumSlots; } // Maximum number of elements in copied array (chosen so that even an array // backed by a double backing store will fit into new-space). static const int kMaximumClonedShallowArrayElements = JSArray::kInitialMaxFastElementArray * kPointerSize / kDoubleSize; // Maximum number of properties in copied object so that the properties store // will fit into new-space. This constant is based on the assumption that // NameDictionaries are 50% over-allocated. static const int kMaximumClonedShallowObjectProperties = NameDictionary::kMaxRegularCapacity / 3 * 2; private: static const int kMaximumSlots = 0x8000; static const int kSmallMaximumSlots = 10; // FastNewFunctionContext can only allocate closures which fit in the // new space. STATIC_ASSERT(((kMaximumSlots + Context::MIN_CONTEXT_SLOTS) * kPointerSize + FixedArray::kHeaderSize) < kMaxRegularHeapObjectSize); }; } // namespace internal } // namespace v8 #endif // V8_BUILTINS_BUILTINS_CONSTRUCTOR_H_
35.652174
79
0.741463
[ "object" ]
e7861b6391e7ad68c86ccc1ae7050b83f6ed91da
24,072
c
C
test/machine/Z80/Z80.c
andydansby/z88dk-mk2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
1
2020-09-15T08:35:49.000Z
2020-09-15T08:35:49.000Z
test/machine/Z80/Z80.c
andydansby/z88dk-MK2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
null
null
null
test/machine/Z80/Z80.c
andydansby/z88dk-MK2
51c15f1387293809c496f5eaf7b196f8a0e9b66b
[ "ClArtistic" ]
null
null
null
/** Z80: portable Z80 emulator *******************************/ /** **/ /** Z80.c **/ /** **/ /** This file contains implementation for Z80 CPU. Don't **/ /** forget to provide RdZ80(), WrZ80(), InZ80(), OutZ80(), **/ /** LoopZ80(), and PatchZ80() functions to accomodate the **/ /** emulated machine's architecture. **/ /** **/ /** Copyright (C) Marat Fayzullin 1994-2007 **/ /** You are not allowed to distribute this software **/ /** commercially. Please, notify me, if you make any **/ /** changes to this file. **/ /*************************************************************/ #include "Z80.h" #include "Tables.h" #include <stdio.h> /** INLINE ***************************************************/ /** C99 standard has "inline", but older compilers used **/ /** __inline for the same purpose. **/ /*************************************************************/ #ifdef __C99__ #define INLINE inline #else #define INLINE __inline #endif /** System-Dependent Stuff ***********************************/ /** This is system-dependent code put here to speed things **/ /** up. It has to stay inlined to be fast. **/ /*************************************************************/ #ifdef COLEM #define RdZ80 RDZ80 extern byte *ROMPage[]; INLINE byte RdZ80(word A) { return(ROMPage[A>>13][A&0x1FFF]); } #endif #ifdef SPECCY #define RdZ80 RDZ80 #define WrZ80 WRZ80 extern byte *Page[],*ROM; INLINE byte RdZ80(word A) { return(Page[A>>13][A&0x1FFF]); } INLINE void WrZ80(word A,byte V) { if(Page[A>>13]<ROM) Page[A>>13][A&0x1FFF]=V; } #endif #ifdef Z88DK extern byte RAM[65536]; INLINE byte RdZ80Dbg(word A) { return(RAM[A]); } INLINE void WrZ80Dbg(word A, byte V) { RAM[A] = V; } #ifndef RCMX000 /** If we don't have the rabbit I/O handler we don't need to separate Debug readings from real (cpu) memory reading */ INLINE byte RdZ80(word A) { return(RAM[A]); } INLINE void WrZ80(word A, byte V) { RAM[A] = V; } #define InZ80(a) (0xFF) #define OutZ80(a,v) #else /** This is set by the ioi instruction so following mem access goes to io instead */ static int ioi_flag=0; static int ioe_flag=0; /** This is a read, either from I/O or memory */ INLINE byte RdZ80(word A) { if (ioi_flag || ioe_flag) { if (ioi_flag) { ioi_flag=0; return rcmx_io_internal_in(A); } if (ioe_flag) { ioe_flag=0; return rcmx_io_external_in(A); } } return(RAM[A]); } /** This is a write, either to I/O or memory */ INLINE void WrZ80(word A, byte V) { if (ioi_flag || ioe_flag) { if (ioi_flag) { ioi_flag=0; rcmx_io_internal_out(A, V); } if (ioe_flag) { ioe_flag=0; rcmx_io_external_out(A, V); } return; } RAM[A] = V; } #endif #endif #ifdef MG #define RdZ80 RDZ80 extern byte *Page[]; INLINE byte RdZ80(word A) { return(Page[A>>13][A&0x1FFF]); } #endif #ifdef FMSX #define FAST_RDOP extern byte *RAM[]; INLINE byte OpZ80(word A) { return(RAM[A>>13][A&0x1FFF]); } #endif /** FAST_RDOP ************************************************/ /** With this #define not present, RdZ80() should perform **/ /** the functions of OpZ80(). **/ /*************************************************************/ #ifndef FAST_RDOP #ifdef RCMX000 /** We need this in order to not reset the ioi / ioe flags * when fetching instructions */ INLINE byte OpZ80(word A) { return RAM[A]; } #else #define OpZ80(A) RdZ80(A) #endif #endif #define S(Fl) R->AF.B.l|=Fl #define R(Fl) R->AF.B.l&=~(Fl) #define FLAGS(Rg,Fl) R->AF.B.l=Fl|ZSTable[Rg] #define M_RLC(Rg) \ R->AF.B.l=Rg>>7;Rg=(Rg<<1)|R->AF.B.l;R->AF.B.l|=PZSTable[Rg] #define M_RRC(Rg) \ R->AF.B.l=Rg&0x01;Rg=(Rg>>1)|(R->AF.B.l<<7);R->AF.B.l|=PZSTable[Rg] #define M_RL(Rg) \ if(Rg&0x80) \ { \ Rg=(Rg<<1)|(R->AF.B.l&C_FLAG); \ R->AF.B.l=PZSTable[Rg]|C_FLAG; \ } \ else \ { \ Rg=(Rg<<1)|(R->AF.B.l&C_FLAG); \ R->AF.B.l=PZSTable[Rg]; \ } #define M_RR(Rg) \ if(Rg&0x01) \ { \ Rg=(Rg>>1)|(R->AF.B.l<<7); \ R->AF.B.l=PZSTable[Rg]|C_FLAG; \ } \ else \ { \ Rg=(Rg>>1)|(R->AF.B.l<<7); \ R->AF.B.l=PZSTable[Rg]; \ } #define M_SLA(Rg) \ R->AF.B.l=Rg>>7;Rg<<=1;R->AF.B.l|=PZSTable[Rg] #define M_SRA(Rg) \ R->AF.B.l=Rg&C_FLAG;Rg=(Rg>>1)|(Rg&0x80);R->AF.B.l|=PZSTable[Rg] #define M_SLL(Rg) \ R->AF.B.l=Rg>>7;Rg=(Rg<<1)|0x01;R->AF.B.l|=PZSTable[Rg] #define M_SRL(Rg) \ R->AF.B.l=Rg&0x01;Rg>>=1;R->AF.B.l|=PZSTable[Rg] #define M_BIT(Bit,Rg) \ R->AF.B.l=(R->AF.B.l&C_FLAG)|H_FLAG|PZSTable[Rg&(1<<Bit)] #define M_SET(Bit,Rg) Rg|=1<<Bit #define M_RES(Bit,Rg) Rg&=~(1<<Bit) #define M_POP(Rg) \ R->Rg.B.l=OpZ80(R->SP.W++);R->Rg.B.h=OpZ80(R->SP.W++) #define M_PUSH(Rg) \ WrZ80(--R->SP.W,R->Rg.B.h);WrZ80(--R->SP.W,R->Rg.B.l) #define M_CALL \ J.B.l=OpZ80(R->PC.W++);J.B.h=OpZ80(R->PC.W++); \ WrZ80(--R->SP.W,R->PC.B.h);WrZ80(--R->SP.W,R->PC.B.l); \ R->PC.W=J.W; \ JumpZ80(J.W) #define M_JP J.B.l=OpZ80(R->PC.W++);J.B.h=OpZ80(R->PC.W);R->PC.W=J.W;JumpZ80(J.W) #define M_JR R->PC.W+=(offset)OpZ80(R->PC.W)+1;JumpZ80(R->PC.W) #define M_RET R->PC.B.l=OpZ80(R->SP.W++);R->PC.B.h=OpZ80(R->SP.W++);JumpZ80(R->PC.W) #define M_RST(Ad) \ WrZ80(--R->SP.W,R->PC.B.h);WrZ80(--R->SP.W,R->PC.B.l);R->PC.W=Ad;JumpZ80(Ad) #define M_LDWORD(Rg) \ R->Rg.B.l=OpZ80(R->PC.W++);R->Rg.B.h=OpZ80(R->PC.W++) #define M_ADD(Rg) \ J.W=R->AF.B.h+Rg; \ R->AF.B.l= \ (~(R->AF.B.h^Rg)&(Rg^J.B.l)&0x80? V_FLAG:0)| \ J.B.h|ZSTable[J.B.l]| \ ((R->AF.B.h^Rg^J.B.l)&H_FLAG); \ R->AF.B.h=J.B.l #define M_SUB(Rg) \ J.W=R->AF.B.h-Rg; \ R->AF.B.l= \ ((R->AF.B.h^Rg)&(R->AF.B.h^J.B.l)&0x80? V_FLAG:0)| \ N_FLAG|-J.B.h|ZSTable[J.B.l]| \ ((R->AF.B.h^Rg^J.B.l)&H_FLAG); \ R->AF.B.h=J.B.l #define M_ADC(Rg) \ J.W=R->AF.B.h+Rg+(R->AF.B.l&C_FLAG); \ R->AF.B.l= \ (~(R->AF.B.h^Rg)&(Rg^J.B.l)&0x80? V_FLAG:0)| \ J.B.h|ZSTable[J.B.l]| \ ((R->AF.B.h^Rg^J.B.l)&H_FLAG); \ R->AF.B.h=J.B.l #define M_SBC(Rg) \ J.W=R->AF.B.h-Rg-(R->AF.B.l&C_FLAG); \ R->AF.B.l= \ ((R->AF.B.h^Rg)&(R->AF.B.h^J.B.l)&0x80? V_FLAG:0)| \ N_FLAG|-J.B.h|ZSTable[J.B.l]| \ ((R->AF.B.h^Rg^J.B.l)&H_FLAG); \ R->AF.B.h=J.B.l #define M_CP(Rg) \ J.W=R->AF.B.h-Rg; \ R->AF.B.l= \ ((R->AF.B.h^Rg)&(R->AF.B.h^J.B.l)&0x80? V_FLAG:0)| \ N_FLAG|-J.B.h|ZSTable[J.B.l]| \ ((R->AF.B.h^Rg^J.B.l)&H_FLAG) #define M_AND(Rg) R->AF.B.h&=Rg;R->AF.B.l=H_FLAG|PZSTable[R->AF.B.h] #define M_OR(Rg) R->AF.B.h|=Rg;R->AF.B.l=PZSTable[R->AF.B.h] #define M_XOR(Rg) R->AF.B.h^=Rg;R->AF.B.l=PZSTable[R->AF.B.h] #define M_IN(Rg) \ Rg=InZ80(R->BC.W); \ R->AF.B.l=PZSTable[Rg]|(R->AF.B.l&C_FLAG) #define M_INC(Rg) \ Rg++; \ R->AF.B.l= \ (R->AF.B.l&C_FLAG)|ZSTable[Rg]| \ (Rg==0x80? V_FLAG:0)|(Rg&0x0F? 0:H_FLAG) #define M_DEC(Rg) \ Rg--; \ R->AF.B.l= \ N_FLAG|(R->AF.B.l&C_FLAG)|ZSTable[Rg]| \ (Rg==0x7F? V_FLAG:0)|((Rg&0x0F)==0x0F? H_FLAG:0) #define M_ADDW(Rg1,Rg2) \ J.W=(R->Rg1.W+R->Rg2.W)&0xFFFF; \ R->AF.B.l= \ (R->AF.B.l&~(H_FLAG|N_FLAG|C_FLAG))| \ ((R->Rg1.W^R->Rg2.W^J.W)&0x1000? H_FLAG:0)| \ (((long)R->Rg1.W+(long)R->Rg2.W)&0x10000? C_FLAG:0); \ R->Rg1.W=J.W #define M_ADCW(Rg) \ I=R->AF.B.l&C_FLAG;J.W=(R->HL.W+R->Rg.W+I)&0xFFFF; \ R->AF.B.l= \ (((long)R->HL.W+(long)R->Rg.W+(long)I)&0x10000? C_FLAG:0)| \ (~(R->HL.W^R->Rg.W)&(R->Rg.W^J.W)&0x8000? V_FLAG:0)| \ ((R->HL.W^R->Rg.W^J.W)&0x1000? H_FLAG:0)| \ (J.W? 0:Z_FLAG)|(J.B.h&S_FLAG); \ R->HL.W=J.W #define M_SBCW(Rg) \ I=R->AF.B.l&C_FLAG;J.W=(R->HL.W-R->Rg.W-I)&0xFFFF; \ R->AF.B.l= \ N_FLAG| \ (((long)R->HL.W-(long)R->Rg.W-(long)I)&0x10000? C_FLAG:0)| \ ((R->HL.W^R->Rg.W)&(R->HL.W^J.W)&0x8000? V_FLAG:0)| \ ((R->HL.W^R->Rg.W^J.W)&0x1000? H_FLAG:0)| \ (J.W? 0:Z_FLAG)|(J.B.h&S_FLAG); \ R->HL.W=J.W enum Codes { NOP,LD_BC_WORD,LD_xBC_A,INC_BC,INC_B,DEC_B,LD_B_BYTE,RLCA, EX_AF_AF,ADD_HL_BC,LD_A_xBC,DEC_BC,INC_C,DEC_C,LD_C_BYTE,RRCA, DJNZ,LD_DE_WORD,LD_xDE_A,INC_DE,INC_D,DEC_D,LD_D_BYTE,RLA, JR,ADD_HL_DE,LD_A_xDE,DEC_DE,INC_E,DEC_E,LD_E_BYTE,RRA, JR_NZ,LD_HL_WORD,LD_xWORD_HL,INC_HL,INC_H,DEC_H,LD_H_BYTE,DAA, JR_Z,ADD_HL_HL,LD_HL_xWORD,DEC_HL,INC_L,DEC_L,LD_L_BYTE,CPL, JR_NC,LD_SP_WORD,LD_xWORD_A,INC_SP,INC_xHL,DEC_xHL,LD_xHL_BYTE,SCF, JR_C,ADD_HL_SP,LD_A_xWORD,DEC_SP,INC_A,DEC_A,LD_A_BYTE,CCF, LD_B_B,LD_B_C,LD_B_D,LD_B_E,LD_B_H,LD_B_L,LD_B_xHL,LD_B_A, LD_C_B,LD_C_C,LD_C_D,LD_C_E,LD_C_H,LD_C_L,LD_C_xHL,LD_C_A, LD_D_B,LD_D_C,LD_D_D,LD_D_E,LD_D_H,LD_D_L,LD_D_xHL,LD_D_A, LD_E_B,LD_E_C,LD_E_D,LD_E_E,LD_E_H,LD_E_L,LD_E_xHL,LD_E_A, LD_H_B,LD_H_C,LD_H_D,LD_H_E,LD_H_H,LD_H_L,LD_H_xHL,LD_H_A, LD_L_B,LD_L_C,LD_L_D,LD_L_E,LD_L_H,LD_L_L,LD_L_xHL,LD_L_A, LD_xHL_B,LD_xHL_C,LD_xHL_D,LD_xHL_E,LD_xHL_H,LD_xHL_L,HALT,LD_xHL_A, LD_A_B,LD_A_C,LD_A_D,LD_A_E,LD_A_H,LD_A_L,LD_A_xHL,LD_A_A, ADD_B,ADD_C,ADD_D,ADD_E,ADD_H,ADD_L,ADD_xHL,ADD_A, ADC_B,ADC_C,ADC_D,ADC_E,ADC_H,ADC_L,ADC_xHL,ADC_A, SUB_B,SUB_C,SUB_D,SUB_E,SUB_H,SUB_L,SUB_xHL,SUB_A, SBC_B,SBC_C,SBC_D,SBC_E,SBC_H,SBC_L,SBC_xHL,SBC_A, AND_B,AND_C,AND_D,AND_E,AND_H,AND_L,AND_xHL,AND_A, XOR_B,XOR_C,XOR_D,XOR_E,XOR_H,XOR_L,XOR_xHL,XOR_A, OR_B,OR_C,OR_D,OR_E,OR_H,OR_L,OR_xHL,OR_A, CP_B,CP_C,CP_D,CP_E,CP_H,CP_L,CP_xHL,CP_A, RET_NZ,POP_BC,JP_NZ,JP,CALL_NZ,PUSH_BC,ADD_BYTE,RST00, RET_Z,RET,JP_Z,PFX_CB,CALL_Z,CALL,ADC_BYTE,RST08, RET_NC,POP_DE,JP_NC, #ifdef RCMX000 IOI, #else OUTA, #endif CALL_NC,PUSH_DE,SUB_BYTE,RST10, RET_C,EXX,JP_C, #ifdef RCMX000 IOE, #else INA, #endif CALL_C,PFX_DD,SBC_BYTE,RST18, RET_PO,POP_HL,JP_PO,EX_HL_xSP,CALL_PO,PUSH_HL,AND_BYTE,RST20, RET_PE,LD_PC_HL,JP_PE,EX_DE_HL,CALL_PE,PFX_ED,XOR_BYTE,RST28, RET_P,POP_AF,JP_P,DI,CALL_P,PUSH_AF,OR_BYTE,RST30, RET_M,LD_SP_HL,JP_M,EI,CALL_M,PFX_FD,CP_BYTE,RST38 }; enum CodesCB { RLC_B,RLC_C,RLC_D,RLC_E,RLC_H,RLC_L,RLC_xHL,RLC_A, RRC_B,RRC_C,RRC_D,RRC_E,RRC_H,RRC_L,RRC_xHL,RRC_A, RL_B,RL_C,RL_D,RL_E,RL_H,RL_L,RL_xHL,RL_A, RR_B,RR_C,RR_D,RR_E,RR_H,RR_L,RR_xHL,RR_A, SLA_B,SLA_C,SLA_D,SLA_E,SLA_H,SLA_L,SLA_xHL,SLA_A, SRA_B,SRA_C,SRA_D,SRA_E,SRA_H,SRA_L,SRA_xHL,SRA_A, SLL_B,SLL_C,SLL_D,SLL_E,SLL_H,SLL_L,SLL_xHL,SLL_A, SRL_B,SRL_C,SRL_D,SRL_E,SRL_H,SRL_L,SRL_xHL,SRL_A, BIT0_B,BIT0_C,BIT0_D,BIT0_E,BIT0_H,BIT0_L,BIT0_xHL,BIT0_A, BIT1_B,BIT1_C,BIT1_D,BIT1_E,BIT1_H,BIT1_L,BIT1_xHL,BIT1_A, BIT2_B,BIT2_C,BIT2_D,BIT2_E,BIT2_H,BIT2_L,BIT2_xHL,BIT2_A, BIT3_B,BIT3_C,BIT3_D,BIT3_E,BIT3_H,BIT3_L,BIT3_xHL,BIT3_A, BIT4_B,BIT4_C,BIT4_D,BIT4_E,BIT4_H,BIT4_L,BIT4_xHL,BIT4_A, BIT5_B,BIT5_C,BIT5_D,BIT5_E,BIT5_H,BIT5_L,BIT5_xHL,BIT5_A, BIT6_B,BIT6_C,BIT6_D,BIT6_E,BIT6_H,BIT6_L,BIT6_xHL,BIT6_A, BIT7_B,BIT7_C,BIT7_D,BIT7_E,BIT7_H,BIT7_L,BIT7_xHL,BIT7_A, RES0_B,RES0_C,RES0_D,RES0_E,RES0_H,RES0_L,RES0_xHL,RES0_A, RES1_B,RES1_C,RES1_D,RES1_E,RES1_H,RES1_L,RES1_xHL,RES1_A, RES2_B,RES2_C,RES2_D,RES2_E,RES2_H,RES2_L,RES2_xHL,RES2_A, RES3_B,RES3_C,RES3_D,RES3_E,RES3_H,RES3_L,RES3_xHL,RES3_A, RES4_B,RES4_C,RES4_D,RES4_E,RES4_H,RES4_L,RES4_xHL,RES4_A, RES5_B,RES5_C,RES5_D,RES5_E,RES5_H,RES5_L,RES5_xHL,RES5_A, RES6_B,RES6_C,RES6_D,RES6_E,RES6_H,RES6_L,RES6_xHL,RES6_A, RES7_B,RES7_C,RES7_D,RES7_E,RES7_H,RES7_L,RES7_xHL,RES7_A, SET0_B,SET0_C,SET0_D,SET0_E,SET0_H,SET0_L,SET0_xHL,SET0_A, SET1_B,SET1_C,SET1_D,SET1_E,SET1_H,SET1_L,SET1_xHL,SET1_A, SET2_B,SET2_C,SET2_D,SET2_E,SET2_H,SET2_L,SET2_xHL,SET2_A, SET3_B,SET3_C,SET3_D,SET3_E,SET3_H,SET3_L,SET3_xHL,SET3_A, SET4_B,SET4_C,SET4_D,SET4_E,SET4_H,SET4_L,SET4_xHL,SET4_A, SET5_B,SET5_C,SET5_D,SET5_E,SET5_H,SET5_L,SET5_xHL,SET5_A, SET6_B,SET6_C,SET6_D,SET6_E,SET6_H,SET6_L,SET6_xHL,SET6_A, SET7_B,SET7_C,SET7_D,SET7_E,SET7_H,SET7_L,SET7_xHL,SET7_A }; enum CodesED { DB_00,DB_01,DB_02,DB_03,DB_04,DB_05,DB_06,DB_07, DB_08,DB_09,DB_0A,DB_0B,DB_0C,DB_0D,DB_0E,DB_0F, DB_10,DB_11,DB_12,DB_13,DB_14,DB_15,DB_16,DB_17, DB_18,DB_19,DB_1A,DB_1B,DB_1C,DB_1D,DB_1E,DB_1F, DB_20,DB_21,DB_22,DB_23,DB_24,DB_25,DB_26,DB_27, DB_28,DB_29,DB_2A,DB_2B,DB_2C,DB_2D,DB_2E,DB_2F, DB_30,DB_31,DB_32,DB_33,DB_34,DB_35,DB_36,DB_37, DB_38,DB_39,DB_3A,DB_3B,DB_3C,DB_3D,DB_3E,DB_3F, IN_B_xC,OUT_xC_B,SBC_HL_BC,LD_xWORDe_BC,NEG,RETN,IM_0,LD_I_A, IN_C_xC,OUT_xC_C,ADC_HL_BC,LD_BC_xWORDe,DB_4C,RETI,DB_,LD_R_A, IN_D_xC,OUT_xC_D,SBC_HL_DE,LD_xWORDe_DE, #ifdef RCMX000 EX_HL_SPx, #else DB_54, #endif DB_55,IM_1,LD_A_I, IN_E_xC,OUT_xC_E,ADC_HL_DE,LD_DE_xWORDe,DB_5C,DB_5D,IM_2,LD_A_R, IN_H_xC,OUT_xC_H,SBC_HL_HL,LD_xWORDe_HL,DB_64,DB_65,DB_66,RRD, IN_L_xC,OUT_xC_L,ADC_HL_HL,LD_HL_xWORDe,DB_6C,DB_6D,DB_6E,RLD, IN_F_xC,DB_71,SBC_HL_SP,LD_xWORDe_SP,DB_74,DB_75,DB_76,DB_77, IN_A_xC,OUT_xC_A,ADC_HL_SP,LD_SP_xWORDe,DB_7C,DB_7D,DB_7E,DB_7F, DB_80,DB_81,DB_82,DB_83,DB_84,DB_85,DB_86,DB_87, DB_88,DB_89,DB_8A,DB_8B,DB_8C,DB_8D,DB_8E,DB_8F, DB_90,DB_91,DB_92,DB_93,DB_94,DB_95,DB_96,DB_97, DB_98,DB_99,DB_9A,DB_9B,DB_9C,DB_9D,DB_9E,DB_9F, LDI,CPI,INI,OUTI,DB_A4,DB_A5,DB_A6,DB_A7, LDD,CPD,IND,OUTD,DB_AC,DB_AD,DB_AE,DB_AF, LDIR,CPIR,INIR,OTIR,DB_B4,DB_B5,DB_B6,DB_B7, LDDR,CPDR,INDR,OTDR,DB_BC,DB_BD,DB_BE,DB_BF, DB_C0,DB_C1,DB_C2,DB_C3,DB_C4,DB_C5,DB_C6,DB_C7, DB_C8,DB_C9,DB_CA,DB_CB,DB_CC,DB_CD,DB_CE,DB_CF, DB_D0,DB_D1,DB_D2,DB_D3,DB_D4,DB_D5,DB_D6,DB_D7, DB_D8,DB_D9,DB_DA,DB_DB,DB_DC,DB_DD,DB_DE,DB_DF, DB_E0,DB_E1,DB_E2,DB_E3,DB_E4,DB_E5,DB_E6,DB_E7, DB_E8,DB_E9,DB_EA,DB_EB,DB_EC,DB_ED,DB_EE,DB_EF, DB_F0,DB_F1,DB_F2,DB_F3,DB_F4,DB_F5,DB_F6,DB_F7, DB_F8,DB_F9,DB_FA,DB_FB,DB_FC,DB_FD,DB_FE,DB_FF }; static void CodesCB(register Z80 *R) { register byte I; I=OpZ80(R->PC.W++); R->ICount-=CyclesCB[I]; switch(I) { #include "CodesCB.h" default: if(R->TrapBadOps) printf ( "[Z80 %lX] Unrecognized instruction: CB %02X at PC=%04X\n", (long)(R->User),OpZ80(R->PC.W-1),R->PC.W-2 ); } } static void CodesDDCB(register Z80 *R) { register pair J; register byte I; #define XX IX J.W=R->XX.W+(offset)OpZ80(R->PC.W++); I=OpZ80(R->PC.W++); R->ICount-=CyclesXXCB[I]; switch(I) { #include "CodesXCB.h" default: if(R->TrapBadOps) printf ( "[Z80 %lX] Unrecognized instruction: DD CB %02X %02X at PC=%04X\n", (long)(R->User),OpZ80(R->PC.W-2),OpZ80(R->PC.W-1),R->PC.W-4 ); } #undef XX } static void CodesFDCB(register Z80 *R) { register pair J; register byte I; #define XX IY J.W=R->XX.W+(offset)OpZ80(R->PC.W++); I=OpZ80(R->PC.W++); R->ICount-=CyclesXXCB[I]; switch(I) { #include "CodesXCB.h" default: if(R->TrapBadOps) printf ( "[Z80 %lX] Unrecognized instruction: FD CB %02X %02X at PC=%04X\n", (long)R->User,OpZ80(R->PC.W-2),OpZ80(R->PC.W-1),R->PC.W-4 ); } #undef XX } static void CodesED(register Z80 *R) { register byte I; register pair J; I=OpZ80(R->PC.W++); R->ICount-=CyclesED[I]; switch(I) { #include "CodesED.h" case PFX_ED: R->PC.W--;break; default: if(R->TrapBadOps) printf ( "[Z80 %lX] Unrecognized instruction: ED %02X at PC=%04X\n", (long)R->User,OpZ80(R->PC.W-1),R->PC.W-2 ); } } static void CodesDD(register Z80 *R) { register byte I; register pair J; #define XX IX I=OpZ80(R->PC.W++); R->ICount-=CyclesXX[I]; switch(I) { #include "CodesXX.h" case PFX_FD: case PFX_DD: R->PC.W--;break; case PFX_CB: CodesDDCB(R);break; default: if(R->TrapBadOps) printf ( "[Z80 %lX] Unrecognized instruction: DD %02X at PC=%04X\n", (long)R->User,OpZ80(R->PC.W-1),R->PC.W-2 ); } #undef XX } static void CodesFD(register Z80 *R) { register byte I; register pair J; #define XX IY I=OpZ80(R->PC.W++); R->ICount-=CyclesXX[I]; switch(I) { #include "CodesXX.h" case PFX_FD: case PFX_DD: R->PC.W--;break; case PFX_CB: CodesFDCB(R);break; default: printf ( "Unrecognized instruction: FD %02X at PC=%04X\n", OpZ80(R->PC.W-1),R->PC.W-2 ); } #undef XX } /** ResetZ80() ***********************************************/ /** This function can be used to reset the register struct **/ /** before starting execution with Z80(). It sets the **/ /** registers to their supposed initial values. **/ /*************************************************************/ void ResetZ80(Z80 *R) { R->PC.W = 0x0000; R->SP.W = 0xF000; R->AF.W = 0x0000; R->BC.W = 0x0000; R->DE.W = 0x0000; R->HL.W = 0x0000; R->AF1.W = 0x0000; R->BC1.W = 0x0000; R->DE1.W = 0x0000; R->HL1.W = 0x0000; R->IX.W = 0x0000; R->IY.W = 0x0000; R->I = 0x00; R->R = 0x00; R->IFF = 0x00; R->ICount = R->IPeriod; R->IRequest = INT_NONE; R->IBackup = 0; JumpZ80(R->PC.W); #ifdef RCMX000 ioi_flag=0; ioe_flag=0; #endif } /** ExecZ80() ************************************************/ /** This function will execute given number of Z80 cycles. **/ /** It will then return the number of cycles left, possibly **/ /** negative, and current register values in R. **/ /*************************************************************/ #ifdef EXECZ80 int ExecZ80(register Z80 *R,register int RunCycles) { register byte I; register pair J; for(R->ICount=RunCycles;;) { while(R->ICount>0) { #ifdef DEBUG /* Turn tracing on when reached trap address */ if(R->PC.W==R->Trap) R->Trace=1; /* Call single-step debugger, exit if requested */ if(R->Trace) if(!DebugZ80(R)) return(R->ICount); #endif /* Read opcode and count cycles */ I=OpZ80(R->PC.W++); /* Count cycles */ R->ICount-=Cycles[I]; /* Interpret opcode */ switch(I) { #include "Codes.h" case PFX_CB: CodesCB(R);break; case PFX_ED: CodesED(R);break; case PFX_FD: CodesFD(R);break; case PFX_DD: CodesDD(R);break; } } /* Unless we have come here after EI, exit */ if(!(R->IFF&IFF_EI)) return(R->ICount); else { /* Done with AfterEI state */ R->IFF=(R->IFF&~IFF_EI)|IFF_1; /* Restore the ICount */ R->ICount+=R->IBackup-1; /* Interrupt CPU if needed */ if((R->IRequest!=INT_NONE)&&(R->IRequest!=INT_QUIT)) IntZ80(R,R->IRequest); } } } #endif /* EXECZ80 */ /** IntZ80() *************************************************/ /** This function will generate interrupt of given vector. **/ /*************************************************************/ void IntZ80(Z80 *R,word Vector) { /* If HALTed, take CPU off HALT instruction */ if(R->IFF&IFF_HALT) { R->PC.W++;R->IFF&=~IFF_HALT; } if((R->IFF&IFF_1)||(Vector==INT_NMI)) { /* Save PC on stack */ M_PUSH(PC); /* Automatically reset IRequest if needed */ if(R->IAutoReset&&(Vector==R->IRequest)) R->IRequest=INT_NONE; /* If it is NMI... */ if(Vector==INT_NMI) { /* Clear IFF1 */ R->IFF&=~(IFF_1|IFF_EI); /* Jump to hardwired NMI vector */ R->PC.W=0x0066; JumpZ80(0x0066); /* Done */ return; } /* Further interrupts off */ R->IFF&=~(IFF_1|IFF_2|IFF_EI); /* If in IM2 mode... */ if(R->IFF&IFF_IM2) { /* Make up the vector address */ Vector=(Vector&0xFF)|((word)(R->I)<<8); /* Read the vector */ R->PC.B.l=RdZ80(Vector++); R->PC.B.h=RdZ80(Vector); JumpZ80(R->PC.W); /* Done */ return; } /* If in IM1 mode, just jump to hardwired IRQ vector */ if(R->IFF&IFF_IM1) { R->PC.W=0x0038;JumpZ80(0x0038);return; } /* If in IM0 mode... */ /* Jump to a vector */ switch(Vector) { case INT_RST00: R->PC.W=0x0000;JumpZ80(0x0000);break; case INT_RST08: R->PC.W=0x0008;JumpZ80(0x0008);break; case INT_RST10: R->PC.W=0x0010;JumpZ80(0x0010);break; case INT_RST18: R->PC.W=0x0018;JumpZ80(0x0018);break; case INT_RST20: R->PC.W=0x0020;JumpZ80(0x0020);break; case INT_RST28: R->PC.W=0x0028;JumpZ80(0x0028);break; case INT_RST30: R->PC.W=0x0030;JumpZ80(0x0030);break; case INT_RST38: R->PC.W=0x0038;JumpZ80(0x0038);break; } } } #ifndef EXECZ80 /** * This function will execute num_instr instructions on the Z80 then return */ word InstrZ80(Z80 *R, int num_instr) { register byte I; register pair J; int n; for(n=1;n<=num_instr;n++) { #ifdef DEBUG /* Turn tracing on when reached trap address */ if(R->PC.W==R->Trap) R->Trace=1; /* Call single-step debugger, exit if requested */ if(R->Trace) if(!DebugZ80(R)) return(R->PC.W); #endif I=OpZ80(R->PC.W++); R->ICount-=Cycles[I]; switch(I) { #include "Codes.h" case PFX_CB: CodesCB(R);break; case PFX_ED: CodesED(R);break; case PFX_FD: CodesFD(R);break; case PFX_DD: CodesDD(R);break; } /* If cycle counter expired... */ if(R->ICount<=0) { /* If we have come after EI, get address from IRequest */ /* Otherwise, get it from the loop handler */ if(R->IFF&IFF_EI) { R->IFF=(R->IFF&~IFF_EI)|IFF_1; /* Done with AfterEI state */ R->ICount+=R->IBackup-1; /* Restore the ICount */ /* Call periodic handler or set pending IRQ */ if(R->ICount>0) J.W=R->IRequest; else { J.W=LoopZ80(R); /* Call periodic handler */ R->ICount+=R->IPeriod; /* Reset the cycle counter */ if(J.W==INT_NONE) J.W=R->IRequest; /* Pending IRQ */ } } else { J.W=LoopZ80(R); /* Call periodic handler */ R->ICount+=R->IPeriod; /* Reset the cycle counter */ if(J.W==INT_NONE) J.W=R->IRequest; /* Pending IRQ */ } if(J.W==INT_QUIT) return(R->PC.W); /* Exit if INT_QUIT */ if(J.W!=INT_NONE) IntZ80(R,J.W); /* Int-pt if needed */ } } #ifdef RCMX000 if (I==IOI || I==IOE) { /** The ioi/ioe and the following "memory" instruction is to be regarded as one * instruction */ InstrZ80(R, 1); } #endif /* Execution stopped */ return(R->PC.W); } /** RunZ80() *************************************************/ /** This function will run Z80 code until an LoopZ80() call **/ /** returns INT_QUIT. It will return the PC at which **/ /** emulation stopped, and current register values in R. **/ /*************************************************************/ word RunZ80(Z80 *R) { register byte I; register pair J; #ifdef RCMX000 rcmx_io_init(); #endif for(;;) { InstrZ80(R,1); } /* Execution stopped */ return(R->PC.W); } #endif /* !EXECZ80 */
29.037394
86
0.563102
[ "vector" ]
e78813e4bfd76cd4f8da3ab5a69fd9244958f691
525
h
C
StRoot/Sti/StiNeverActiveFunctor.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/Sti/StiNeverActiveFunctor.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/Sti/StiNeverActiveFunctor.h
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/** * @file StiNeverActiveFunctor.h * @class StiNeverActiveFunctor * @brief function object which always returns false * * @author Ben Norman, Kent State University * @date March 2002 */ #ifndef STI_NEVER_ACTIVE_FUNCTOR #define STI_NEVER_ACTIVE_FUNCTOR #include "StiIsActiveFunctor.h" ///Class implements an object which is never active. class StiNeverActiveFunctor : public StiIsActiveFunctor { public: StiNeverActiveFunctor(); virtual ~StiNeverActiveFunctor(); }; #endif // defined STI_NEVER_ACTIVE_FUNCTOR
21.875
55
0.779048
[ "object" ]
e7886d69f882eab1db0c82b35760aa63dcbdf8e2
3,381
h
C
SFUI/Include/UI/Widgets/Preloader.h
JayhawkZombie/SFUI
2870aab39deacb1a0be41d414d7d9d2349bdd17b
[ "MIT" ]
1
2019-04-30T23:38:05.000Z
2019-04-30T23:38:05.000Z
SFUI/Include/UI/Widgets/Preloader.h
JayhawkZombie/SFUI
2870aab39deacb1a0be41d414d7d9d2349bdd17b
[ "MIT" ]
null
null
null
SFUI/Include/UI/Widgets/Preloader.h
JayhawkZombie/SFUI
2870aab39deacb1a0be41d414d7d9d2349bdd17b
[ "MIT" ]
null
null
null
#ifndef SFUI_PRELOADER_H #define SFUI_PRELOADER_H //////////////////////////////////////////////////////////// // // MIT License // // Copyright(c) 2017 Kurt Slagle - kurt_slagle@yahoo.com // // 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. // // 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 of the software used is required. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Internal Headers //////////////////////////////////////////////////////////// #include <SFUI/Include/UI/Widget.h> #include <SFUI/Include/UI/Widgets/PreloaderBox.h> //////////////////////////////////////////////////////////// // Dependency Headers //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Standard Library Headers //////////////////////////////////////////////////////////// namespace sfui { class Preloader : public Widget { public: WIDGET_DERIVED(Preloader, Widget); Preloader(optional<Theme*> theme = { }, optional<Widget*> parent = { }); virtual ~Preloader() override; static shared_ptr Create(optional<Theme*> theme = { }, optional<Widget*> parent = { }); virtual void Update() override; virtual void Render(sf::RenderTarget &Target) override; virtual void SetPosition(const Vec2i &Position) override; virtual void SetSize(const Vec2i &Size) override; virtual void Move(const Vec2i &Delta) override; virtual void Start(uint32 SpawnFallDuration, uint32 SitDuration, uint32 DespawnFallDuration); virtual void Pause(); virtual void Stop(); virtual void Restart(); virtual void SetColor(const Color &c); protected: void PositionBoxes(); void BlockFinished(); SequenceTimer m_RestartTimer; std::vector<PreloaderBox::shared_ptr> m_Boxes; Vec2f m_BoxVelocities; int m_BoxHeight = 0; int m_BoxSpacing = 0; int m_FinishedCount = 0; uint32 m_SpawnDur = 0; uint32 m_SitDur = 0; uint32 m_DespDur = 0; kairos::Timer m_AnimTimer; kairos::Duration m_AnimDuration; bool m_ShouldRestart = true; bool m_IsPlaying = false; }; } #endif // SFUI_PRELOADER_H
35.589474
97
0.624076
[ "render", "vector" ]
e78fd5d9e0eb613c537e145251ae3049bc4451a8
12,730
h
C
ros_mscl/include/ros_mscl/microstrain_3dm.h
allenh1/ROS-MSCL
5dc63de808ed090b5c26bf70fc943a545391cf0a
[ "MIT" ]
null
null
null
ros_mscl/include/ros_mscl/microstrain_3dm.h
allenh1/ROS-MSCL
5dc63de808ed090b5c26bf70fc943a545391cf0a
[ "MIT" ]
null
null
null
ros_mscl/include/ros_mscl/microstrain_3dm.h
allenh1/ROS-MSCL
5dc63de808ed090b5c26bf70fc943a545391cf0a
[ "MIT" ]
null
null
null
/* Copyright (c) 2017, Brian Bingham Copyright (c) 2020, Parker Hannifin Corp This code is licensed under MIT license (see LICENSE file for details) */ #ifndef _MICROSTRAIN_3DM_H #define _MICROSTRAIN_3DM_H #include <cstdio> #include <unistd.h> #include <time.h> // ROS #include "ros/ros.h" #include "sensor_msgs/NavSatFix.h" #include "sensor_msgs/Imu.h" #include "geometry_msgs/PoseWithCovarianceStamped.h" #include "geometry_msgs/Vector3.h" #include "sensor_msgs/MagneticField.h" #include "nav_msgs/Odometry.h" #include "std_msgs/Int8.h" #include "std_msgs/Int16MultiArray.h" #include "std_msgs/MultiArrayLayout.h" #include "std_srvs/Empty.h" #include "std_srvs/Trigger.h" #include "std_msgs/Bool.h" #include "std_msgs/String.h" #include "ros_mscl/status_msg.h" #include "ros_mscl/nav_status_msg.h" #include "mscl/mscl.h" #include "ros_mscl/SetAccelBias.h" #include "ros_mscl/SetGyroBias.h" #include "ros_mscl/SetHardIronValues.h" #include "ros_mscl/SetSoftIronMatrix.h" #include "ros_mscl/SetComplementaryFilter.h" #include "ros_mscl/SetFilterEuler.h" #include "ros_mscl/SetFilterHeading.h" #include "ros_mscl/SetAccelBiasModel.h" #include "ros_mscl/SetAccelAdaptiveVals.h" #include "ros_mscl/SetSensorVehicleFrameTrans.h" #include "ros_mscl/SetSensorVehicleFrameOffset.h" #include "ros_mscl/SetReferencePosition.h" #include "ros_mscl/SetConingScullingComp.h" #include "ros_mscl/SetEstimationControlFlags.h" #include "ros_mscl/SetDynamicsMode.h" #include "ros_mscl/SetZeroAngleUpdateThreshold.h" #include "ros_mscl/SetZeroVelocityUpdateThreshold.h" #include "ros_mscl/SetTareOrientation.h" #include "ros_mscl/SetAccelNoise.h" #include "ros_mscl/SetGyroNoise.h" #include "ros_mscl/SetMagNoise.h" #include "ros_mscl/SetGyroBiasModel.h" #include "ros_mscl/SetMagAdaptiveVals.h" #include "ros_mscl/SetMagDipAdaptiveVals.h" #include "ros_mscl/SetHeadingSource.h" #define MIP_SDK_GX4_45_IMU_STANDARD_MODE 0x01 #define MIP_SDK_GX4_45_IMU_DIRECT_MODE 0x02 #define NUM_COMMAND_LINE_ARGUMENTS 3 #define DEFAULT_PACKET_TIMEOUT_MS 1000 //milliseconds //macro to cause Sleep call to behave as it does for windows #define Sleep(x) usleep(x*1000.0) #define GX5_45_DEVICE "3DM-GX5-45" #define GX5_35_DEVICE "3DM-GX5-35" #define GX5_25_DEVICE "3DM-GX5-25" #define GX5_15_DEVICE "3DM-GX5-15" /** * \brief Contains functions for micostrain driver */ namespace Microstrain { /** * \brief Microstrain class * */ class Microstrain { public: /** * Contructor */ Microstrain(); /** Destructor */ ~Microstrain(); /** * Main run loop */ void run(); void parseMipPacket(const mscl::MipDataPacket& packet); void parseSensorPacket(const mscl::MipDataPacket& packet); void parseEstFilterPacket(const mscl::MipDataPacket& packet); void parseGnssPacket(const mscl::MipDataPacket& packet); void device_status_callback(); void velocity_zupt_callback(const std_msgs::Bool& state); void velZupt(); void ang_zupt_callback(const std_msgs::Bool& state); void angZupt(); bool set_accel_bias(ros_mscl::SetAccelBias::Request &req, ros_mscl::SetAccelBias::Response &res); bool get_accel_bias(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_gyro_bias(ros_mscl::SetGyroBias::Request &req, ros_mscl::SetGyroBias::Response &res); bool get_gyro_bias(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_hard_iron_values(ros_mscl::SetHardIronValues::Request &req, ros_mscl::SetHardIronValues::Response &res); bool get_hard_iron_values(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool device_report(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool gyro_bias_capture(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_soft_iron_matrix(ros_mscl::SetSoftIronMatrix::Request &req, ros_mscl::SetSoftIronMatrix::Response &res); bool get_soft_iron_matrix(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_complementary_filter(ros_mscl::SetComplementaryFilter::Request &req, ros_mscl::SetComplementaryFilter::Response &res); bool get_complementary_filter(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_filter_euler(ros_mscl::SetFilterEuler::Request &req, ros_mscl::SetFilterEuler::Response &res); bool set_filter_heading(ros_mscl::SetFilterHeading::Request &req, ros_mscl::SetFilterHeading::Response &res); bool cmded_vel_zupt(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool cmded_ang_rate_zupt(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_heading_source(ros_mscl::SetHeadingSource::Request &req, ros_mscl::SetHeadingSource::Response &res); bool set_accel_bias_model(ros_mscl::SetAccelBiasModel::Request &req, ros_mscl::SetAccelBiasModel::Response &res); bool set_accel_adaptive_vals(ros_mscl::SetAccelAdaptiveVals::Request &req, ros_mscl::SetAccelAdaptiveVals::Response &res); bool set_sensor_vehicle_frame_trans(ros_mscl::SetSensorVehicleFrameTrans::Request &req, ros_mscl::SetSensorVehicleFrameTrans::Response &res); bool get_sensor_vehicle_frame_trans(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_sensor_vehicle_frame_offset(ros_mscl::SetSensorVehicleFrameOffset::Request &req, ros_mscl::SetSensorVehicleFrameOffset::Response &res); bool get_sensor_vehicle_frame_offset(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_reference_position(ros_mscl::SetReferencePosition::Request &req, ros_mscl::SetReferencePosition::Response &res); bool get_reference_position(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_coning_sculling_comp(ros_mscl::SetConingScullingComp::Request &req, ros_mscl::SetConingScullingComp::Response &res); bool get_coning_sculling_comp(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_estimation_control_flags(ros_mscl::SetEstimationControlFlags::Request &req, ros_mscl::SetEstimationControlFlags::Response &res); bool get_estimation_control_flags(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_dynamics_mode(ros_mscl::SetDynamicsMode::Request &req, ros_mscl::SetDynamicsMode::Response &res); bool get_dynamics_mode(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool get_basic_status(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool get_diagnostic_report(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_zero_angle_update_threshold(ros_mscl::SetZeroAngleUpdateThreshold::Request &req, ros_mscl::SetZeroAngleUpdateThreshold::Response &res); bool get_zero_angle_update_threshold(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_zero_velocity_update_threshold(ros_mscl::SetZeroVelocityUpdateThreshold::Request &req, ros_mscl::SetZeroVelocityUpdateThreshold::Response &res); bool get_zero_velocity_update_threshold(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_tare_orientation(ros_mscl::SetTareOrientation::Request &req, ros_mscl::SetTareOrientation::Response &res); bool set_accel_noise(ros_mscl::SetAccelNoise::Request &req, ros_mscl::SetAccelNoise::Response &res); bool get_accel_noise(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_gyro_noise(ros_mscl::SetGyroNoise::Request &req, ros_mscl::SetGyroNoise::Response &res); bool get_gyro_noise(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_mag_noise(ros_mscl::SetMagNoise::Request &req, ros_mscl::SetMagNoise::Response &res); bool get_mag_noise(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool set_gyro_bias_model(ros_mscl::SetGyroBiasModel::Request &req, ros_mscl::SetGyroBiasModel::Response &res); bool get_gyro_bias_model(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool get_accel_adaptive_vals(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res ); bool set_mag_adaptive_vals(ros_mscl::SetMagAdaptiveVals::Request &req, ros_mscl::SetMagAdaptiveVals::Response &res ); bool get_mag_adaptive_vals(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res ); bool set_mag_dip_adaptive_vals(ros_mscl::SetMagDipAdaptiveVals::Request &req, ros_mscl::SetMagDipAdaptiveVals::Response &res ); bool get_mag_dip_adaptive_vals(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res ); bool get_accel_bias_model(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res); bool get_model_gps() { if (Microstrain::GX5_45 || Microstrain::GX5_35) return true; else return false; } private: //! @brief Reset KF service callback bool reset_callback(std_srvs::Empty::Request &req, std_srvs::Empty::Response &resp); //! @brief Convience for printing packet stats void print_packet_stats(); // Variables/fields mscl::InertialNode *msclInertialNode; //Packet Counters (valid, timeout, and checksum errors) uint32_t filter_valid_packet_count_; uint32_t ahrs_valid_packet_count_; uint32_t gps_valid_packet_count_; uint32_t filter_timeout_packet_count_; uint32_t ahrs_timeout_packet_count_; uint32_t gps_timeout_packet_count_; uint32_t filter_checksum_error_packet_count_; uint32_t ahrs_checksum_error_packet_count_; uint32_t gps_checksum_error_packet_count_; //Data field storage //AHRS float curr_ahrs_mag_x; float curr_ahrs_mag_y; float curr_ahrs_mag_z; mscl::Vector curr_ahrs_quaternion_; //FILTER mscl::Vector curr_filter_quaternion_; float curr_filter_velNorth; float curr_filter_velEast; float curr_filter_velDown; double curr_filter_posLat; double curr_filter_posLong; double curr_filter_posHeight; float curr_filter_roll; float curr_filter_pitch; float curr_filter_yaw; float curr_filter_angularRate_x; float curr_filter_angularRate_y; float curr_filter_angularRate_z; float curr_filter_pos_uncert_north; float curr_filter_pos_uncert_east; float curr_filter_pos_uncert_down; float curr_filter_vel_uncert_north; float curr_filter_vel_uncert_east; float curr_filter_vel_uncert_down; float curr_filter_att_uncert_roll; float curr_filter_att_uncert_pitch; float curr_filter_att_uncert_yaw; // ROS ros::Publisher gps_pub_; ros::Publisher imu_pub_; ros::Publisher mag_pub_; ros::Publisher filtered_imu_pub_; ros::Publisher nav_pub_; ros::Publisher gps_odom_pub_; ros::Publisher nav_status_pub_; ros::Publisher bias_pub_; ros::Publisher device_status_pub_; ros::Subscriber vel_state_sub_; ros::Subscriber ang_state_sub_; sensor_msgs::NavSatFix gps_msg_; sensor_msgs::MagneticField mag_msg_; nav_msgs::Odometry gps_odom_msg_; sensor_msgs::Imu imu_msg_; sensor_msgs::Imu filtered_imu_msg_; nav_msgs::Odometry nav_msg_; geometry_msgs::Vector3 bias_msg_; std::string gps_frame_id_; std::string imu_frame_id_; std::string odom_frame_id_; std::string odom_child_frame_id_; std::string velocity_zupt_topic; std::string angular_zupt_topic; ros_mscl::status_msg device_status_msg_; ros_mscl::nav_status_msg nav_status_msg_; bool publish_gps_; bool publish_imu_; bool publish_odom_; bool publish_bias_; bool angular_zupt; bool velocity_zupt; bool vel_still; bool ang_still; std::vector<double> imu_linear_cov_; std::vector<double> imu_angular_cov_; std::vector<double> imu_orientation_cov_; //Device Flags bool GX5_15; bool GX5_25; bool GX5_35; bool GX5_45; bool GQX_45; bool RQX_45; bool CXX_45; bool CVX_10; bool CVX_15; bool CVX_25; // Update rates int nav_rate_; int imu_rate_; int gps_rate_; clock_t start; float field_data[3]; float soft_iron[9]; float soft_iron_readback[9]; float angles[3]; float heading_angle; float readback_angles[3]; float noise[3]; float beta[3]; float readback_beta[3]; float readback_noise[3]; float offset[3]; float readback_offset[3]; uint8_t com_mode; double reference_position_command[3]; double reference_position_readback[3]; uint8_t dynamics_mode; }; // Microstrain class // Define wrapper functions that call the Microstrain member functions #ifdef __cplusplus extern "C" #endif { #ifdef __cplusplus } #endif } // namespace Microstrain #endif // _MICROSTRAIN_3DM_GX5_45_H
32.809278
157
0.770463
[ "vector" ]
e793587e1f3f5be17e8522199385ce3a186eb4c4
1,141
h
C
bsp/rx/RPDL/r_pdl_iwdt_RX62Nxx.h
Davidfind/rt-thread
56f1a8af4f9e8bad0a0fdc5cea7112767267b243
[ "Apache-2.0" ]
7,482
2015-01-01T09:23:08.000Z
2022-03-31T19:34:05.000Z
bsp/rx/RPDL/r_pdl_iwdt_RX62Nxx.h
zlzerg/rt-thread
c0a400ccbee720fc0e9ee904298f09bd07a21382
[ "Apache-2.0" ]
2,543
2015-01-09T02:01:34.000Z
2022-03-31T23:10:14.000Z
bsp/rx/RPDL/r_pdl_iwdt_RX62Nxx.h
zlzerg/rt-thread
c0a400ccbee720fc0e9ee904298f09bd07a21382
[ "Apache-2.0" ]
4,645
2015-01-06T07:05:31.000Z
2022-03-31T18:21:50.000Z
/*""FILE COMMENT""******************************************************* * System Name : Independent Watchdog timer API for RX62Nxx * File Name : r_pdl_iwdt_RX62Nxx.h * Version : 1.02 * Contents : IWDT API header * Customer : * Model : * Order : * CPU : RX * Compiler : RXC * OS : Nothing * Programmer : * Note : ************************************************************************ * Copyright, 2011. Renesas Electronics Corporation * and Renesas Solutions Corporation ************************************************************************ * History : 2011.04.08 * : Ver 1.02 * : CS-5 release. *""FILE COMMENT END""**************************************************/ #ifndef R_PDL_IWDT_RX62Nxx_H #define R_PDL_IWDT_RX62Nxx_H /* Library prototypes */ bool R_IWDT_SetAll( const uint16_t ); bool R_IWDT_ControlAll( const uint8_t ); bool R_IWDT_ReadAll( volatile uint16_t * const ); /* Macro definitions */ #define R_IWDT_Set(a) \ ( \ R_IWDT_SetAll( (a) ) \ ) #define R_IWDT_Control(a) \ ( \ R_IWDT_ControlAll( (a) ) \ ) #define R_IWDT_Read(a) \ ( \ R_IWDT_ReadAll( (a) ) \ ) #endif /* End of file */
20.375
73
0.520596
[ "model" ]
e79514c0e2f6165ceb3829b653d8670b0a214f04
8,172
h
C
cppForSwig/lmdbpp.h
isabella232/BitcoinArmory
53c6f0b652aeb5774862952f729b8216664a1779
[ "MIT" ]
1
2020-10-02T13:49:19.000Z
2020-10-02T13:49:19.000Z
cppForSwig/lmdbpp.h
pryds/BitcoinArmory
53c6f0b652aeb5774862952f729b8216664a1779
[ "MIT" ]
1
2021-06-11T12:22:09.000Z
2021-06-11T12:22:09.000Z
cppForSwig/lmdbpp.h
isabella232/BitcoinArmory
53c6f0b652aeb5774862952f729b8216664a1779
[ "MIT" ]
1
2021-06-11T09:40:38.000Z
2021-06-11T09:40:38.000Z
//////////////////////////////////////////////////////////////////////////////// // // // Copyright (C) 2011-2015, Armory Technologies, Inc. // // Distributed under the GNU Affero General Public License (AGPL v3) // // See LICENSE-ATI or http://www.gnu.org/licenses/agpl.html // // // //////////////////////////////////////////////////////////////////////////////// #ifndef LMDBPP_H #define LMDBPP_H #include <string> #include <stdexcept> #include <vector> #include <unordered_map> #include <pthread.h> #include <mutex> struct MDB_env; struct MDB_txn; struct MDB_cursor; // this exception is thrown for all errors from LMDB class LMDBException : public std::runtime_error { public: LMDBException(const std::string &what) : std::runtime_error(what) { } }; class NoValue : public LMDBException { public: NoValue(const std::string &what) : LMDBException(what) { } }; // a class that stores a pointer to a memory block class CharacterArrayRef { public: const size_t len; const char *data; CharacterArrayRef(const size_t len, const char *data) : len(len), data(data) { } CharacterArrayRef(const size_t len, const unsigned char *data) : len(len), data(reinterpret_cast<const char*>(data)) { } CharacterArrayRef(const std::string &data) : len(data.size()), data(&data[0]) { } CharacterArrayRef(const std::vector<char> &data) : len(data.size()), data(&data.front()) { } }; class LMDBEnv; //one mother-txn per thread struct LMDBThreadTxInfo; class LMDB { public: class Iterator; enum Mode { ReadWrite, ReadOnly }; private: LMDBEnv *env=nullptr; unsigned int dbi=0; friend class Iterator; public: // this class can be used like a C++ iterator, // or you can just use isValid() to test for "last item" class Iterator { friend class LMDBEnv; friend class LMDB; LMDB *db_=nullptr; mutable MDB_cursor *csr_=nullptr; mutable bool hasTx=true; bool has_=false; LMDBThreadTxInfo* txnPtr_=nullptr; std::string key_, val_; void reset(); void checkHasDb() const; void checkOk() const; void openCursor(); Iterator(LMDB *db); public: Iterator() { } ~Iterator(); // copying permitted (encouraged!) Iterator(const Iterator &copy); Iterator(Iterator &&move); Iterator& operator=(Iterator &&move); Iterator& operator=(const Iterator &copy); // Returns true if the key pointed to is identical, or if both iterators // are invalid, and false otherwise. // returns true if the key pointed to is in different databases bool operator==(const Iterator &other) const; // the inverse bool operator!=(const Iterator &other) const { return !operator==(other); } enum SeekBy { Seek_EQ, Seek_GE, Seek_LE }; // move this iterator such that, if the exact key is not found: // for e == Seek_EQ // The cursor is left as Invalid. // for e == Seek_GE // The cursor is left pointing to the smallest key in the database that is // larger than (key). If the database contains no keys larger than // (key), the cursor is left as Invalid. void seek(const CharacterArrayRef &key, SeekBy e = Seek_EQ); // is the cursor pointing to a valid location? bool isValid() const { return has_; } operator bool() const { return isValid(); } bool isEOF() const { return !isValid(); } // advance the cursor // the postfix increment operator is not defined for performance reasons Iterator& operator++() { advance(); return *this; } void advance(); Iterator& operator--() { retreat(); return *this; } void retreat(); // seek this iterator to the first sequence void toFirst(); // returns the key currently pointed to, if no key is being pointed to // std::logic_error is returned (not LSMException). LSMException may // be thrown for other reasons. You can avoid logic_error by // calling isValid() first const std::string& key() const { return key_; } // returns the value currently pointed to. Exceptions are thrown // under the same conditions as key() const std::string& value() const { return val_; } }; LMDB() { } LMDB(LMDBEnv *env, const std::string &name=std::string()) { open(env, name); } ~LMDB(); void open(LMDBEnv *env, const std::string &name=std::string()); void close(); void drop(); // insert a value into the database, replacing // the one with a matching key if it is already there void insert( const CharacterArrayRef& key, const CharacterArrayRef& value ); // delete the entry with the given key, doing nothing // if such a key does not exist void erase(const CharacterArrayRef& key); // read the value having the given key std::string value(const CharacterArrayRef& key) const; // read the value having the given key, without copying its // data even once. The return object has a pointer to the // location in memory CharacterArrayRef get_NoCopy(const CharacterArrayRef& key) const; // create a cursor for scanning the database that points to the first // item Iterator begin() const { Iterator c(const_cast<LMDB*>(this)); c.toFirst(); return c; } // creates a cursor that points to an invalid item Iterator end() const { Iterator c(const_cast<LMDB*>(this)); return c; } template<class T> Iterator find(const T &t) const { Iterator c = cursor(); c.seek(t); return c; } // Create an iterator that points to an invalid item. // like end(), the iterator can be repositioned to // become a valid entry Iterator cursor() const { return end(); } private: LMDB(const LMDB &nocopy); }; struct LMDBThreadTxInfo { MDB_txn *txn_=nullptr; std::vector<LMDB::Iterator*> iterators_; unsigned transactionLevel_=0; LMDB::Mode mode_; }; class LMDBEnv { public: class Transaction; private: MDB_env *dbenv=nullptr; std::mutex threadTxMutex_; std::unordered_map<pthread_t, LMDBThreadTxInfo> txForThreads_; friend class LMDB; public: class Transaction { friend class LMDB; LMDBEnv *env=nullptr; bool began=false; LMDB::Mode mode_; public: Transaction() { } // begin a transaction Transaction(LMDBEnv *env, LMDB::Mode mode = LMDB::ReadWrite); // commit a transaction if it exists ~Transaction(); Transaction& operator=(Transaction&& mv); // commit the current transaction, create a new one, and begin it void open(LMDBEnv *env, LMDB::Mode mode = LMDB::ReadWrite); // commit a transaction, if it exists, doing nothing otherwise. // after this function completes, no transaction exists void commit(); // rollback the transaction, if it exists, doing nothing otherwise. // All modifications made since this transaction began are removed. // After this function completes, no transaction exists void rollback(); // start a new transaction. If one already exists, do nothing void begin(); private: Transaction(const Transaction&); // no copies }; LMDBEnv() { } ~LMDBEnv(); // open a database by filename void open(const char *filename); void open(const std::string &filename) { open(filename.c_str()); } // close a database, doing nothing if one is presently not open void close(); private: LMDBEnv(const LMDBEnv&); // disallow copy }; #endif // kate: indent-width 3; replace-tabs on;
25.77918
80
0.599731
[ "object", "vector" ]
436b41278049e82d7577988230d86911af3f1bba
5,253
h
C
searchcore/src/vespa/searchcore/proton/index/indexmanager.h
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
null
null
null
searchcore/src/vespa/searchcore/proton/index/indexmanager.h
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
null
null
null
searchcore/src/vespa/searchcore/proton/index/indexmanager.h
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
null
null
null
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/searchcorespi/index/iindexmaintaineroperations.h> #include <vespa/searchcorespi/index/iindexmanager.h> #include <vespa/searchcorespi/index/indexmaintainer.h> #include <vespa/searchcorespi/index/ithreadingservice.h> #include <vespa/searchcorespi/index/warmupconfig.h> namespace proton::index { struct IndexConfig { using WarmupConfig = searchcorespi::index::WarmupConfig; IndexConfig() : IndexConfig(WarmupConfig(), 2, 0) { } IndexConfig(WarmupConfig warmup_, size_t maxFlushed_, size_t cacheSize_) : warmup(warmup_), maxFlushed(maxFlushed_), cacheSize(cacheSize_) { } const WarmupConfig warmup; const size_t maxFlushed; const size_t cacheSize; }; /** * The IndexManager provides a holistic view of a set of disk and * memory indexes. It allows updating the active index, enables search * across all indexes, and manages the set of indexes through flushing * of memory indexes and fusion of disk indexes. */ class IndexManager : public searchcorespi::IIndexManager { public: class MaintainerOperations : public searchcorespi::index::IIndexMaintainerOperations { private: using IDiskIndex = searchcorespi::index::IDiskIndex; using IMemoryIndex = searchcorespi::index::IMemoryIndex; const size_t _cacheSize; const search::common::FileHeaderContext &_fileHeaderContext; const search::TuneFileIndexing _tuneFileIndexing; const search::TuneFileSearch _tuneFileSearch; searchcorespi::index::IThreadingService &_threadingService; public: MaintainerOperations(const search::common::FileHeaderContext &fileHeaderContext, const search::TuneFileIndexManager &tuneFileIndexManager, size_t cacheSize, searchcorespi::index::IThreadingService &threadingService); IMemoryIndex::SP createMemoryIndex(const Schema& schema, const IFieldLengthInspector& inspector, SerialNum serialNum) override; IDiskIndex::SP loadDiskIndex(const vespalib::string &indexDir) override; IDiskIndex::SP reloadDiskIndex(const IDiskIndex &oldIndex) override; bool runFusion(const Schema &schema, const vespalib::string &outputDir, const std::vector<vespalib::string> &sources, const SelectorArray &docIdSelector, search::SerialNum lastSerialNum, std::shared_ptr<search::IFlushToken> flush_token) override; }; private: MaintainerOperations _operations; searchcorespi::index::IndexMaintainer _maintainer; public: IndexManager(const IndexManager &) = delete; IndexManager & operator = (const IndexManager &) = delete; IndexManager(const vespalib::string &baseDir, const IndexConfig & indexConfig, const Schema &schema, SerialNum serialNum, Reconfigurer &reconfigurer, searchcorespi::index::IThreadingService &threadingService, vespalib::Executor & warmupExecutor, const search::TuneFileIndexManager &tuneFileIndexManager, const search::TuneFileAttributes &tuneFileAttributes, const search::common::FileHeaderContext &fileHeaderContext); ~IndexManager() override; searchcorespi::index::IndexMaintainer &getMaintainer() { return _maintainer; } /** * Implements searchcorespi::IIndexManager **/ void putDocument(uint32_t lid, const Document &doc, SerialNum serialNum, OnWriteDoneType on_write_done) override { _maintainer.putDocument(lid, doc, serialNum, on_write_done); } void removeDocuments(LidVector lids, SerialNum serialNum) override { _maintainer.removeDocuments(std::move(lids), serialNum); } void commit(SerialNum serialNum, OnWriteDoneType onWriteDone) override { _maintainer.commit(serialNum, onWriteDone); } void heartBeat(SerialNum serialNum) override { _maintainer.heartBeat(serialNum); } void compactLidSpace(uint32_t lidLimit, SerialNum serialNum) override; SerialNum getCurrentSerialNum() const override { return _maintainer.getCurrentSerialNum(); } SerialNum getFlushedSerialNum() const override { return _maintainer.getFlushedSerialNum(); } searchcorespi::IndexSearchable::SP getSearchable() const override { return _maintainer.getSearchable(); } search::SearchableStats getSearchableStats() const override { return _maintainer.getSearchableStats(); } searchcorespi::IFlushTarget::List getFlushTargets() override { return _maintainer.getFlushTargets(); } void setSchema(const Schema &schema, SerialNum serialNum) override { _maintainer.setSchema(schema, serialNum); } void setMaxFlushed(uint32_t maxFlushed) override { _maintainer.setMaxFlushed(maxFlushed); } }; } // namespace proton
38.625
118
0.684942
[ "vector" ]
436ebc77dfe5a07f94182b3367547fe902a215b5
7,646
h
C
chrome/browser/extensions/extension_sync_service.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extension_sync_service.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/extension_sync_service.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 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 CHROME_BROWSER_EXTENSIONS_EXTENSION_SYNC_SERVICE_H_ #define CHROME_BROWSER_EXTENSIONS_EXTENSION_SYNC_SERVICE_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/scoped_observer.h" #include "base/version.h" #include "chrome/browser/extensions/sync_bundle.h" #include "components/keyed_service/core/keyed_service.h" #include "components/sync/model/model_error.h" #include "components/sync/model/syncable_service.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_prefs_observer.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" class Profile; namespace extensions { class Extension; class ExtensionService; class ExtensionSet; class ExtensionSyncData; } // namespace extensions // SyncableService implementation responsible for the APPS and EXTENSIONS data // types, i.e. "proper" apps/extensions (not themes). class ExtensionSyncService : public syncer::SyncableService, public KeyedService, public extensions::ExtensionRegistryObserver, public extensions::ExtensionPrefsObserver { public: explicit ExtensionSyncService(Profile* profile); ~ExtensionSyncService() override; // Convenience function to get the ExtensionSyncService for a BrowserContext. static ExtensionSyncService* Get(content::BrowserContext* context); // Notifies Sync (if needed) of a newly-installed extension or a change to // an existing extension. Call this when you change an extension setting that // is synced as part of ExtensionSyncData (e.g. incognito_enabled). void SyncExtensionChangeIfNeeded(const extensions::Extension& extension); // Returns whether the extension with the given |id| will be re-enabled once // it is updated to the given |version|. This happens when we get a Sync // update telling us to re-enable a newer version than what is currently // installed. // TODO(crbug/1019813): The logic for this function was broken after forced // custodian installations were removed. See // ExtensionServiceTestSupervised. // UpdateWithPermissionIncreaseApprovalNewVersion // for an example of when this function should return true but returns false // instead in the test code. bool HasPendingReenable(const std::string& id, const base::Version& version) const; // syncer::SyncableService implementation. void WaitUntilReadyToSync(base::OnceClosure done) override; base::Optional<syncer::ModelError> MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, std::unique_ptr<syncer::SyncChangeProcessor> sync_processor, std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory) override; void StopSyncing(syncer::ModelType type) override; syncer::SyncDataList GetAllSyncDataForTesting(syncer::ModelType type) const; base::Optional<syncer::ModelError> ProcessSyncChanges( const base::Location& from_here, const syncer::SyncChangeList& change_list) override; void SetSyncStartFlareForTesting( const syncer::SyncableService::StartSyncFlare& flare); // Special hack: There was a bug where themes incorrectly ended up in the // syncer::EXTENSIONS type. This is for cleaning up the data. crbug.com/558299 // DO NOT USE FOR ANYTHING ELSE! // TODO(crbug.com/862665): This *should* be safe to remove now, but it's not. void DeleteThemeDoNotUse(const extensions::Extension& theme); private: FRIEND_TEST_ALL_PREFIXES(TwoClientExtensionAppsSyncTest, UnexpectedLaunchType); FRIEND_TEST_ALL_PREFIXES(ExtensionDisabledGlobalErrorTest, HigherPermissionsFromSync); extensions::ExtensionService* extension_service() const; // extensions::ExtensionRegistryObserver: void OnExtensionInstalled(content::BrowserContext* browser_context, const extensions::Extension* extension, bool is_update) override; void OnExtensionUninstalled(content::BrowserContext* browser_context, const extensions::Extension* extension, extensions::UninstallReason reason) override; // extensions::ExtensionPrefsObserver: void OnExtensionStateChanged(const std::string& extension_id, bool state) override; void OnExtensionDisableReasonsChanged(const std::string& extension_id, int disabled_reasons) override; // Gets the SyncBundle for the given |type|. extensions::SyncBundle* GetSyncBundle(syncer::ModelType type); const extensions::SyncBundle* GetSyncBundle(syncer::ModelType type) const; // Creates the ExtensionSyncData for the given app/extension. extensions::ExtensionSyncData CreateSyncData( const extensions::Extension& extension) const; // Applies the given change coming in from the server to the local state. void ApplySyncData(const extensions::ExtensionSyncData& extension_sync_data); // Applies the bookmark app specific parts of |extension_sync_data|. void ApplyBookmarkAppSyncData( const extensions::ExtensionSyncData& extension_sync_data); // Collects the ExtensionSyncData for all installed apps or extensions. std::vector<extensions::ExtensionSyncData> GetLocalSyncDataList( syncer::ModelType type) const; // Helper for GetLocalSyncDataList. void FillSyncDataList( const extensions::ExtensionSet& extensions, syncer::ModelType type, std::vector<extensions::ExtensionSyncData>* sync_data_list) const; // Returns whether the given extension should be synced by this class. // Filters out unsyncable extensions as well as themes (which are handled by // ThemeSyncableService instead). bool ShouldSync(const extensions::Extension& extension) const; // The normal profile associated with this ExtensionSyncService. Profile* profile_; ScopedObserver<extensions::ExtensionRegistry, extensions::ExtensionRegistryObserver> registry_observer_{this}; ScopedObserver<extensions::ExtensionPrefs, extensions::ExtensionPrefsObserver> prefs_observer_{this}; // When this is set to true, any incoming updates (from the observers as well // as from explicit SyncExtensionChangeIfNeeded calls) are ignored. This is // set during ApplySyncData, so that ExtensionSyncService doesn't end up // notifying itself while applying sync changes. bool ignore_updates_; extensions::SyncBundle app_sync_bundle_; extensions::SyncBundle extension_sync_bundle_; // Map from extension id to pending update data. Used for two things: // - To send the new version back to the sync server while we're waiting for // an extension to update. // - For re-enables, to defer granting permissions until the version matches. struct PendingUpdate; std::map<std::string, PendingUpdate> pending_updates_; // Run()ning tells sync to try and start soon, because syncable changes // have started happening. It will cause sync to call us back // asynchronously via MergeDataAndStartSyncing as soon as possible. syncer::SyncableService::StartSyncFlare flare_; DISALLOW_COPY_AND_ASSIGN(ExtensionSyncService); }; #endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_SYNC_SERVICE_H_
43.942529
80
0.749673
[ "vector", "model" ]
43738e7d1eec2c2e9ec6df00fe5e170f4684bc62
10,940
h
C
Message/ChatMessage.h
coderwinnie/startalk_pc
30675f52204d798f4fef210a40ef9c5f1ac34ea9
[ "MIT" ]
null
null
null
Message/ChatMessage.h
coderwinnie/startalk_pc
30675f52204d798f4fef210a40ef9c5f1ac34ea9
[ "MIT" ]
null
null
null
Message/ChatMessage.h
coderwinnie/startalk_pc
30675f52204d798f4fef210a40ef9c5f1ac34ea9
[ "MIT" ]
null
null
null
 #ifndef _CHARMESSAGE_H_ #define _CHARMESSAGE_H_ #include <memory> #include <set> #include "../EventBus/Event.hpp" #include "../include/CommonDefine.h" #include "../include/im_enum.h" #include "../entity/IM_Session.h" #include "../entity/im_message.h" #include "../include/CommonStrcut.h" #include "../entity/UID.h" #include <map> #include <utility> typedef std::vector<QTalk::Entity::ImMessageInfo> VectorMessage; // 发送消息 class S_Message : public Event { public: QInt64 time; QUInt8 chatType; std::string userId; QTalk::Entity::ImMessageInfo message; }; // 接收消息 class R_Message : public Event { public: QInt64 time; QUInt8 chatType; std::string userId; QTalk::Entity::ImMessageInfo message; bool isCarbon; }; class PreSendMessageEvt : public Event { public: QTalk::Entity::ImMessageInfo message; }; // 拉的历史消息 class HistoryMessage : public Event { public: QInt64 time; QUInt8 chatType; QTalk::Entity::UID uid; VectorMessage msgList; }; class NetHistoryMessage : public HistoryMessage { public: std::string direction; }; class LocalHistoryMessage : public Event { public: QInt64 time; std::string userid; std::string realJid; VectorMessage msgList; }; class FileHistoryMessage : public Event { public: QInt64 time; std::string userid; std::string realJid; VectorMessage msgList; }; class ImageHistoryMessage : public Event { public: QInt64 time; std::string userid; std::string realJid; VectorMessage msgList; }; class LinkHistoryMessage : public Event { public: QInt64 time; std::string userid; std::string realJid; VectorMessage msgList; }; class SearchHistoryMessage : public Event { public: QInt64 time; std::string userid; std::string realJid; std::string searchKey; VectorMessage msgList; }; /** * 后翻拉取本地历史 */ class AfterMessage : public Event { public: QInt64 time; std::string userid; std::string realJid; VectorMessage msgList; }; // 获取本地图片的网络地址 class LocalImgEvt : public Event { public: std::string localFilePath; std::string netFilePath; }; //获取网络图片的本地地址 class NetImgEvt : public LocalImgEvt{}; class SourceNetImage : public LocalImgEvt{}; // 获取网络头像的本地地址 class NetHeadImgEvt : public NetImgEvt{}; // 批量下载图片 class DownLoadHeadPhotoEvent : public Event { public: std::vector<std::string> _withoutHeadPhotos; }; // 批量下载图片成功 class DownloadHeadSuccess : public Event { }; // 批量下载群图片 class DownLoadGroupHeadPhotoEvent : public Event { public: std::vector<std::string> _withoutHeadPhotos; }; // 批量下载群图片成功 class DownloadGroupHeadSuccess : public Event{}; // 更新在线状态 class UpdateOnlineEvent : public Event{}; // 获取用户在离线信息 class GetUsersOnlineEvent : public Event { public: std::set<std::string> _users; }; class GetUsersOnlineSucessEvent : public Event { public: std::map<std::string, std::string> _userstatus; }; // class DownloadFileWithProcess : public Event { public: std::string strUri; std::string strLocalPath; std::string processKey; }; class FileWrited : public Event { public: std::string localPath; }; class FileProcessMessage : public Event { public: std::string key; double downloadTotal; double downloadNow; double uploadTotal; double uploadNow; double speed; double leftTime; }; class DownloadFileComplete : public Event { public: std::string key; std::string localPath; bool finish; }; // class GetEmoticonFileMessage : public Event { public: GetEmoticonFileMessage(std::string pid, std::string sid, std::string name) : pkgid(std::move(pid)), emoShortcut(std::move(sid)), fileName(std::move(name)) { } public: std::string pkgid; std::string emoShortcut; std::string fileName; std::string realFilePath; }; // class GetNetEmoticon : public Event { public: ArStNetEmoticon arEmoInfo; }; class SearchInfoEvent : public Event { public: //"start":0, "length":5, "key":"dan.liu xuejie.bi", "qtalkId": "jingyu.he", "groupId":"Q07", "cKey":"xxx" int start = 0; int length = 0; std::string key; int action; std::string to_user; std::string to_muc; // SearchResult searchRet; }; // class ReadedMessage : public Event { public: explicit ReadedMessage(std::string messageId, std::string userId, QUInt8 chatType) : messageId(std::move(messageId)), userId(std::move(userId)), chatType(chatType) { }; public: const std::string messageId; const std::string userId; const QUInt8 chatType; }; class SignalReadState : public Event { public: SignalReadState(const std::map<std::string, QInt32>& mapRead, const std::string& userId,const std::string& realJid) : userId(userId),realJid(realJid), mapReadState(mapRead) { }; public: const std::string& userId; const std::string& realJid; const std::map<std::string, QInt32 >& mapReadState; }; class MStateEvt : public Event { public: std::string userId; std::string realJid; std::string messageId; QInt64 time; }; class GroupReadState : public Event { public: GroupReadState(const std::map<std::string, int >& readCount, const std::string& groupId) : mapReadCount(readCount), groupId(groupId) { } public: const std::map<std::string, int >& mapReadCount; const std::string& groupId; }; // delete delete class GroupReadMState : public Event { public: GroupReadMState(const std::vector<std::string>& ids, const std::string& groupId) : msgIds(ids), groupId(groupId) { } public: const std::vector<std::string>& msgIds; const std::string& groupId; }; class RevokeMessage : public Event { public: RevokeMessage(QTalk::Entity::UID uid, std::string fromId, std::string messageId) : uid(std::move(uid)), messageFrom(std::move(fromId)), messageId(std::move(messageId)),chatType(QTalk::Enum::ChatType::TwoPersonChat) { } public: RevokeMessage(QTalk::Entity::UID uid, std::string fromId, std::string messageId,QUInt8 chatType) :uid(std::move(uid)), messageFrom(std::move(fromId)), messageId(std::move(messageId)),chatType(chatType) { } public: const QTalk::Entity::UID uid; const std::string messageFrom; const std::string messageId; const QUInt8 chatType; QInt64 time; }; class S_RevokeMessage : public RevokeMessage { public: S_RevokeMessage(const QTalk::Entity::UID& uid, const std::string& fromId, const std::string& messageId,const QUInt8 chatType) :RevokeMessage(uid, fromId, messageId,chatType) {} ~S_RevokeMessage() override = default; }; /** * 对方拉黑自己 收到反馈 */ class R_BlackListMessage : public Event { public: std::string messageId; std::string messageFrom; }; class DownloadCollection : public Event { public: explicit DownloadCollection(const std::vector<std::string>& downloads) :arDownloads(downloads){} ~DownloadCollection() override = default; public: const std::vector<std::string>& arDownloads; }; class ForwardMessage : public Event { public: ForwardMessage(std::string messageId, std::map<std::string, int> users) :messageId(std::move(messageId)), users(std::move(users)) {} public: std::string messageId; std::map<std::string, int> users; }; class LogReportMessage: public Event { public: LogReportMessage(std::string desc, std::string logPath) : _strLogPath(std::move(logPath)), _desc(std::move(desc)) { } public: std::string _strLogPath; std::string _desc; }; class ReportDump : public Event { public: explicit ReportDump(std::string ip, std::string id, std::string dump, QInt64 time) :ipAddr(std::move(ip)), id(id), dumpFile(std::move(dump)), crashTime(time) { } public: std::string ipAddr; std::string id; std::string dumpFile; QInt64 crashTime; }; class ReportLogin : public Event {}; class CheckUpdaterEvt : public Event { public: int version = 0; std::string updater_link; }; class CheckUpdaterResultEvt : public Event { public: bool hasUpdate {}; bool forceUpdate{}; std::string link; }; class LogReportMessageRet : public Event { public: explicit LogReportMessageRet(bool isSuccess, std::string msg) : _strLogRetMsg(std::move(msg)), _success(isSuccess) { } public: std::string _strLogRetMsg; bool _success; }; class RecvVideoMessage : public Event { public: explicit RecvVideoMessage(std::string userId) : _userId(std::move(userId)) {} public: std::string _userId; }; class SaveConfigEvt : public Event { public: SaveConfigEvt() = default; }; class ClearSystemCacheEvt : public Event { public: ClearSystemCacheEvt() = default; }; class ChangeHeadMessage : public Event { public: explicit ChangeHeadMessage(std::string userHead) : userHead(std::move(userHead)) {}; public: std::string userHead; }; class ChangeHeadRetMessage : public Event { public: explicit ChangeHeadRetMessage(bool ret, std::string localHead) : ret(ret), localHead(std::move(localHead)) { } public: bool ret{}; std::string localHead; }; class UploadFileEvt : public Event { public: explicit UploadFileEvt(std::string localPath, bool withProcess, std::string processKey) : localPath(std::move(localPath)), withProcess(withProcess), process_key(std::move(processKey)) { } public: std::string localPath; bool withProcess; std::string process_key; std::string fileUrl; }; class RecentSessionEvt : public Event { public: explicit RecentSessionEvt(std::vector<QTalk::StShareSession>& ss) : sessions(ss) { }; public: std::vector<QTalk::StShareSession>& sessions; }; class ContactsSessionEvt : public Event { public: explicit ContactsSessionEvt(std::vector<QTalk::StShareSession>& ss) : sessions(ss) { }; public: std::vector<QTalk::StShareSession>& sessions; }; class ImageMessageEvt : public Event { public: explicit ImageMessageEvt(bool isNext, const std::string& messageId, std::vector<std::pair<std::string, std::string>> & msgs) : messageId(messageId), msgs(msgs), isNext(isNext){ }; public: const std::string& messageId; std::vector<std::pair<std::string, std::string>> & msgs; bool isNext; }; class EmptyMessageEvt : public Event { public: explicit EmptyMessageEvt(QTalk::Entity::ImMessageInfo msgInfo) { this->msgInfo = std::move(msgInfo); } public: QTalk::Entity::ImMessageInfo msgInfo; }; class HotLineMessageListEvt : public Event { public: std::string xmppId; }; class UpdateMsgExtendInfo : public Event { public: std::string msgId; std::string extendInfo; }; #endif//_CHARMESSAGE_H_
19.890909
143
0.675229
[ "vector" ]
437838fc99fb49da615d2b2852726315900eaa29
1,143
h
C
app/src/frames.h
alchal/scrcpy
b882322f7371b16acd53677c4a3adbaaed0aef77
[ "Apache-2.0" ]
11
2020-02-19T06:44:11.000Z
2020-12-12T11:36:15.000Z
app/src/frames.h
alchal/scrcpy
b882322f7371b16acd53677c4a3adbaaed0aef77
[ "Apache-2.0" ]
1
2019-09-05T10:14:51.000Z
2019-09-05T10:14:51.000Z
app/src/frames.h
alchal/scrcpy
b882322f7371b16acd53677c4a3adbaaed0aef77
[ "Apache-2.0" ]
9
2019-12-27T05:52:48.000Z
2020-09-29T16:02:45.000Z
#ifndef FRAMES_H #define FRAMES_H #include <SDL2/SDL_mutex.h> #include <SDL2/SDL_stdinc.h> #include "config.h" #include "fps_counter.h" // forward declarations typedef struct AVFrame AVFrame; struct frames { AVFrame *decoding_frame; AVFrame *rendering_frame; SDL_mutex *mutex; #ifndef SKIP_FRAMES SDL_bool stopped; SDL_cond *rendering_frame_consumed_cond; #endif SDL_bool rendering_frame_consumed; struct fps_counter fps_counter; }; SDL_bool frames_init(struct frames *frames); void frames_destroy(struct frames *frames); // set the decoder frame as ready for rendering // this function locks frames->mutex during its execution // returns true if the previous frame had been consumed SDL_bool frames_offer_decoded_frame(struct frames *frames); // mark the rendering frame as consumed and return it // MUST be called with frames->mutex locked!!! // the caller is expected to render the returned frame to some texture before // unlocking frames->mutex const AVFrame *frames_consume_rendered_frame(struct frames *frames); // wake up and avoid any blocking call void frames_stop(struct frames *frames); #endif
26.581395
77
0.776903
[ "render" ]
437a6d05f840ca1a725e8fb23039087dfe6bd887
174,620
c
C
external/bsd/bind/dist/lib/isc/unix/socket.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
external/bsd/bind/dist/lib/isc/unix/socket.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
external/bsd/bind/dist/lib/isc/unix/socket.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
/* $NetBSD: socket.c,v 1.17 2015/07/08 17:29:00 christos Exp $ */ /* * Copyright (C) 2004-2014 Internet Systems Consortium, Inc. ("ISC") * Copyright (C) 1998-2003 Internet Software Consortium. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* Id */ /*! \file */ #include <config.h> #include <sys/param.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/uio.h> #if defined(HAVE_LINUX_NETLINK_H) && defined(HAVE_LINUX_RTNETLINK_H) #include <linux/netlink.h> #include <linux/rtnetlink.h> #endif #include <errno.h> #include <fcntl.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifdef HAVE_INTTYPES_H #include <inttypes.h> /* uintptr_t */ #endif #include <isc/buffer.h> #include <isc/bufferlist.h> #include <isc/condition.h> #include <isc/formatcheck.h> #include <isc/json.h> #include <isc/list.h> #include <isc/log.h> #include <isc/mem.h> #include <isc/msgs.h> #include <isc/mutex.h> #include <isc/net.h> #include <isc/once.h> #include <isc/platform.h> #include <isc/print.h> #include <isc/region.h> #include <isc/resource.h> #include <isc/socket.h> #include <isc/stats.h> #include <isc/strerror.h> #include <isc/task.h> #include <isc/thread.h> #include <isc/util.h> #include <isc/xml.h> #ifdef ISC_PLATFORM_HAVESYSUNH #include <sys/un.h> #endif #ifdef ISC_PLATFORM_HAVEKQUEUE #include <sys/event.h> #endif #ifdef ISC_PLATFORM_HAVEEPOLL #include <sys/epoll.h> #endif #ifdef ISC_PLATFORM_HAVEDEVPOLL #if defined(HAVE_SYS_DEVPOLL_H) #include <sys/devpoll.h> #elif defined(HAVE_DEVPOLL_H) #include <devpoll.h> #endif #endif #include "errno2result.h" /* See task.c about the following definition: */ #ifdef ISC_PLATFORM_USETHREADS #define USE_WATCHER_THREAD #else #define USE_SHARED_MANAGER #endif /* ISC_PLATFORM_USETHREADS */ #ifndef USE_WATCHER_THREAD #include "socket_p.h" #include "../task_p.h" #endif /* USE_WATCHER_THREAD */ #if defined(SO_BSDCOMPAT) && defined(__linux__) #include <sys/utsname.h> #endif /*% * Choose the most preferable multiplex method. */ #ifdef ISC_PLATFORM_HAVEKQUEUE #define USE_KQUEUE #elif defined (ISC_PLATFORM_HAVEEPOLL) #define USE_EPOLL #elif defined (ISC_PLATFORM_HAVEDEVPOLL) #define USE_DEVPOLL typedef struct { unsigned int want_read : 1, want_write : 1; } pollinfo_t; #else #define USE_SELECT #endif /* ISC_PLATFORM_HAVEKQUEUE */ #ifndef USE_WATCHER_THREAD #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) struct isc_socketwait { int nevents; }; #elif defined (USE_SELECT) struct isc_socketwait { fd_set *readset; fd_set *writeset; int nfds; int maxfd; }; #endif /* USE_KQUEUE */ #endif /* !USE_WATCHER_THREAD */ /* * Set by the -T dscp option on the command line. If set to a value * other than -1, we check to make sure DSCP values match it, and * assert if not. */ int isc_dscp_check_value = -1; /*% * Maximum number of allowable open sockets. This is also the maximum * allowable socket file descriptor. * * Care should be taken before modifying this value for select(): * The API standard doesn't ensure select() accept more than (the system default * of) FD_SETSIZE descriptors, and the default size should in fact be fine in * the vast majority of cases. This constant should therefore be increased only * when absolutely necessary and possible, i.e., the server is exhausting all * available file descriptors (up to FD_SETSIZE) and the select() function * and FD_xxx macros support larger values than FD_SETSIZE (which may not * always by true, but we keep using some of them to ensure as much * portability as possible). Note also that overall server performance * may be rather worsened with a larger value of this constant due to * inherent scalability problems of select(). * * As a special note, this value shouldn't have to be touched if * this is a build for an authoritative only DNS server. */ #ifndef ISC_SOCKET_MAXSOCKETS #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) #ifdef TUNE_LARGE #define ISC_SOCKET_MAXSOCKETS 21000 #else #define ISC_SOCKET_MAXSOCKETS 4096 #endif /* TUNE_LARGE */ #elif defined(USE_SELECT) #define ISC_SOCKET_MAXSOCKETS FD_SETSIZE #endif /* USE_KQUEUE... */ #endif /* ISC_SOCKET_MAXSOCKETS */ #ifdef USE_SELECT /*% * Mac OS X needs a special definition to support larger values in select(). * We always define this because a larger value can be specified run-time. */ #ifdef __APPLE__ #define _DARWIN_UNLIMITED_SELECT #endif /* __APPLE__ */ #endif /* USE_SELECT */ #ifdef ISC_SOCKET_USE_POLLWATCH /*% * If this macro is defined, enable workaround for a Solaris /dev/poll kernel * bug: DP_POLL ioctl could keep sleeping even if socket I/O is possible for * some of the specified FD. The idea is based on the observation that it's * likely for a busy server to keep receiving packets. It specifically works * as follows: the socket watcher is first initialized with the state of * "poll_idle". While it's in the idle state it keeps sleeping until a socket * event occurs. When it wakes up for a socket I/O event, it moves to the * poll_active state, and sets the poll timeout to a short period * (ISC_SOCKET_POLLWATCH_TIMEOUT msec). If timeout occurs in this state, the * watcher goes to the poll_checking state with the same timeout period. * In this state, the watcher tries to detect whether this is a break * during intermittent events or the kernel bug is triggered. If the next * polling reports an event within the short period, the previous timeout is * likely to be a kernel bug, and so the watcher goes back to the active state. * Otherwise, it moves to the idle state again. * * It's not clear whether this is a thread-related bug, but since we've only * seen this with threads, this workaround is used only when enabling threads. */ typedef enum { poll_idle, poll_active, poll_checking } pollstate_t; #ifndef ISC_SOCKET_POLLWATCH_TIMEOUT #define ISC_SOCKET_POLLWATCH_TIMEOUT 10 #endif /* ISC_SOCKET_POLLWATCH_TIMEOUT */ #endif /* ISC_SOCKET_USE_POLLWATCH */ /*% * Size of per-FD lock buckets. */ #ifdef ISC_PLATFORM_USETHREADS #define FDLOCK_COUNT 1024 #define FDLOCK_ID(fd) ((fd) % FDLOCK_COUNT) #else #define FDLOCK_COUNT 1 #define FDLOCK_ID(fd) 0 #endif /* ISC_PLATFORM_USETHREADS */ /*% * Maximum number of events communicated with the kernel. There should normally * be no need for having a large number. */ #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) #ifndef ISC_SOCKET_MAXEVENTS #ifdef TUNE_LARGE #define ISC_SOCKET_MAXEVENTS 2048 #else #define ISC_SOCKET_MAXEVENTS 64 #endif /* TUNE_LARGE */ #endif #endif /*% * Some systems define the socket length argument as an int, some as size_t, * some as socklen_t. This is here so it can be easily changed if needed. */ #ifndef ISC_SOCKADDR_LEN_T #define ISC_SOCKADDR_LEN_T unsigned int #endif /*% * Define what the possible "soft" errors can be. These are non-fatal returns * of various network related functions, like recv() and so on. * * For some reason, BSDI (and perhaps others) will sometimes return <0 * from recv() but will have errno==0. This is broken, but we have to * work around it here. */ #define SOFT_ERROR(e) ((e) == EAGAIN || \ (e) == EWOULDBLOCK || \ (e) == EINTR || \ (e) == 0) #define DLVL(x) ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(x) /*!< * DLVL(90) -- Function entry/exit and other tracing. * DLVL(70) -- Socket "correctness" -- including returning of events, etc. * DLVL(60) -- Socket data send/receive * DLVL(50) -- Event tracing, including receiving/sending completion events. * DLVL(20) -- Socket creation/destruction. */ #define TRACE_LEVEL 90 #define CORRECTNESS_LEVEL 70 #define IOEVENT_LEVEL 60 #define EVENT_LEVEL 50 #define CREATION_LEVEL 20 #define TRACE DLVL(TRACE_LEVEL) #define CORRECTNESS DLVL(CORRECTNESS_LEVEL) #define IOEVENT DLVL(IOEVENT_LEVEL) #define EVENT DLVL(EVENT_LEVEL) #define CREATION DLVL(CREATION_LEVEL) typedef isc_event_t intev_t; #define SOCKET_MAGIC ISC_MAGIC('I', 'O', 'i', 'o') #define VALID_SOCKET(s) ISC_MAGIC_VALID(s, SOCKET_MAGIC) /*! * IPv6 control information. If the socket is an IPv6 socket we want * to collect the destination address and interface so the client can * set them on outgoing packets. */ #ifdef ISC_PLATFORM_HAVEIN6PKTINFO #ifndef USE_CMSG #define USE_CMSG 1 #endif #endif /*% * NetBSD and FreeBSD can timestamp packets. XXXMLG Should we have * a setsockopt() like interface to request timestamps, and if the OS * doesn't do it for us, call gettimeofday() on every UDP receive? */ #ifdef SO_TIMESTAMP #ifndef USE_CMSG #define USE_CMSG 1 #endif #endif /*% * The size to raise the receive buffer to (from BIND 8). */ #ifdef TUNE_LARGE #ifdef sun #define RCVBUFSIZE (1*1024*1024) #else #define RCVBUFSIZE (16*1024*1024) #endif #else #define RCVBUFSIZE (32*1024) #endif /* TUNE_LARGE */ /*% * The number of times a send operation is repeated if the result is EINTR. */ #define NRETRIES 10 typedef struct isc__socket isc__socket_t; typedef struct isc__socketmgr isc__socketmgr_t; #define NEWCONNSOCK(ev) ((isc__socket_t *)(ev)->newsocket) struct isc__socket { /* Not locked. */ isc_socket_t common; isc__socketmgr_t *manager; isc_mutex_t lock; isc_sockettype_t type; const isc_statscounter_t *statsindex; /* Locked by socket lock. */ ISC_LINK(isc__socket_t) link; unsigned int references; int fd; int pf; char name[16]; void * tag; ISC_LIST(isc_socketevent_t) send_list; ISC_LIST(isc_socketevent_t) recv_list; ISC_LIST(isc_socket_newconnev_t) accept_list; isc_socket_connev_t *connect_ev; /* * Internal events. Posted when a descriptor is readable or * writable. These are statically allocated and never freed. * They will be set to non-purgable before use. */ intev_t readable_ev; intev_t writable_ev; isc_sockaddr_t peer_address; /* remote address */ unsigned int pending_recv : 1, pending_send : 1, pending_accept : 1, listener : 1, /* listener socket */ connected : 1, connecting : 1, /* connect pending */ bound : 1, /* bound to local addr */ dupped : 1, active : 1, /* currently active */ pktdscp : 1; /* per packet dscp */ #ifdef ISC_NET_RECVOVERFLOW unsigned char overflow; /* used for MSG_TRUNC fake */ #endif char *recvcmsgbuf; ISC_SOCKADDR_LEN_T recvcmsgbuflen; char *sendcmsgbuf; ISC_SOCKADDR_LEN_T sendcmsgbuflen; void *fdwatcharg; isc_sockfdwatch_t fdwatchcb; int fdwatchflags; isc_task_t *fdwatchtask; unsigned int dscp; }; #define SOCKET_MANAGER_MAGIC ISC_MAGIC('I', 'O', 'm', 'g') #define VALID_MANAGER(m) ISC_MAGIC_VALID(m, SOCKET_MANAGER_MAGIC) struct isc__socketmgr { /* Not locked. */ isc_socketmgr_t common; isc_mem_t *mctx; isc_mutex_t lock; isc_mutex_t *fdlock; isc_stats_t *stats; #ifdef USE_KQUEUE int kqueue_fd; int nevents; struct kevent *events; #endif /* USE_KQUEUE */ #ifdef USE_EPOLL int epoll_fd; int nevents; struct epoll_event *events; #endif /* USE_EPOLL */ #ifdef USE_DEVPOLL int devpoll_fd; isc_resourcevalue_t open_max; unsigned int calls; int nevents; struct pollfd *events; #endif /* USE_DEVPOLL */ #ifdef USE_SELECT int fd_bufsize; #endif /* USE_SELECT */ unsigned int maxsocks; #ifdef ISC_PLATFORM_USETHREADS int pipe_fds[2]; #endif /* Locked by fdlock. */ isc__socket_t **fds; int *fdstate; #ifdef USE_DEVPOLL pollinfo_t *fdpollinfo; #endif /* Locked by manager lock. */ ISC_LIST(isc__socket_t) socklist; #ifdef USE_SELECT fd_set *read_fds; fd_set *read_fds_copy; fd_set *write_fds; fd_set *write_fds_copy; int maxfd; #endif /* USE_SELECT */ int reserved; /* unlocked */ #ifdef USE_WATCHER_THREAD isc_thread_t watcher; isc_condition_t shutdown_ok; #else /* USE_WATCHER_THREAD */ unsigned int refs; #endif /* USE_WATCHER_THREAD */ int maxudp; }; #ifdef USE_SHARED_MANAGER static isc__socketmgr_t *socketmgr = NULL; #endif /* USE_SHARED_MANAGER */ #define CLOSED 0 /* this one must be zero */ #define MANAGED 1 #define CLOSE_PENDING 2 /* * send() and recv() iovec counts */ #define MAXSCATTERGATHER_SEND (ISC_SOCKET_MAXSCATTERGATHER) #ifdef ISC_NET_RECVOVERFLOW # define MAXSCATTERGATHER_RECV (ISC_SOCKET_MAXSCATTERGATHER + 1) #else # define MAXSCATTERGATHER_RECV (ISC_SOCKET_MAXSCATTERGATHER) #endif static isc_result_t socket_create(isc_socketmgr_t *manager0, int pf, isc_sockettype_t type, isc_socket_t **socketp, isc_socket_t *dup_socket); static void send_recvdone_event(isc__socket_t *, isc_socketevent_t **); static void send_senddone_event(isc__socket_t *, isc_socketevent_t **); static void free_socket(isc__socket_t **); static isc_result_t allocate_socket(isc__socketmgr_t *, isc_sockettype_t, isc__socket_t **); static void destroy(isc__socket_t **); static void internal_accept(isc_task_t *, isc_event_t *); static void internal_connect(isc_task_t *, isc_event_t *); static void internal_recv(isc_task_t *, isc_event_t *); static void internal_send(isc_task_t *, isc_event_t *); static void internal_fdwatch_write(isc_task_t *, isc_event_t *); static void internal_fdwatch_read(isc_task_t *, isc_event_t *); static void process_cmsg(isc__socket_t *, struct msghdr *, isc_socketevent_t *); static void build_msghdr_send(isc__socket_t *, isc_socketevent_t *, struct msghdr *, struct iovec *, size_t *); static void build_msghdr_recv(isc__socket_t *, isc_socketevent_t *, struct msghdr *, struct iovec *, size_t *); #ifdef USE_WATCHER_THREAD static isc_boolean_t process_ctlfd(isc__socketmgr_t *manager); #endif static void setdscp(isc__socket_t *sock, isc_dscp_t dscp); /*% * The following are intended for internal use (indicated by "isc__" * prefix) but are not declared as static, allowing direct access from * unit tests etc. */ isc_result_t isc__socket_open(isc_socket_t *sock0); isc_result_t isc__socket_close(isc_socket_t *sock0); isc_result_t isc__socket_create(isc_socketmgr_t *manager, int pf, isc_sockettype_t type, isc_socket_t **socketp); void isc__socket_attach(isc_socket_t *sock, isc_socket_t **socketp); void isc__socket_detach(isc_socket_t **socketp); isc_result_t isc__socket_recvv(isc_socket_t *sock, isc_bufferlist_t *buflist, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc__socket_recv(isc_socket_t *sock, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc__socket_recv2(isc_socket_t *sock, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_socketevent_t *event, unsigned int flags); isc_result_t isc__socket_send(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc__socket_sendto(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo); isc_result_t isc__socket_sendv(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc__socket_sendtov(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo); isc_result_t isc__socket_sendtov2(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, unsigned int flags); isc_result_t isc__socket_sendto2(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, isc_socketevent_t *event, unsigned int flags); isc_socketevent_t * isc_socket_socketevent(isc_mem_t *mctx, void *sender, isc_eventtype_t eventtype, isc_taskaction_t action, void *arg); void isc__socket_cleanunix(isc_sockaddr_t *sockaddr, isc_boolean_t active); isc_result_t isc__socket_permunix(isc_sockaddr_t *sockaddr, isc_uint32_t perm, isc_uint32_t owner, isc_uint32_t group); isc_result_t isc__socket_bind(isc_socket_t *sock, isc_sockaddr_t *sockaddr, unsigned int options); isc_result_t isc__socket_filter(isc_socket_t *sock, const char *filter); isc_result_t isc__socket_listen(isc_socket_t *sock, unsigned int backlog); isc_result_t isc__socket_accept(isc_socket_t *sock, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc__socket_connect(isc_socket_t *sock, isc_sockaddr_t *addr, isc_task_t *task, isc_taskaction_t action, void *arg); isc_result_t isc__socket_getpeername(isc_socket_t *sock, isc_sockaddr_t *addressp); isc_result_t isc__socket_getsockname(isc_socket_t *sock, isc_sockaddr_t *addressp); void isc__socket_cancel(isc_socket_t *sock, isc_task_t *task, unsigned int how); isc_sockettype_t isc__socket_gettype(isc_socket_t *sock); isc_boolean_t isc__socket_isbound(isc_socket_t *sock); void isc__socket_ipv6only(isc_socket_t *sock, isc_boolean_t yes); void isc__socket_dscp(isc_socket_t *sock, isc_dscp_t dscp); isc_result_t isc__socket_fdwatchcreate(isc_socketmgr_t *manager, int fd, int flags, isc_sockfdwatch_t callback, void *cbarg, isc_task_t *task, isc_socket_t **socketp); isc_result_t isc__socket_fdwatchpoke(isc_socket_t *sock, int flags); isc_result_t isc__socket_dup(isc_socket_t *sock, isc_socket_t **socketp); int isc__socket_getfd(isc_socket_t *sock); isc_result_t isc__socketmgr_create(isc_mem_t *mctx, isc_socketmgr_t **managerp); isc_result_t isc__socketmgr_create2(isc_mem_t *mctx, isc_socketmgr_t **managerp, unsigned int maxsocks); isc_result_t isc_socketmgr_getmaxsockets(isc_socketmgr_t *manager0, unsigned int *nsockp); void isc_socketmgr_setstats(isc_socketmgr_t *manager0, isc_stats_t *stats); void isc__socketmgr_destroy(isc_socketmgr_t **managerp); void isc__socket_setname(isc_socket_t *socket0, const char *name, void *tag); const char * isc__socket_getname(isc_socket_t *socket0); void * isc__socket_gettag(isc_socket_t *socket0); #ifdef HAVE_LIBXML2 void isc__socketmgr_renderxml(isc_socketmgr_t *mgr0, xmlTextWriterPtr writer); #endif #ifdef HAVE_JSON isc_result_t isc__socketmgr_renderjson(isc_socketmgr_t *mgr0, json_object *stats); #endif static struct { isc_socketmethods_t methods; /*% * The following are defined just for avoiding unused static functions. */ void *recvv, *send, *sendv, *sendto2, *cleanunix, *permunix, *filter, *listen, *accept, *getpeername, *isbound; } socketmethods = { { isc__socket_attach, isc__socket_detach, isc__socket_bind, isc__socket_sendto, isc__socket_sendto2, isc__socket_connect, isc__socket_recv, isc__socket_recv2, isc__socket_cancel, isc__socket_getsockname, isc__socket_gettype, isc__socket_ipv6only, isc__socket_fdwatchpoke, isc__socket_dup, isc__socket_getfd, isc__socket_dscp }, (void *)isc__socket_recvv, (void *)isc__socket_send, (void *)isc__socket_sendv, (void *)isc__socket_sendto2, (void *)isc__socket_cleanunix, (void *)isc__socket_permunix, (void *)isc__socket_filter, (void *)isc__socket_listen, (void *)isc__socket_accept, (void *)isc__socket_getpeername, (void *)isc__socket_isbound }; static isc_socketmgrmethods_t socketmgrmethods = { isc__socketmgr_destroy, isc__socket_create, isc__socket_fdwatchcreate }; #define SELECT_POKE_SHUTDOWN (-1) #define SELECT_POKE_NOTHING (-2) #define SELECT_POKE_READ (-3) #define SELECT_POKE_ACCEPT (-3) /*%< Same as _READ */ #define SELECT_POKE_WRITE (-4) #define SELECT_POKE_CONNECT (-4) /*%< Same as _WRITE */ #define SELECT_POKE_CLOSE (-5) #define SOCK_DEAD(s) ((s)->references == 0) /*% * Shortcut index arrays to get access to statistics counters. */ enum { STATID_OPEN = 0, STATID_OPENFAIL = 1, STATID_CLOSE = 2, STATID_BINDFAIL = 3, STATID_CONNECTFAIL = 4, STATID_CONNECT = 5, STATID_ACCEPTFAIL = 6, STATID_ACCEPT = 7, STATID_SENDFAIL = 8, STATID_RECVFAIL = 9, STATID_ACTIVE = 10 }; static const isc_statscounter_t udp4statsindex[] = { isc_sockstatscounter_udp4open, isc_sockstatscounter_udp4openfail, isc_sockstatscounter_udp4close, isc_sockstatscounter_udp4bindfail, isc_sockstatscounter_udp4connectfail, isc_sockstatscounter_udp4connect, -1, -1, isc_sockstatscounter_udp4sendfail, isc_sockstatscounter_udp4recvfail, isc_sockstatscounter_udp4active }; static const isc_statscounter_t udp6statsindex[] = { isc_sockstatscounter_udp6open, isc_sockstatscounter_udp6openfail, isc_sockstatscounter_udp6close, isc_sockstatscounter_udp6bindfail, isc_sockstatscounter_udp6connectfail, isc_sockstatscounter_udp6connect, -1, -1, isc_sockstatscounter_udp6sendfail, isc_sockstatscounter_udp6recvfail, isc_sockstatscounter_udp6active }; static const isc_statscounter_t tcp4statsindex[] = { isc_sockstatscounter_tcp4open, isc_sockstatscounter_tcp4openfail, isc_sockstatscounter_tcp4close, isc_sockstatscounter_tcp4bindfail, isc_sockstatscounter_tcp4connectfail, isc_sockstatscounter_tcp4connect, isc_sockstatscounter_tcp4acceptfail, isc_sockstatscounter_tcp4accept, isc_sockstatscounter_tcp4sendfail, isc_sockstatscounter_tcp4recvfail, isc_sockstatscounter_tcp4active }; static const isc_statscounter_t tcp6statsindex[] = { isc_sockstatscounter_tcp6open, isc_sockstatscounter_tcp6openfail, isc_sockstatscounter_tcp6close, isc_sockstatscounter_tcp6bindfail, isc_sockstatscounter_tcp6connectfail, isc_sockstatscounter_tcp6connect, isc_sockstatscounter_tcp6acceptfail, isc_sockstatscounter_tcp6accept, isc_sockstatscounter_tcp6sendfail, isc_sockstatscounter_tcp6recvfail, isc_sockstatscounter_tcp6active }; static const isc_statscounter_t unixstatsindex[] = { isc_sockstatscounter_unixopen, isc_sockstatscounter_unixopenfail, isc_sockstatscounter_unixclose, isc_sockstatscounter_unixbindfail, isc_sockstatscounter_unixconnectfail, isc_sockstatscounter_unixconnect, isc_sockstatscounter_unixacceptfail, isc_sockstatscounter_unixaccept, isc_sockstatscounter_unixsendfail, isc_sockstatscounter_unixrecvfail, isc_sockstatscounter_unixactive }; static const isc_statscounter_t fdwatchstatsindex[] = { -1, -1, isc_sockstatscounter_fdwatchclose, isc_sockstatscounter_fdwatchbindfail, isc_sockstatscounter_fdwatchconnectfail, isc_sockstatscounter_fdwatchconnect, -1, -1, isc_sockstatscounter_fdwatchsendfail, isc_sockstatscounter_fdwatchrecvfail, -1 }; static const isc_statscounter_t rawstatsindex[] = { isc_sockstatscounter_rawopen, isc_sockstatscounter_rawopenfail, isc_sockstatscounter_rawclose, -1, -1, -1, -1, -1, -1, isc_sockstatscounter_rawrecvfail, isc_sockstatscounter_rawactive }; #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) || \ defined(USE_WATCHER_THREAD) static void manager_log(isc__socketmgr_t *sockmgr, isc_logcategory_t *category, isc_logmodule_t *module, int level, const char *fmt, ...) ISC_FORMAT_PRINTF(5, 6); static void manager_log(isc__socketmgr_t *sockmgr, isc_logcategory_t *category, isc_logmodule_t *module, int level, const char *fmt, ...) { char msgbuf[2048]; va_list ap; if (! isc_log_wouldlog(isc_lctx, level)) return; va_start(ap, fmt); vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap); va_end(ap); isc_log_write(isc_lctx, category, module, level, "sockmgr %p: %s", sockmgr, msgbuf); } #endif static void socket_log(isc__socket_t *sock, isc_sockaddr_t *address, isc_logcategory_t *category, isc_logmodule_t *module, int level, isc_msgcat_t *msgcat, int msgset, int message, const char *fmt, ...) ISC_FORMAT_PRINTF(9, 10); static void socket_log(isc__socket_t *sock, isc_sockaddr_t *address, isc_logcategory_t *category, isc_logmodule_t *module, int level, isc_msgcat_t *msgcat, int msgset, int message, const char *fmt, ...) { char msgbuf[2048]; char peerbuf[ISC_SOCKADDR_FORMATSIZE]; va_list ap; if (! isc_log_wouldlog(isc_lctx, level)) return; va_start(ap, fmt); vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap); va_end(ap); if (address == NULL) { isc_log_iwrite(isc_lctx, category, module, level, msgcat, msgset, message, "socket %p: %s", sock, msgbuf); } else { isc_sockaddr_format(address, peerbuf, sizeof(peerbuf)); isc_log_iwrite(isc_lctx, category, module, level, msgcat, msgset, message, "socket %p %s: %s", sock, peerbuf, msgbuf); } } #if defined(_AIX) && defined(ISC_NET_BSD44MSGHDR) && \ defined(USE_CMSG) && defined(IPV6_RECVPKTINFO) /* * AIX has a kernel bug where IPV6_RECVPKTINFO gets cleared by * setting IPV6_V6ONLY. */ static void FIX_IPV6_RECVPKTINFO(isc__socket_t *sock) { char strbuf[ISC_STRERRORSIZE]; int on = 1; if (sock->pf != AF_INET6 || sock->type != isc_sockettype_udp) return; if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *)&on, sizeof(on)) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_RECVPKTINFO) " "%s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } } #else #define FIX_IPV6_RECVPKTINFO(sock) (void)0 #endif /*% * Increment socket-related statistics counters. */ static inline void inc_stats(isc_stats_t *stats, isc_statscounter_t counterid) { REQUIRE(counterid != -1); if (stats != NULL) isc_stats_increment(stats, counterid); } /*% * Decrement socket-related statistics counters. */ static inline void dec_stats(isc_stats_t *stats, isc_statscounter_t counterid) { REQUIRE(counterid != -1); if (stats != NULL) isc_stats_decrement(stats, counterid); } static inline isc_result_t watch_fd(isc__socketmgr_t *manager, int fd, int msg) { isc_result_t result = ISC_R_SUCCESS; #ifdef USE_KQUEUE struct kevent evchange; memset(&evchange, 0, sizeof(evchange)); if (msg == SELECT_POKE_READ) evchange.filter = EVFILT_READ; else evchange.filter = EVFILT_WRITE; evchange.flags = EV_ADD; evchange.ident = fd; if (kevent(manager->kqueue_fd, &evchange, 1, NULL, 0, NULL) != 0) result = isc__errno2result(errno); return (result); #elif defined(USE_EPOLL) struct epoll_event event; if (msg == SELECT_POKE_READ) event.events = EPOLLIN; else event.events = EPOLLOUT; memset(&event.data, 0, sizeof(event.data)); event.data.fd = fd; if (epoll_ctl(manager->epoll_fd, EPOLL_CTL_ADD, fd, &event) == -1 && errno != EEXIST) { result = isc__errno2result(errno); } return (result); #elif defined(USE_DEVPOLL) struct pollfd pfd; int lockid = FDLOCK_ID(fd); memset(&pfd, 0, sizeof(pfd)); if (msg == SELECT_POKE_READ) pfd.events = POLLIN; else pfd.events = POLLOUT; pfd.fd = fd; pfd.revents = 0; LOCK(&manager->fdlock[lockid]); if (write(manager->devpoll_fd, &pfd, sizeof(pfd)) == -1) result = isc__errno2result(errno); else { if (msg == SELECT_POKE_READ) manager->fdpollinfo[fd].want_read = 1; else manager->fdpollinfo[fd].want_write = 1; } UNLOCK(&manager->fdlock[lockid]); return (result); #elif defined(USE_SELECT) LOCK(&manager->lock); if (msg == SELECT_POKE_READ) FD_SET(fd, manager->read_fds); if (msg == SELECT_POKE_WRITE) FD_SET(fd, manager->write_fds); UNLOCK(&manager->lock); return (result); #endif } static inline isc_result_t unwatch_fd(isc__socketmgr_t *manager, int fd, int msg) { isc_result_t result = ISC_R_SUCCESS; #ifdef USE_KQUEUE struct kevent evchange; memset(&evchange, 0, sizeof(evchange)); if (msg == SELECT_POKE_READ) evchange.filter = EVFILT_READ; else evchange.filter = EVFILT_WRITE; evchange.flags = EV_DELETE; evchange.ident = fd; if (kevent(manager->kqueue_fd, &evchange, 1, NULL, 0, NULL) != 0) result = isc__errno2result(errno); return (result); #elif defined(USE_EPOLL) struct epoll_event event; if (msg == SELECT_POKE_READ) event.events = EPOLLIN; else event.events = EPOLLOUT; memset(&event.data, 0, sizeof(event.data)); event.data.fd = fd; if (epoll_ctl(manager->epoll_fd, EPOLL_CTL_DEL, fd, &event) == -1 && errno != ENOENT) { char strbuf[ISC_STRERRORSIZE]; isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "epoll_ctl(DEL), %d: %s", fd, strbuf); result = ISC_R_UNEXPECTED; } return (result); #elif defined(USE_DEVPOLL) struct pollfd pfds[2]; size_t writelen = sizeof(pfds[0]); int lockid = FDLOCK_ID(fd); memset(pfds, 0, sizeof(pfds)); pfds[0].events = POLLREMOVE; pfds[0].fd = fd; /* * Canceling read or write polling via /dev/poll is tricky. Since it * only provides a way of canceling per FD, we may need to re-poll the * socket for the other operation. */ LOCK(&manager->fdlock[lockid]); if (msg == SELECT_POKE_READ && manager->fdpollinfo[fd].want_write == 1) { pfds[1].events = POLLOUT; pfds[1].fd = fd; writelen += sizeof(pfds[1]); } if (msg == SELECT_POKE_WRITE && manager->fdpollinfo[fd].want_read == 1) { pfds[1].events = POLLIN; pfds[1].fd = fd; writelen += sizeof(pfds[1]); } if (write(manager->devpoll_fd, pfds, writelen) == -1) result = isc__errno2result(errno); else { if (msg == SELECT_POKE_READ) manager->fdpollinfo[fd].want_read = 0; else manager->fdpollinfo[fd].want_write = 0; } UNLOCK(&manager->fdlock[lockid]); return (result); #elif defined(USE_SELECT) LOCK(&manager->lock); if (msg == SELECT_POKE_READ) FD_CLR(fd, manager->read_fds); else if (msg == SELECT_POKE_WRITE) FD_CLR(fd, manager->write_fds); UNLOCK(&manager->lock); return (result); #endif } static void wakeup_socket(isc__socketmgr_t *manager, int fd, int msg) { isc_result_t result; int lockid = FDLOCK_ID(fd); /* * This is a wakeup on a socket. If the socket is not in the * process of being closed, start watching it for either reads * or writes. */ INSIST(fd >= 0 && fd < (int)manager->maxsocks); if (msg == SELECT_POKE_CLOSE) { /* No one should be updating fdstate, so no need to lock it */ INSIST(manager->fdstate[fd] == CLOSE_PENDING); manager->fdstate[fd] = CLOSED; (void)unwatch_fd(manager, fd, SELECT_POKE_READ); (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE); (void)close(fd); return; } LOCK(&manager->fdlock[lockid]); if (manager->fdstate[fd] == CLOSE_PENDING) { UNLOCK(&manager->fdlock[lockid]); /* * We accept (and ignore) any error from unwatch_fd() as we are * closing the socket, hoping it doesn't leave dangling state in * the kernel. * Note that unwatch_fd() must be called after releasing the * fdlock; otherwise it could cause deadlock due to a lock order * reversal. */ (void)unwatch_fd(manager, fd, SELECT_POKE_READ); (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE); return; } if (manager->fdstate[fd] != MANAGED) { UNLOCK(&manager->fdlock[lockid]); return; } UNLOCK(&manager->fdlock[lockid]); /* * Set requested bit. */ result = watch_fd(manager, fd, msg); if (result != ISC_R_SUCCESS) { /* * XXXJT: what should we do? Ignoring the failure of watching * a socket will make the application dysfunctional, but there * seems to be no reasonable recovery process. */ isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, "failed to start watching FD (%d): %s", fd, isc_result_totext(result)); } } #ifdef USE_WATCHER_THREAD /* * Poke the select loop when there is something for us to do. * The write is required (by POSIX) to complete. That is, we * will not get partial writes. */ static void select_poke(isc__socketmgr_t *mgr, int fd, int msg) { int cc; int buf[2]; char strbuf[ISC_STRERRORSIZE]; buf[0] = fd; buf[1] = msg; do { cc = write(mgr->pipe_fds[1], buf, sizeof(buf)); #ifdef ENOSR /* * Treat ENOSR as EAGAIN but loop slowly as it is * unlikely to clear fast. */ if (cc < 0 && errno == ENOSR) { sleep(1); errno = EAGAIN; } #endif } while (cc < 0 && SOFT_ERROR(errno)); if (cc < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); FATAL_ERROR(__FILE__, __LINE__, isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_WRITEFAILED, "write() failed " "during watcher poke: %s"), strbuf); } INSIST(cc == sizeof(buf)); } /* * Read a message on the internal fd. */ static void select_readmsg(isc__socketmgr_t *mgr, int *fd, int *msg) { int buf[2]; int cc; char strbuf[ISC_STRERRORSIZE]; cc = read(mgr->pipe_fds[0], buf, sizeof(buf)); if (cc < 0) { *msg = SELECT_POKE_NOTHING; *fd = -1; /* Silence compiler. */ if (SOFT_ERROR(errno)) return; isc__strerror(errno, strbuf, sizeof(strbuf)); FATAL_ERROR(__FILE__, __LINE__, isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_READFAILED, "read() failed " "during watcher poke: %s"), strbuf); } INSIST(cc == sizeof(buf)); *fd = buf[0]; *msg = buf[1]; } #else /* USE_WATCHER_THREAD */ /* * Update the state of the socketmgr when something changes. */ static void select_poke(isc__socketmgr_t *manager, int fd, int msg) { if (msg == SELECT_POKE_SHUTDOWN) return; else if (fd >= 0) wakeup_socket(manager, fd, msg); return; } #endif /* USE_WATCHER_THREAD */ /* * Make a fd non-blocking. */ static isc_result_t make_nonblock(int fd) { int ret; int flags; char strbuf[ISC_STRERRORSIZE]; #ifdef USE_FIONBIO_IOCTL int on = 1; ret = ioctl(fd, FIONBIO, (char *)&on); #else flags = fcntl(fd, F_GETFL, 0); flags |= PORT_NONBLOCK; ret = fcntl(fd, F_SETFL, flags); #endif if (ret == -1) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, #ifdef USE_FIONBIO_IOCTL "ioctl(%d, FIONBIO, &on): %s", fd, #else "fcntl(%d, F_SETFL, %d): %s", fd, flags, #endif strbuf); return (ISC_R_UNEXPECTED); } return (ISC_R_SUCCESS); } #ifdef USE_CMSG /* * Not all OSes support advanced CMSG macros: CMSG_LEN and CMSG_SPACE. * In order to ensure as much portability as possible, we provide wrapper * functions of these macros. * Note that cmsg_space() could run slow on OSes that do not have * CMSG_SPACE. */ static inline ISC_SOCKADDR_LEN_T cmsg_len(ISC_SOCKADDR_LEN_T len) { #ifdef CMSG_LEN return (CMSG_LEN(len)); #else ISC_SOCKADDR_LEN_T hdrlen; /* * Cast NULL so that any pointer arithmetic performed by CMSG_DATA * is correct. */ hdrlen = (ISC_SOCKADDR_LEN_T)CMSG_DATA(((struct cmsghdr *)NULL)); return (hdrlen + len); #endif } static inline ISC_SOCKADDR_LEN_T cmsg_space(ISC_SOCKADDR_LEN_T len) { #ifdef CMSG_SPACE return (CMSG_SPACE(len)); #else struct msghdr msg; struct cmsghdr *cmsgp; /* * XXX: The buffer length is an ad-hoc value, but should be enough * in a practical sense. */ char dummybuf[sizeof(struct cmsghdr) + 1024]; memset(&msg, 0, sizeof(msg)); msg.msg_control = dummybuf; msg.msg_controllen = sizeof(dummybuf); cmsgp = (struct cmsghdr *)dummybuf; cmsgp->cmsg_len = cmsg_len(len); cmsgp = CMSG_NXTHDR(&msg, cmsgp); if (cmsgp != NULL) return ((char *)cmsgp - (char *)msg.msg_control); else return (0); #endif } #endif /* USE_CMSG */ /* * Process control messages received on a socket. */ static void process_cmsg(isc__socket_t *sock, struct msghdr *msg, isc_socketevent_t *dev) { #ifdef USE_CMSG struct cmsghdr *cmsgp; #ifdef ISC_PLATFORM_HAVEIN6PKTINFO struct in6_pktinfo *pktinfop; #endif #ifdef SO_TIMESTAMP void *timevalp; #endif #endif /* * sock is used only when ISC_NET_BSD44MSGHDR and USE_CMSG are defined. * msg and dev are used only when ISC_NET_BSD44MSGHDR is defined. * They are all here, outside of the CPP tests, because it is * more consistent with the usual ISC coding style. */ UNUSED(sock); UNUSED(msg); UNUSED(dev); #ifdef ISC_NET_BSD44MSGHDR #ifdef MSG_TRUNC if ((msg->msg_flags & MSG_TRUNC) == MSG_TRUNC) dev->attributes |= ISC_SOCKEVENTATTR_TRUNC; #endif #ifdef MSG_CTRUNC if ((msg->msg_flags & MSG_CTRUNC) == MSG_CTRUNC) dev->attributes |= ISC_SOCKEVENTATTR_CTRUNC; #endif #ifndef USE_CMSG return; #else if (msg->msg_controllen == 0U || msg->msg_control == NULL) return; #ifdef SO_TIMESTAMP timevalp = NULL; #endif #ifdef ISC_PLATFORM_HAVEIN6PKTINFO pktinfop = NULL; #endif cmsgp = CMSG_FIRSTHDR(msg); while (cmsgp != NULL) { socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PROCESSCMSG, "processing cmsg %p", cmsgp); #ifdef ISC_PLATFORM_HAVEIN6PKTINFO if (cmsgp->cmsg_level == IPPROTO_IPV6 && cmsgp->cmsg_type == IPV6_PKTINFO) { pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp); memmove(&dev->pktinfo, pktinfop, sizeof(struct in6_pktinfo)); dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO; socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_IFRECEIVED, "interface received on ifindex %u", dev->pktinfo.ipi6_ifindex); if (IN6_IS_ADDR_MULTICAST(&pktinfop->ipi6_addr)) dev->attributes |= ISC_SOCKEVENTATTR_MULTICAST; goto next; } #endif #ifdef SO_TIMESTAMP if (cmsgp->cmsg_level == SOL_SOCKET && cmsgp->cmsg_type == SCM_TIMESTAMP) { struct timeval tv; timevalp = CMSG_DATA(cmsgp); memmove(&tv, timevalp, sizeof(tv)); dev->timestamp.seconds = tv.tv_sec; dev->timestamp.nanoseconds = tv.tv_usec * 1000; dev->attributes |= ISC_SOCKEVENTATTR_TIMESTAMP; goto next; } #endif #ifdef IPV6_TCLASS if (cmsgp->cmsg_level == IPPROTO_IPV6 && cmsgp->cmsg_type == IPV6_TCLASS) { dev->dscp = *(int *)CMSG_DATA(cmsgp); dev->dscp >>= 2; dev->attributes |= ISC_SOCKEVENTATTR_DSCP; goto next; } #endif #ifdef IP_TOS if (cmsgp->cmsg_level == IPPROTO_IP && (cmsgp->cmsg_type == IP_TOS #ifdef IP_RECVTOS || cmsgp->cmsg_type == IP_RECVTOS #endif )) { dev->dscp = (int) *(unsigned char *)CMSG_DATA(cmsgp); dev->dscp >>= 2; dev->attributes |= ISC_SOCKEVENTATTR_DSCP; goto next; } #endif next: cmsgp = CMSG_NXTHDR(msg, cmsgp); } #endif /* USE_CMSG */ #endif /* ISC_NET_BSD44MSGHDR */ } /* * Construct an iov array and attach it to the msghdr passed in. This is * the SEND constructor, which will use the used region of the buffer * (if using a buffer list) or will use the internal region (if a single * buffer I/O is requested). * * Nothing can be NULL, and the done event must list at least one buffer * on the buffer linked list for this function to be meaningful. * * If write_countp != NULL, *write_countp will hold the number of bytes * this transaction can send. */ static void build_msghdr_send(isc__socket_t *sock, isc_socketevent_t *dev, struct msghdr *msg, struct iovec *iov, size_t *write_countp) { unsigned int iovcount; isc_buffer_t *buffer; isc_region_t used; size_t write_count; size_t skip_count; #ifdef ISC_NET_BSD44MSGHDR struct cmsghdr *cmsgp; #endif memset(msg, 0, sizeof(*msg)); if (!sock->connected) { msg->msg_name = (void *)&dev->address.type.sa; msg->msg_namelen = dev->address.length; } else { msg->msg_name = NULL; msg->msg_namelen = 0; } buffer = ISC_LIST_HEAD(dev->bufferlist); write_count = 0; iovcount = 0; /* * Single buffer I/O? Skip what we've done so far in this region. */ if (buffer == NULL) { write_count = dev->region.length - dev->n; iov[0].iov_base = (void *)(dev->region.base + dev->n); iov[0].iov_len = write_count; iovcount = 1; goto config; } /* * Multibuffer I/O. * Skip the data in the buffer list that we have already written. */ skip_count = dev->n; while (buffer != NULL) { REQUIRE(ISC_BUFFER_VALID(buffer)); if (skip_count < isc_buffer_usedlength(buffer)) break; skip_count -= isc_buffer_usedlength(buffer); buffer = ISC_LIST_NEXT(buffer, link); } while (buffer != NULL) { INSIST(iovcount < MAXSCATTERGATHER_SEND); isc_buffer_usedregion(buffer, &used); if (used.length > 0) { iov[iovcount].iov_base = (void *)(used.base + skip_count); iov[iovcount].iov_len = used.length - skip_count; write_count += (used.length - skip_count); skip_count = 0; iovcount++; } buffer = ISC_LIST_NEXT(buffer, link); } INSIST(skip_count == 0U); config: msg->msg_iov = iov; msg->msg_iovlen = iovcount; #ifdef ISC_NET_BSD44MSGHDR msg->msg_control = NULL; msg->msg_controllen = 0; msg->msg_flags = 0; #if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIN6PKTINFO) if ((sock->type == isc_sockettype_udp) && ((dev->attributes & ISC_SOCKEVENTATTR_PKTINFO) != 0)) { #if defined(IPV6_USE_MIN_MTU) int use_min_mtu = 1; /* -1, 0, 1 */ #endif struct in6_pktinfo *pktinfop; socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_SENDTODATA, "sendto pktinfo data, ifindex %u", dev->pktinfo.ipi6_ifindex); msg->msg_controllen = cmsg_space(sizeof(struct in6_pktinfo)); INSIST(msg->msg_controllen <= sock->sendcmsgbuflen); msg->msg_control = (void *)sock->sendcmsgbuf; cmsgp = (struct cmsghdr *)sock->sendcmsgbuf; cmsgp->cmsg_level = IPPROTO_IPV6; cmsgp->cmsg_type = IPV6_PKTINFO; cmsgp->cmsg_len = cmsg_len(sizeof(struct in6_pktinfo)); pktinfop = (struct in6_pktinfo *)CMSG_DATA(cmsgp); memmove(pktinfop, &dev->pktinfo, sizeof(struct in6_pktinfo)); #if defined(IPV6_USE_MIN_MTU) /* * Set IPV6_USE_MIN_MTU as a per packet option as FreeBSD * ignores setsockopt(IPV6_USE_MIN_MTU) when IPV6_PKTINFO * is used. */ cmsgp = (struct cmsghdr *)(sock->sendcmsgbuf + msg->msg_controllen); msg->msg_controllen += cmsg_space(sizeof(use_min_mtu)); INSIST(msg->msg_controllen <= sock->sendcmsgbuflen); cmsgp->cmsg_level = IPPROTO_IPV6; cmsgp->cmsg_type = IPV6_USE_MIN_MTU; cmsgp->cmsg_len = cmsg_len(sizeof(use_min_mtu)); memmove(CMSG_DATA(cmsgp), &use_min_mtu, sizeof(use_min_mtu)); #endif } if (isc_dscp_check_value > -1) { if (sock->type == isc_sockettype_udp) INSIST((int)dev->dscp == isc_dscp_check_value); else if (sock->type == isc_sockettype_tcp) INSIST((int)sock->dscp == isc_dscp_check_value); } if ((sock->type == isc_sockettype_udp) && ((dev->attributes & ISC_SOCKEVENTATTR_DSCP) != 0)) { int dscp = (dev->dscp << 2) & 0xff; INSIST(dev->dscp < 0x40); #ifdef IP_TOS if (sock->pf == AF_INET && sock->pktdscp) { cmsgp = (struct cmsghdr *)(sock->sendcmsgbuf + msg->msg_controllen); msg->msg_control = (void *)sock->sendcmsgbuf; msg->msg_controllen += cmsg_space(sizeof(dscp)); INSIST(msg->msg_controllen <= sock->sendcmsgbuflen); cmsgp->cmsg_level = IPPROTO_IP; cmsgp->cmsg_type = IP_TOS; cmsgp->cmsg_len = cmsg_len(sizeof(char)); *(unsigned char*)CMSG_DATA(cmsgp) = dscp; } else if (sock->pf == AF_INET && sock->dscp != dev->dscp) { if (setsockopt(sock->fd, IPPROTO_IP, IP_TOS, (void *)&dscp, sizeof(int)) < 0) { char strbuf[ISC_STRERRORSIZE]; isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IP_TOS, %.02x)" " %s: %s", sock->fd, dscp >> 2, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } else sock->dscp = dscp; } #endif #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) if (sock->pf == AF_INET6 && sock->pktdscp) { cmsgp = (struct cmsghdr *)(sock->sendcmsgbuf + msg->msg_controllen); msg->msg_control = (void *)sock->sendcmsgbuf; msg->msg_controllen += cmsg_space(sizeof(dscp)); INSIST(msg->msg_controllen <= sock->sendcmsgbuflen); cmsgp->cmsg_level = IPPROTO_IPV6; cmsgp->cmsg_type = IPV6_TCLASS; cmsgp->cmsg_len = cmsg_len(sizeof(dscp)); memmove(CMSG_DATA(cmsgp), &dscp, sizeof(dscp)); } else if (sock->pf == AF_INET6 && sock->dscp != dev->dscp) { if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_TCLASS, (void *)&dscp, sizeof(int)) < 0) { char strbuf[ISC_STRERRORSIZE]; isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_TCLASS, " "%.02x) %s: %s", sock->fd, dscp >> 2, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } else sock->dscp = dscp; } #endif } #endif /* USE_CMSG && ISC_PLATFORM_HAVEIPV6 */ #else /* ISC_NET_BSD44MSGHDR */ msg->msg_accrights = NULL; msg->msg_accrightslen = 0; #endif /* ISC_NET_BSD44MSGHDR */ if (write_countp != NULL) *write_countp = write_count; } /* * Construct an iov array and attach it to the msghdr passed in. This is * the RECV constructor, which will use the available region of the buffer * (if using a buffer list) or will use the internal region (if a single * buffer I/O is requested). * * Nothing can be NULL, and the done event must list at least one buffer * on the buffer linked list for this function to be meaningful. * * If read_countp != NULL, *read_countp will hold the number of bytes * this transaction can receive. */ static void build_msghdr_recv(isc__socket_t *sock, isc_socketevent_t *dev, struct msghdr *msg, struct iovec *iov, size_t *read_countp) { unsigned int iovcount; isc_buffer_t *buffer; isc_region_t available; size_t read_count; memset(msg, 0, sizeof(struct msghdr)); if (sock->type == isc_sockettype_udp) { memset(&dev->address, 0, sizeof(dev->address)); #ifdef BROKEN_RECVMSG if (sock->pf == AF_INET) { msg->msg_name = (void *)&dev->address.type.sin; msg->msg_namelen = sizeof(dev->address.type.sin6); } else if (sock->pf == AF_INET6) { msg->msg_name = (void *)&dev->address.type.sin6; msg->msg_namelen = sizeof(dev->address.type.sin6); #ifdef ISC_PLATFORM_HAVESYSUNH } else if (sock->pf == AF_UNIX) { msg->msg_name = (void *)&dev->address.type.sunix; msg->msg_namelen = sizeof(dev->address.type.sunix); #endif } else { msg->msg_name = (void *)&dev->address.type.sa; msg->msg_namelen = sizeof(dev->address.type); } #else msg->msg_name = (void *)&dev->address.type.sa; msg->msg_namelen = sizeof(dev->address.type); #endif #ifdef ISC_NET_RECVOVERFLOW /* If needed, steal one iovec for overflow detection. */ maxiov--; #endif } else { /* TCP */ msg->msg_name = NULL; msg->msg_namelen = 0; dev->address = sock->peer_address; } buffer = ISC_LIST_HEAD(dev->bufferlist); read_count = 0; /* * Single buffer I/O? Skip what we've done so far in this region. */ if (buffer == NULL) { read_count = dev->region.length - dev->n; iov[0].iov_base = (void *)(dev->region.base + dev->n); iov[0].iov_len = read_count; iovcount = 1; goto config; } /* * Multibuffer I/O. * Skip empty buffers. */ while (buffer != NULL) { REQUIRE(ISC_BUFFER_VALID(buffer)); if (isc_buffer_availablelength(buffer) != 0) break; buffer = ISC_LIST_NEXT(buffer, link); } iovcount = 0; while (buffer != NULL) { INSIST(iovcount < MAXSCATTERGATHER_RECV); isc_buffer_availableregion(buffer, &available); if (available.length > 0) { iov[iovcount].iov_base = (void *)(available.base); iov[iovcount].iov_len = available.length; read_count += available.length; iovcount++; } buffer = ISC_LIST_NEXT(buffer, link); } config: /* * If needed, set up to receive that one extra byte. Note that * we know there is at least one iov left, since we stole it * at the top of this function. */ #ifdef ISC_NET_RECVOVERFLOW if (sock->type == isc_sockettype_udp) { iov[iovcount].iov_base = (void *)(&sock->overflow); iov[iovcount].iov_len = 1; iovcount++; } #endif msg->msg_iov = iov; msg->msg_iovlen = iovcount; #ifdef ISC_NET_BSD44MSGHDR msg->msg_control = NULL; msg->msg_controllen = 0; msg->msg_flags = 0; #if defined(USE_CMSG) msg->msg_control = sock->recvcmsgbuf; msg->msg_controllen = sock->recvcmsgbuflen; #endif /* USE_CMSG */ #else /* ISC_NET_BSD44MSGHDR */ msg->msg_accrights = NULL; msg->msg_accrightslen = 0; #endif /* ISC_NET_BSD44MSGHDR */ if (read_countp != NULL) *read_countp = read_count; } static void set_dev_address(isc_sockaddr_t *address, isc__socket_t *sock, isc_socketevent_t *dev) { if (sock->type == isc_sockettype_udp) { if (address != NULL) dev->address = *address; else dev->address = sock->peer_address; } else if (sock->type == isc_sockettype_tcp) { INSIST(address == NULL); dev->address = sock->peer_address; } } static void destroy_socketevent(isc_event_t *event) { isc_socketevent_t *ev = (isc_socketevent_t *)event; INSIST(ISC_LIST_EMPTY(ev->bufferlist)); (ev->destroy)(event); } static isc_socketevent_t * allocate_socketevent(isc_mem_t *mctx, void *sender, isc_eventtype_t eventtype, isc_taskaction_t action, void *arg) { isc_socketevent_t *ev; ev = (isc_socketevent_t *)isc_event_allocate(mctx, sender, eventtype, action, arg, sizeof(*ev)); if (ev == NULL) return (NULL); ev->result = ISC_R_UNSET; ISC_LINK_INIT(ev, ev_link); ISC_LIST_INIT(ev->bufferlist); ev->region.base = NULL; ev->n = 0; ev->offset = 0; ev->attributes = 0; ev->destroy = ev->ev_destroy; ev->ev_destroy = destroy_socketevent; ev->dscp = 0; return (ev); } #if defined(ISC_SOCKET_DEBUG) static void dump_msg(struct msghdr *msg) { unsigned int i; printf("MSGHDR %p\n", msg); printf("\tname %p, namelen %ld\n", msg->msg_name, (long) msg->msg_namelen); printf("\tiov %p, iovlen %ld\n", msg->msg_iov, (long) msg->msg_iovlen); for (i = 0; i < (unsigned int)msg->msg_iovlen; i++) printf("\t\t%d\tbase %p, len %ld\n", i, msg->msg_iov[i].iov_base, (long) msg->msg_iov[i].iov_len); #ifdef ISC_NET_BSD44MSGHDR printf("\tcontrol %p, controllen %ld\n", msg->msg_control, (long) msg->msg_controllen); #endif } #endif #define DOIO_SUCCESS 0 /* i/o ok, event sent */ #define DOIO_SOFT 1 /* i/o ok, soft error, no event sent */ #define DOIO_HARD 2 /* i/o error, event sent */ #define DOIO_EOF 3 /* EOF, no event sent */ static int doio_recv(isc__socket_t *sock, isc_socketevent_t *dev) { int cc; struct iovec iov[MAXSCATTERGATHER_RECV]; size_t read_count; size_t actual_count; struct msghdr msghdr; isc_buffer_t *buffer; int recv_errno; char strbuf[ISC_STRERRORSIZE]; build_msghdr_recv(sock, dev, &msghdr, iov, &read_count); #if defined(ISC_SOCKET_DEBUG) dump_msg(&msghdr); #endif cc = recvmsg(sock->fd, &msghdr, 0); recv_errno = errno; #if defined(ISC_SOCKET_DEBUG) dump_msg(&msghdr); #endif if (cc < 0) { if (SOFT_ERROR(recv_errno)) return (DOIO_SOFT); if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) { isc__strerror(recv_errno, strbuf, sizeof(strbuf)); socket_log(sock, NULL, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_DOIORECV, "doio_recv: recvmsg(%d) %d bytes, err %d/%s", sock->fd, cc, recv_errno, strbuf); } #define SOFT_OR_HARD(_system, _isc) \ if (recv_errno == _system) { \ if (sock->connected) { \ dev->result = _isc; \ inc_stats(sock->manager->stats, \ sock->statsindex[STATID_RECVFAIL]); \ return (DOIO_HARD); \ } \ return (DOIO_SOFT); \ } #define ALWAYS_HARD(_system, _isc) \ if (recv_errno == _system) { \ dev->result = _isc; \ inc_stats(sock->manager->stats, \ sock->statsindex[STATID_RECVFAIL]); \ return (DOIO_HARD); \ } SOFT_OR_HARD(ECONNREFUSED, ISC_R_CONNREFUSED); SOFT_OR_HARD(ENETUNREACH, ISC_R_NETUNREACH); SOFT_OR_HARD(EHOSTUNREACH, ISC_R_HOSTUNREACH); SOFT_OR_HARD(EHOSTDOWN, ISC_R_HOSTDOWN); /* HPUX 11.11 can return EADDRNOTAVAIL. */ SOFT_OR_HARD(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL); ALWAYS_HARD(ENOBUFS, ISC_R_NORESOURCES); /* Should never get this one but it was seen. */ #ifdef ENOPROTOOPT SOFT_OR_HARD(ENOPROTOOPT, ISC_R_HOSTUNREACH); #endif /* * HPUX returns EPROTO and EINVAL on receiving some ICMP/ICMPv6 * errors. */ #ifdef EPROTO SOFT_OR_HARD(EPROTO, ISC_R_HOSTUNREACH); #endif SOFT_OR_HARD(EINVAL, ISC_R_HOSTUNREACH); #undef SOFT_OR_HARD #undef ALWAYS_HARD dev->result = isc__errno2result(recv_errno); inc_stats(sock->manager->stats, sock->statsindex[STATID_RECVFAIL]); return (DOIO_HARD); } /* * On TCP and UNIX sockets, zero length reads indicate EOF, * while on UDP sockets, zero length reads are perfectly valid, * although strange. */ switch (sock->type) { case isc_sockettype_tcp: case isc_sockettype_unix: if (cc == 0) return (DOIO_EOF); break; case isc_sockettype_udp: case isc_sockettype_raw: break; case isc_sockettype_fdwatch: default: INSIST(0); } if (sock->type == isc_sockettype_udp) { dev->address.length = msghdr.msg_namelen; if (isc_sockaddr_getport(&dev->address) == 0) { if (isc_log_wouldlog(isc_lctx, IOEVENT_LEVEL)) { socket_log(sock, &dev->address, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_ZEROPORT, "dropping source port zero packet"); } return (DOIO_SOFT); } /* * Simulate a firewall blocking UDP responses bigger than * 'maxudp' bytes. */ if (sock->manager->maxudp != 0 && cc > sock->manager->maxudp) return (DOIO_SOFT); } socket_log(sock, &dev->address, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PKTRECV, "packet received correctly"); /* * Overflow bit detection. If we received MORE bytes than we should, * this indicates an overflow situation. Set the flag in the * dev entry and adjust how much we read by one. */ #ifdef ISC_NET_RECVOVERFLOW if ((sock->type == isc_sockettype_udp) && ((size_t)cc > read_count)) { dev->attributes |= ISC_SOCKEVENTATTR_TRUNC; cc--; } #endif /* * If there are control messages attached, run through them and pull * out the interesting bits. */ process_cmsg(sock, &msghdr, dev); /* * update the buffers (if any) and the i/o count */ dev->n += cc; actual_count = cc; buffer = ISC_LIST_HEAD(dev->bufferlist); while (buffer != NULL && actual_count > 0U) { REQUIRE(ISC_BUFFER_VALID(buffer)); if (isc_buffer_availablelength(buffer) <= actual_count) { actual_count -= isc_buffer_availablelength(buffer); isc_buffer_add(buffer, isc_buffer_availablelength(buffer)); } else { isc_buffer_add(buffer, actual_count); actual_count = 0; POST(actual_count); break; } buffer = ISC_LIST_NEXT(buffer, link); if (buffer == NULL) { INSIST(actual_count == 0U); } } /* * If we read less than we expected, update counters, * and let the upper layer poke the descriptor. */ if (((size_t)cc != read_count) && (dev->n < dev->minimum)) return (DOIO_SOFT); /* * Full reads are posted, or partials if partials are ok. */ dev->result = ISC_R_SUCCESS; return (DOIO_SUCCESS); } /* * Returns: * DOIO_SUCCESS The operation succeeded. dev->result contains * ISC_R_SUCCESS. * * DOIO_HARD A hard or unexpected I/O error was encountered. * dev->result contains the appropriate error. * * DOIO_SOFT A soft I/O error was encountered. No senddone * event was sent. The operation should be retried. * * No other return values are possible. */ static int doio_send(isc__socket_t *sock, isc_socketevent_t *dev) { int cc; struct iovec iov[MAXSCATTERGATHER_SEND]; size_t write_count; struct msghdr msghdr; char addrbuf[ISC_SOCKADDR_FORMATSIZE]; int attempts = 0; int send_errno; char strbuf[ISC_STRERRORSIZE]; build_msghdr_send(sock, dev, &msghdr, iov, &write_count); resend: if (sock->type == isc_sockettype_udp && sock->manager->maxudp != 0 && write_count > (size_t)sock->manager->maxudp) cc = write_count; else cc = sendmsg(sock->fd, &msghdr, 0); send_errno = errno; /* * Check for error or block condition. */ if (cc < 0) { if (send_errno == EINTR && ++attempts < NRETRIES) goto resend; if (SOFT_ERROR(send_errno)) return (DOIO_SOFT); #define SOFT_OR_HARD(_system, _isc) \ if (send_errno == _system) { \ if (sock->connected) { \ dev->result = _isc; \ inc_stats(sock->manager->stats, \ sock->statsindex[STATID_SENDFAIL]); \ return (DOIO_HARD); \ } \ return (DOIO_SOFT); \ } #define ALWAYS_HARD(_system, _isc) \ if (send_errno == _system) { \ dev->result = _isc; \ inc_stats(sock->manager->stats, \ sock->statsindex[STATID_SENDFAIL]); \ return (DOIO_HARD); \ } SOFT_OR_HARD(ECONNREFUSED, ISC_R_CONNREFUSED); ALWAYS_HARD(EACCES, ISC_R_NOPERM); ALWAYS_HARD(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL); ALWAYS_HARD(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL); ALWAYS_HARD(EHOSTUNREACH, ISC_R_HOSTUNREACH); #ifdef EHOSTDOWN ALWAYS_HARD(EHOSTDOWN, ISC_R_HOSTUNREACH); #endif ALWAYS_HARD(ENETUNREACH, ISC_R_NETUNREACH); ALWAYS_HARD(ENOBUFS, ISC_R_NORESOURCES); ALWAYS_HARD(EPERM, ISC_R_HOSTUNREACH); ALWAYS_HARD(EPIPE, ISC_R_NOTCONNECTED); ALWAYS_HARD(ECONNRESET, ISC_R_CONNECTIONRESET); #undef SOFT_OR_HARD #undef ALWAYS_HARD /* * The other error types depend on whether or not the * socket is UDP or TCP. If it is UDP, some errors * that we expect to be fatal under TCP are merely * annoying, and are really soft errors. * * However, these soft errors are still returned as * a status. */ isc_sockaddr_format(&dev->address, addrbuf, sizeof(addrbuf)); isc__strerror(send_errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_send: %s: %s", addrbuf, strbuf); dev->result = isc__errno2result(send_errno); inc_stats(sock->manager->stats, sock->statsindex[STATID_SENDFAIL]); return (DOIO_HARD); } if (cc == 0) { inc_stats(sock->manager->stats, sock->statsindex[STATID_SENDFAIL]); UNEXPECTED_ERROR(__FILE__, __LINE__, "doio_send: send() %s 0", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_RETURNED, "returned")); } /* * If we write less than we expected, update counters, poke. */ dev->n += cc; if ((size_t)cc != write_count) return (DOIO_SOFT); /* * Exactly what we wanted to write. We're done with this * entry. Post its completion event. */ dev->result = ISC_R_SUCCESS; return (DOIO_SUCCESS); } /* * Kill. * * Caller must ensure that the socket is not locked and no external * references exist. */ static void socketclose(isc__socketmgr_t *manager, isc__socket_t *sock, int fd) { isc_sockettype_t type = sock->type; int lockid = FDLOCK_ID(fd); /* * No one has this socket open, so the watcher doesn't have to be * poked, and the socket doesn't have to be locked. */ LOCK(&manager->fdlock[lockid]); manager->fds[fd] = NULL; if (type == isc_sockettype_fdwatch) manager->fdstate[fd] = CLOSED; else manager->fdstate[fd] = CLOSE_PENDING; UNLOCK(&manager->fdlock[lockid]); if (type == isc_sockettype_fdwatch) { /* * The caller may close the socket once this function returns, * and `fd' may be reassigned for a new socket. So we do * unwatch_fd() here, rather than defer it via select_poke(). * Note: this may complicate data protection among threads and * may reduce performance due to additional locks. One way to * solve this would be to dup() the watched descriptor, but we * take a simpler approach at this moment. */ (void)unwatch_fd(manager, fd, SELECT_POKE_READ); (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE); } else select_poke(manager, fd, SELECT_POKE_CLOSE); inc_stats(manager->stats, sock->statsindex[STATID_CLOSE]); if (sock->active == 1) { dec_stats(manager->stats, sock->statsindex[STATID_ACTIVE]); sock->active = 0; } /* * update manager->maxfd here (XXX: this should be implemented more * efficiently) */ #ifdef USE_SELECT LOCK(&manager->lock); if (manager->maxfd == fd) { int i; manager->maxfd = 0; for (i = fd - 1; i >= 0; i--) { lockid = FDLOCK_ID(i); LOCK(&manager->fdlock[lockid]); if (manager->fdstate[i] == MANAGED) { manager->maxfd = i; UNLOCK(&manager->fdlock[lockid]); break; } UNLOCK(&manager->fdlock[lockid]); } #ifdef ISC_PLATFORM_USETHREADS if (manager->maxfd < manager->pipe_fds[0]) manager->maxfd = manager->pipe_fds[0]; #endif } UNLOCK(&manager->lock); #endif /* USE_SELECT */ } static void destroy(isc__socket_t **sockp) { int fd; isc__socket_t *sock = *sockp; isc__socketmgr_t *manager = sock->manager; socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_DESTROYING, "destroying"); INSIST(ISC_LIST_EMPTY(sock->accept_list)); INSIST(ISC_LIST_EMPTY(sock->recv_list)); INSIST(ISC_LIST_EMPTY(sock->send_list)); INSIST(sock->connect_ev == NULL); REQUIRE(sock->fd == -1 || sock->fd < (int)manager->maxsocks); if (sock->fd >= 0) { fd = sock->fd; sock->fd = -1; socketclose(manager, sock, fd); } LOCK(&manager->lock); ISC_LIST_UNLINK(manager->socklist, sock, link); #ifdef USE_WATCHER_THREAD if (ISC_LIST_EMPTY(manager->socklist)) SIGNAL(&manager->shutdown_ok); #endif /* USE_WATCHER_THREAD */ /* can't unlock manager as its memory context is still used */ free_socket(sockp); UNLOCK(&manager->lock); } static isc_result_t allocate_socket(isc__socketmgr_t *manager, isc_sockettype_t type, isc__socket_t **socketp) { isc__socket_t *sock; isc_result_t result; ISC_SOCKADDR_LEN_T cmsgbuflen; sock = isc_mem_get(manager->mctx, sizeof(*sock)); if (sock == NULL) return (ISC_R_NOMEMORY); sock->common.magic = 0; sock->common.impmagic = 0; sock->references = 0; sock->manager = manager; sock->type = type; sock->fd = -1; sock->dscp = 0; /* TOS/TCLASS is zero until set. */ sock->dupped = 0; sock->statsindex = NULL; ISC_LINK_INIT(sock, link); sock->recvcmsgbuf = NULL; sock->sendcmsgbuf = NULL; /* * Set up cmsg buffers. */ cmsgbuflen = 0; #if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIN6PKTINFO) cmsgbuflen += cmsg_space(sizeof(struct in6_pktinfo)); #endif #if defined(USE_CMSG) && defined(SO_TIMESTAMP) cmsgbuflen += cmsg_space(sizeof(struct timeval)); #endif #if defined(USE_CMSG) && (defined(IPV6_TCLASS) || defined(IP_TOS)) cmsgbuflen += cmsg_space(sizeof(int)); #endif sock->recvcmsgbuflen = cmsgbuflen; if (sock->recvcmsgbuflen != 0U) { sock->recvcmsgbuf = isc_mem_get(manager->mctx, cmsgbuflen); if (sock->recvcmsgbuf == NULL) { result = ISC_R_NOMEMORY; goto error; } } cmsgbuflen = 0; #if defined(USE_CMSG) && defined(ISC_PLATFORM_HAVEIN6PKTINFO) cmsgbuflen += cmsg_space(sizeof(struct in6_pktinfo)); #if defined(IPV6_USE_MIN_MTU) /* * Provide space for working around FreeBSD's broken IPV6_USE_MIN_MTU * support. */ cmsgbuflen += cmsg_space(sizeof(int)); #endif #endif #if defined(USE_CMSG) && (defined(IP_TOS) || defined(IPV6_TCLASS)) cmsgbuflen += cmsg_space(sizeof(int)); #endif sock->sendcmsgbuflen = cmsgbuflen; if (sock->sendcmsgbuflen != 0U) { sock->sendcmsgbuf = isc_mem_get(manager->mctx, cmsgbuflen); if (sock->sendcmsgbuf == NULL) { result = ISC_R_NOMEMORY; goto error; } } memset(sock->name, 0, sizeof(sock->name)); sock->tag = NULL; /* * Set up list of readers and writers to be initially empty. */ ISC_LIST_INIT(sock->recv_list); ISC_LIST_INIT(sock->send_list); ISC_LIST_INIT(sock->accept_list); sock->connect_ev = NULL; sock->pending_recv = 0; sock->pending_send = 0; sock->pending_accept = 0; sock->listener = 0; sock->connected = 0; sock->connecting = 0; sock->bound = 0; sock->pktdscp = 0; /* * Initialize the lock. */ result = isc_mutex_init(&sock->lock); if (result != ISC_R_SUCCESS) { sock->common.magic = 0; sock->common.impmagic = 0; goto error; } /* * Initialize readable and writable events. */ ISC_EVENT_INIT(&sock->readable_ev, sizeof(intev_t), ISC_EVENTATTR_NOPURGE, NULL, ISC_SOCKEVENT_INTR, NULL, sock, sock, NULL, NULL); ISC_EVENT_INIT(&sock->writable_ev, sizeof(intev_t), ISC_EVENTATTR_NOPURGE, NULL, ISC_SOCKEVENT_INTW, NULL, sock, sock, NULL, NULL); sock->common.magic = ISCAPI_SOCKET_MAGIC; sock->common.impmagic = SOCKET_MAGIC; *socketp = sock; return (ISC_R_SUCCESS); error: if (sock->recvcmsgbuf != NULL) isc_mem_put(manager->mctx, sock->recvcmsgbuf, sock->recvcmsgbuflen); if (sock->sendcmsgbuf != NULL) isc_mem_put(manager->mctx, sock->sendcmsgbuf, sock->sendcmsgbuflen); isc_mem_put(manager->mctx, sock, sizeof(*sock)); return (result); } /* * This event requires that the various lists be empty, that the reference * count be 1, and that the magic number is valid. The other socket bits, * like the lock, must be initialized as well. The fd associated must be * marked as closed, by setting it to -1 on close, or this routine will * also close the socket. */ static void free_socket(isc__socket_t **socketp) { isc__socket_t *sock = *socketp; INSIST(sock->references == 0); INSIST(VALID_SOCKET(sock)); INSIST(!sock->connecting); INSIST(!sock->pending_recv); INSIST(!sock->pending_send); INSIST(!sock->pending_accept); INSIST(ISC_LIST_EMPTY(sock->recv_list)); INSIST(ISC_LIST_EMPTY(sock->send_list)); INSIST(ISC_LIST_EMPTY(sock->accept_list)); INSIST(!ISC_LINK_LINKED(sock, link)); if (sock->recvcmsgbuf != NULL) isc_mem_put(sock->manager->mctx, sock->recvcmsgbuf, sock->recvcmsgbuflen); if (sock->sendcmsgbuf != NULL) isc_mem_put(sock->manager->mctx, sock->sendcmsgbuf, sock->sendcmsgbuflen); sock->common.magic = 0; sock->common.impmagic = 0; DESTROYLOCK(&sock->lock); isc_mem_put(sock->manager->mctx, sock, sizeof(*sock)); *socketp = NULL; } #ifdef SO_RCVBUF static isc_once_t rcvbuf_once = ISC_ONCE_INIT; static int rcvbuf = RCVBUFSIZE; static void set_rcvbuf(void) { int fd; int max = rcvbuf, min; ISC_SOCKADDR_LEN_T len; fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); #if defined(ISC_PLATFORM_HAVEIPV6) if (fd == -1) { switch (errno) { case EPROTONOSUPPORT: case EPFNOSUPPORT: case EAFNOSUPPORT: /* * Linux 2.2 (and maybe others) return EINVAL instead of * EAFNOSUPPORT. */ case EINVAL: fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); break; } } #endif if (fd == -1) return; len = sizeof(min); if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void *)&min, &len) >= 0 && min < rcvbuf) { again: if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, sizeof(rcvbuf)) == -1) { if (errno == ENOBUFS && rcvbuf > min) { max = rcvbuf - 1; rcvbuf = (rcvbuf + min) / 2; goto again; } else { rcvbuf = min; goto cleanup; } } else min = rcvbuf; if (min != max) { rcvbuf = max; goto again; } } cleanup: close (fd); } #endif #ifdef SO_BSDCOMPAT /* * This really should not be necessary to do. Having to workout * which kernel version we are on at run time so that we don't cause * the kernel to issue a warning about us using a deprecated socket option. * Such warnings should *never* be on by default in production kernels. * * We can't do this a build time because executables are moved between * machines and hence kernels. * * We can't just not set SO_BSDCOMAT because some kernels require it. */ static isc_once_t bsdcompat_once = ISC_ONCE_INIT; isc_boolean_t bsdcompat = ISC_TRUE; static void clear_bsdcompat(void) { #ifdef __linux__ struct utsname buf; char *endp; long int major; long int minor; uname(&buf); /* Can only fail if buf is bad in Linux. */ /* Paranoia in parsing can be increased, but we trust uname(). */ major = strtol(buf.release, &endp, 10); if (*endp == '.') { minor = strtol(endp+1, &endp, 10); if ((major > 2) || ((major == 2) && (minor >= 4))) { bsdcompat = ISC_FALSE; } } #endif /* __linux __ */ } #endif static void use_min_mtu(isc__socket_t *sock) { #if !defined(IPV6_USE_MIN_MTU) && !defined(IPV6_MTU) UNUSED(sock); #endif #ifdef IPV6_USE_MIN_MTU /* use minimum MTU */ if (sock->pf == AF_INET6) { int on = 1; (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_USE_MIN_MTU, (void *)&on, sizeof(on)); } #endif #if defined(IPV6_MTU) /* * Use minimum MTU on IPv6 sockets. */ if (sock->pf == AF_INET6) { int mtu = 1280; (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MTU, &mtu, sizeof(mtu)); } #endif } static isc_result_t opensocket(isc__socketmgr_t *manager, isc__socket_t *sock, isc__socket_t *dup_socket) { isc_result_t result; char strbuf[ISC_STRERRORSIZE]; const char *err = "socket"; int tries = 0; #if defined(USE_CMSG) || defined(SO_BSDCOMPAT) || defined(SO_NOSIGPIPE) int on = 1; #endif #if defined(SO_RCVBUF) ISC_SOCKADDR_LEN_T optlen; int size; #endif again: if (dup_socket == NULL) { switch (sock->type) { case isc_sockettype_udp: sock->fd = socket(sock->pf, SOCK_DGRAM, IPPROTO_UDP); break; case isc_sockettype_tcp: sock->fd = socket(sock->pf, SOCK_STREAM, IPPROTO_TCP); break; case isc_sockettype_unix: sock->fd = socket(sock->pf, SOCK_STREAM, 0); break; case isc_sockettype_raw: errno = EPFNOSUPPORT; /* * PF_ROUTE is a alias for PF_NETLINK on linux. */ #if defined(PF_ROUTE) if (sock->fd == -1 && sock->pf == PF_ROUTE) { #ifdef NETLINK_ROUTE sock->fd = socket(sock->pf, SOCK_RAW, NETLINK_ROUTE); #else sock->fd = socket(sock->pf, SOCK_RAW, 0); #endif if (sock->fd != -1) { #ifdef NETLINK_ROUTE struct sockaddr_nl sa; int n; /* * Do an implicit bind. */ memset(&sa, 0, sizeof(sa)); sa.nl_family = AF_NETLINK; sa.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; n = bind(sock->fd, (struct sockaddr *) &sa, sizeof(sa)); if (n < 0) { close(sock->fd); sock->fd = -1; } #endif sock->bound = 1; } } #endif break; case isc_sockettype_fdwatch: /* * We should not be called for isc_sockettype_fdwatch * sockets. */ INSIST(0); break; } } else { sock->fd = dup(dup_socket->fd); sock->dupped = 1; sock->bound = dup_socket->bound; } if (sock->fd == -1 && errno == EINTR && tries++ < 42) goto again; #ifdef F_DUPFD /* * Leave a space for stdio and TCP to work in. */ if (manager->reserved != 0 && sock->type == isc_sockettype_udp && sock->fd >= 0 && sock->fd < manager->reserved) { int new, tmp; new = fcntl(sock->fd, F_DUPFD, manager->reserved); tmp = errno; (void)close(sock->fd); errno = tmp; sock->fd = new; err = "isc_socket_create: fcntl/reserved"; } else if (sock->fd >= 0 && sock->fd < 20) { int new, tmp; new = fcntl(sock->fd, F_DUPFD, 20); tmp = errno; (void)close(sock->fd); errno = tmp; sock->fd = new; err = "isc_socket_create: fcntl"; } #endif if (sock->fd >= (int)manager->maxsocks) { (void)close(sock->fd); isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_TOOMANYFDS, "socket: file descriptor exceeds limit (%d/%u)", sock->fd, manager->maxsocks); inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]); return (ISC_R_NORESOURCES); } if (sock->fd < 0) { switch (errno) { case EMFILE: case ENFILE: isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_TOOMANYFDS, "%s: %s", err, strbuf); /* fallthrough */ case ENOBUFS: inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]); return (ISC_R_NORESOURCES); case EPROTONOSUPPORT: case EPFNOSUPPORT: case EAFNOSUPPORT: /* * Linux 2.2 (and maybe others) return EINVAL instead of * EAFNOSUPPORT. */ case EINVAL: inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]); return (ISC_R_FAMILYNOSUPPORT); default: isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "%s() %s: %s", err, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]); return (ISC_R_UNEXPECTED); } } if (dup_socket != NULL) goto setup_done; result = make_nonblock(sock->fd); if (result != ISC_R_SUCCESS) { (void)close(sock->fd); inc_stats(manager->stats, sock->statsindex[STATID_OPENFAIL]); return (result); } #ifdef SO_BSDCOMPAT RUNTIME_CHECK(isc_once_do(&bsdcompat_once, clear_bsdcompat) == ISC_R_SUCCESS); if (sock->type != isc_sockettype_unix && bsdcompat && setsockopt(sock->fd, SOL_SOCKET, SO_BSDCOMPAT, (void *)&on, sizeof(on)) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, SO_BSDCOMPAT) %s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); /* Press on... */ } #endif #ifdef SO_NOSIGPIPE if (setsockopt(sock->fd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&on, sizeof(on)) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, SO_NOSIGPIPE) %s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); /* Press on... */ } #endif /* * Use minimum mtu if possible. */ use_min_mtu(sock); #if defined(USE_CMSG) || defined(SO_RCVBUF) if (sock->type == isc_sockettype_udp) { #if defined(USE_CMSG) #if defined(SO_TIMESTAMP) if (setsockopt(sock->fd, SOL_SOCKET, SO_TIMESTAMP, (void *)&on, sizeof(on)) < 0 && errno != ENOPROTOOPT) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, SO_TIMESTAMP) %s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); /* Press on... */ } #endif /* SO_TIMESTAMP */ #if defined(ISC_PLATFORM_HAVEIPV6) if (sock->pf == AF_INET6 && sock->recvcmsgbuflen == 0U) { /* * Warn explicitly because this anomaly can be hidden * in usual operation (and unexpectedly appear later). */ UNEXPECTED_ERROR(__FILE__, __LINE__, "No buffer available to receive " "IPv6 destination"); } #ifdef ISC_PLATFORM_HAVEIN6PKTINFO #ifdef IPV6_RECVPKTINFO /* RFC 3542 */ if ((sock->pf == AF_INET6) && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *)&on, sizeof(on)) < 0)) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_RECVPKTINFO) " "%s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } #else /* RFC 2292 */ if ((sock->pf == AF_INET6) && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_PKTINFO, (void *)&on, sizeof(on)) < 0)) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_PKTINFO) %s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } #endif /* IPV6_RECVPKTINFO */ #endif /* ISC_PLATFORM_HAVEIN6PKTINFO */ #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT) /* * Turn off Path MTU discovery on IPv6/UDP sockets. */ if (sock->pf == AF_INET6) { int action = IPV6_PMTUDISC_DONT; (void)setsockopt(sock->fd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &action, sizeof(action)); } #endif #endif /* ISC_PLATFORM_HAVEIPV6 */ #endif /* defined(USE_CMSG) */ #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT) /* * Turn off Path MTU discovery on IPv4/UDP sockets. */ if (sock->pf == AF_INET) { int action = IP_PMTUDISC_DONT; (void)setsockopt(sock->fd, IPPROTO_IP, IP_MTU_DISCOVER, &action, sizeof(action)); } #endif #if defined(IP_DONTFRAG) /* * Turn off Path MTU discovery on IPv4/UDP sockets. */ if (sock->pf == AF_INET) { int off = 0; (void)setsockopt(sock->fd, IPPROTO_IP, IP_DONTFRAG, &off, sizeof(off)); } #endif #if defined(SO_RCVBUF) optlen = sizeof(size); if (getsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF, (void *)&size, &optlen) >= 0 && size < rcvbuf) { RUNTIME_CHECK(isc_once_do(&rcvbuf_once, set_rcvbuf) == ISC_R_SUCCESS); if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf, sizeof(rcvbuf)) == -1) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, SO_RCVBUF, %d) %s: %s", sock->fd, rcvbuf, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } } #endif } #ifdef IPV6_RECVTCLASS if ((sock->pf == AF_INET6) && (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_RECVTCLASS, (void *)&on, sizeof(on)) < 0)) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_RECVTCLASS) " "%s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } #endif #ifdef IP_RECVTOS if ((sock->pf == AF_INET) && (setsockopt(sock->fd, IPPROTO_IP, IP_RECVTOS, (void *)&on, sizeof(on)) < 0)) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IP_RECVTOS) " "%s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } #endif #endif /* defined(USE_CMSG) || defined(SO_RCVBUF) */ setup_done: inc_stats(manager->stats, sock->statsindex[STATID_OPEN]); if (sock->active == 0) { inc_stats(manager->stats, sock->statsindex[STATID_ACTIVE]); sock->active = 1; } return (ISC_R_SUCCESS); } /* * Create a 'type' socket or duplicate an existing socket, managed * by 'manager'. Events will be posted to 'task' and when dispatched * 'action' will be called with 'arg' as the arg value. The new * socket is returned in 'socketp'. */ static isc_result_t socket_create(isc_socketmgr_t *manager0, int pf, isc_sockettype_t type, isc_socket_t **socketp, isc_socket_t *dup_socket) { isc__socket_t *sock = NULL; isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; isc_result_t result; int lockid; REQUIRE(VALID_MANAGER(manager)); REQUIRE(socketp != NULL && *socketp == NULL); REQUIRE(type != isc_sockettype_fdwatch); result = allocate_socket(manager, type, &sock); if (result != ISC_R_SUCCESS) return (result); switch (sock->type) { case isc_sockettype_udp: sock->statsindex = (pf == AF_INET) ? udp4statsindex : udp6statsindex; #define DCSPPKT(pf) ((pf == AF_INET) ? ISC_NET_DSCPPKTV4 : ISC_NET_DSCPPKTV6) sock->pktdscp = (isc_net_probedscp() & DCSPPKT(pf)) != 0; break; case isc_sockettype_tcp: sock->statsindex = (pf == AF_INET) ? tcp4statsindex : tcp6statsindex; break; case isc_sockettype_unix: sock->statsindex = unixstatsindex; break; case isc_sockettype_raw: sock->statsindex = rawstatsindex; break; default: INSIST(0); } sock->active = 0; sock->pf = pf; result = opensocket(manager, sock, (isc__socket_t *)dup_socket); if (result != ISC_R_SUCCESS) { free_socket(&sock); return (result); } sock->common.methods = (isc_socketmethods_t *)&socketmethods; sock->references = 1; *socketp = (isc_socket_t *)sock; /* * Note we don't have to lock the socket like we normally would because * there are no external references to it yet. */ lockid = FDLOCK_ID(sock->fd); LOCK(&manager->fdlock[lockid]); manager->fds[sock->fd] = sock; manager->fdstate[sock->fd] = MANAGED; #ifdef USE_DEVPOLL INSIST(sock->manager->fdpollinfo[sock->fd].want_read == 0 && sock->manager->fdpollinfo[sock->fd].want_write == 0); #endif UNLOCK(&manager->fdlock[lockid]); LOCK(&manager->lock); ISC_LIST_APPEND(manager->socklist, sock, link); #ifdef USE_SELECT if (manager->maxfd < sock->fd) manager->maxfd = sock->fd; #endif UNLOCK(&manager->lock); socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_CREATED, dup_socket != NULL ? "dupped" : "created"); return (ISC_R_SUCCESS); } /*% * Create a new 'type' socket managed by 'manager'. Events * will be posted to 'task' and when dispatched 'action' will be * called with 'arg' as the arg value. The new socket is returned * in 'socketp'. */ isc_result_t isc__socket_create(isc_socketmgr_t *manager0, int pf, isc_sockettype_t type, isc_socket_t **socketp) { return (socket_create(manager0, pf, type, socketp, NULL)); } /*% * Duplicate an existing socket. The new socket is returned * in 'socketp'. */ isc_result_t isc__socket_dup(isc_socket_t *sock0, isc_socket_t **socketp) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); REQUIRE(socketp != NULL && *socketp == NULL); return (socket_create((isc_socketmgr_t *) sock->manager, sock->pf, sock->type, socketp, sock0)); } isc_result_t isc__socket_open(isc_socket_t *sock0) { isc_result_t result; isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); LOCK(&sock->lock); REQUIRE(sock->references == 1); REQUIRE(sock->type != isc_sockettype_fdwatch); UNLOCK(&sock->lock); /* * We don't need to retain the lock hereafter, since no one else has * this socket. */ REQUIRE(sock->fd == -1); result = opensocket(sock->manager, sock, NULL); if (result != ISC_R_SUCCESS) sock->fd = -1; if (result == ISC_R_SUCCESS) { int lockid = FDLOCK_ID(sock->fd); LOCK(&sock->manager->fdlock[lockid]); sock->manager->fds[sock->fd] = sock; sock->manager->fdstate[sock->fd] = MANAGED; #ifdef USE_DEVPOLL INSIST(sock->manager->fdpollinfo[sock->fd].want_read == 0 && sock->manager->fdpollinfo[sock->fd].want_write == 0); #endif UNLOCK(&sock->manager->fdlock[lockid]); #ifdef USE_SELECT LOCK(&sock->manager->lock); if (sock->manager->maxfd < sock->fd) sock->manager->maxfd = sock->fd; UNLOCK(&sock->manager->lock); #endif } return (result); } /* * Create a new 'type' socket managed by 'manager'. Events * will be posted to 'task' and when dispatched 'action' will be * called with 'arg' as the arg value. The new socket is returned * in 'socketp'. */ isc_result_t isc__socket_fdwatchcreate(isc_socketmgr_t *manager0, int fd, int flags, isc_sockfdwatch_t callback, void *cbarg, isc_task_t *task, isc_socket_t **socketp) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; isc__socket_t *sock = NULL; isc_result_t result; int lockid; REQUIRE(VALID_MANAGER(manager)); REQUIRE(socketp != NULL && *socketp == NULL); result = allocate_socket(manager, isc_sockettype_fdwatch, &sock); if (result != ISC_R_SUCCESS) return (result); sock->fd = fd; sock->fdwatcharg = cbarg; sock->fdwatchcb = callback; sock->fdwatchflags = flags; sock->fdwatchtask = task; sock->statsindex = fdwatchstatsindex; sock->common.methods = (isc_socketmethods_t *)&socketmethods; sock->references = 1; *socketp = (isc_socket_t *)sock; /* * Note we don't have to lock the socket like we normally would because * there are no external references to it yet. */ lockid = FDLOCK_ID(sock->fd); LOCK(&manager->fdlock[lockid]); manager->fds[sock->fd] = sock; manager->fdstate[sock->fd] = MANAGED; UNLOCK(&manager->fdlock[lockid]); LOCK(&manager->lock); ISC_LIST_APPEND(manager->socklist, sock, link); #ifdef USE_SELECT if (manager->maxfd < sock->fd) manager->maxfd = sock->fd; #endif UNLOCK(&manager->lock); if (flags & ISC_SOCKFDWATCH_READ) select_poke(sock->manager, sock->fd, SELECT_POKE_READ); if (flags & ISC_SOCKFDWATCH_WRITE) select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE); socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_CREATED, "fdwatch-created"); return (ISC_R_SUCCESS); } /* * Indicate to the manager that it should watch the socket again. * This can be used to restart watching if the previous event handler * didn't indicate there was more data to be processed. Primarily * it is for writing but could be used for reading if desired */ isc_result_t isc__socket_fdwatchpoke(isc_socket_t *sock0, int flags) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); /* * We check both flags first to allow us to get the lock * once but only if we need it. */ if ((flags & (ISC_SOCKFDWATCH_READ | ISC_SOCKFDWATCH_WRITE)) != 0) { LOCK(&sock->lock); if (((flags & ISC_SOCKFDWATCH_READ) != 0) && !sock->pending_recv) select_poke(sock->manager, sock->fd, SELECT_POKE_READ); if (((flags & ISC_SOCKFDWATCH_WRITE) != 0) && !sock->pending_send) select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE); UNLOCK(&sock->lock); } socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_POKED, "fdwatch-poked flags: %d", flags); return (ISC_R_SUCCESS); } /* * Attach to a socket. Caller must explicitly detach when it is done. */ void isc__socket_attach(isc_socket_t *sock0, isc_socket_t **socketp) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); REQUIRE(socketp != NULL && *socketp == NULL); LOCK(&sock->lock); sock->references++; UNLOCK(&sock->lock); *socketp = (isc_socket_t *)sock; } /* * Dereference a socket. If this is the last reference to it, clean things * up by destroying the socket. */ void isc__socket_detach(isc_socket_t **socketp) { isc__socket_t *sock; isc_boolean_t kill_socket = ISC_FALSE; REQUIRE(socketp != NULL); sock = (isc__socket_t *)*socketp; REQUIRE(VALID_SOCKET(sock)); LOCK(&sock->lock); REQUIRE(sock->references > 0); sock->references--; if (sock->references == 0) kill_socket = ISC_TRUE; UNLOCK(&sock->lock); if (kill_socket) destroy(&sock); *socketp = NULL; } isc_result_t isc__socket_close(isc_socket_t *sock0) { isc__socket_t *sock = (isc__socket_t *)sock0; int fd; isc__socketmgr_t *manager; fflush(stdout); REQUIRE(VALID_SOCKET(sock)); LOCK(&sock->lock); REQUIRE(sock->references == 1); REQUIRE(sock->type != isc_sockettype_fdwatch); REQUIRE(sock->fd >= 0 && sock->fd < (int)sock->manager->maxsocks); INSIST(!sock->connecting); INSIST(!sock->pending_recv); INSIST(!sock->pending_send); INSIST(!sock->pending_accept); INSIST(ISC_LIST_EMPTY(sock->recv_list)); INSIST(ISC_LIST_EMPTY(sock->send_list)); INSIST(ISC_LIST_EMPTY(sock->accept_list)); INSIST(sock->connect_ev == NULL); manager = sock->manager; fd = sock->fd; sock->fd = -1; sock->dupped = 0; memset(sock->name, 0, sizeof(sock->name)); sock->tag = NULL; sock->listener = 0; sock->connected = 0; sock->connecting = 0; sock->bound = 0; isc_sockaddr_any(&sock->peer_address); UNLOCK(&sock->lock); socketclose(manager, sock, fd); return (ISC_R_SUCCESS); } /* * I/O is possible on a given socket. Schedule an event to this task that * will call an internal function to do the I/O. This will charge the * task with the I/O operation and let our select loop handler get back * to doing something real as fast as possible. * * The socket and manager must be locked before calling this function. */ static void dispatch_recv(isc__socket_t *sock) { intev_t *iev; isc_socketevent_t *ev; isc_task_t *sender; INSIST(!sock->pending_recv); if (sock->type != isc_sockettype_fdwatch) { ev = ISC_LIST_HEAD(sock->recv_list); if (ev == NULL) return; socket_log(sock, NULL, EVENT, NULL, 0, 0, "dispatch_recv: event %p -> task %p", ev, ev->ev_sender); sender = ev->ev_sender; } else { sender = sock->fdwatchtask; } sock->pending_recv = 1; iev = &sock->readable_ev; sock->references++; iev->ev_sender = sock; if (sock->type == isc_sockettype_fdwatch) iev->ev_action = internal_fdwatch_read; else iev->ev_action = internal_recv; iev->ev_arg = sock; isc_task_send(sender, (isc_event_t **)&iev); } static void dispatch_send(isc__socket_t *sock) { intev_t *iev; isc_socketevent_t *ev; isc_task_t *sender; INSIST(!sock->pending_send); if (sock->type != isc_sockettype_fdwatch) { ev = ISC_LIST_HEAD(sock->send_list); if (ev == NULL) return; socket_log(sock, NULL, EVENT, NULL, 0, 0, "dispatch_send: event %p -> task %p", ev, ev->ev_sender); sender = ev->ev_sender; } else { sender = sock->fdwatchtask; } sock->pending_send = 1; iev = &sock->writable_ev; sock->references++; iev->ev_sender = sock; if (sock->type == isc_sockettype_fdwatch) iev->ev_action = internal_fdwatch_write; else iev->ev_action = internal_send; iev->ev_arg = sock; isc_task_send(sender, (isc_event_t **)&iev); } /* * Dispatch an internal accept event. */ static void dispatch_accept(isc__socket_t *sock) { intev_t *iev; isc_socket_newconnev_t *ev; INSIST(!sock->pending_accept); /* * Are there any done events left, or were they all canceled * before the manager got the socket lock? */ ev = ISC_LIST_HEAD(sock->accept_list); if (ev == NULL) return; sock->pending_accept = 1; iev = &sock->readable_ev; sock->references++; /* keep socket around for this internal event */ iev->ev_sender = sock; iev->ev_action = internal_accept; iev->ev_arg = sock; isc_task_send(ev->ev_sender, (isc_event_t **)&iev); } static void dispatch_connect(isc__socket_t *sock) { intev_t *iev; isc_socket_connev_t *ev; iev = &sock->writable_ev; ev = sock->connect_ev; INSIST(ev != NULL); /* XXX */ INSIST(sock->connecting); sock->references++; /* keep socket around for this internal event */ iev->ev_sender = sock; iev->ev_action = internal_connect; iev->ev_arg = sock; isc_task_send(ev->ev_sender, (isc_event_t **)&iev); } /* * Dequeue an item off the given socket's read queue, set the result code * in the done event to the one provided, and send it to the task it was * destined for. * * If the event to be sent is on a list, remove it before sending. If * asked to, send and detach from the socket as well. * * Caller must have the socket locked if the event is attached to the socket. */ static void send_recvdone_event(isc__socket_t *sock, isc_socketevent_t **dev) { isc_task_t *task; task = (*dev)->ev_sender; (*dev)->ev_sender = sock; if (ISC_LINK_LINKED(*dev, ev_link)) ISC_LIST_DEQUEUE(sock->recv_list, *dev, ev_link); if (((*dev)->attributes & ISC_SOCKEVENTATTR_ATTACHED) == ISC_SOCKEVENTATTR_ATTACHED) isc_task_sendanddetach(&task, (isc_event_t **)dev); else isc_task_send(task, (isc_event_t **)dev); } /* * See comments for send_recvdone_event() above. * * Caller must have the socket locked if the event is attached to the socket. */ static void send_senddone_event(isc__socket_t *sock, isc_socketevent_t **dev) { isc_task_t *task; INSIST(dev != NULL && *dev != NULL); task = (*dev)->ev_sender; (*dev)->ev_sender = sock; if (ISC_LINK_LINKED(*dev, ev_link)) ISC_LIST_DEQUEUE(sock->send_list, *dev, ev_link); if (((*dev)->attributes & ISC_SOCKEVENTATTR_ATTACHED) == ISC_SOCKEVENTATTR_ATTACHED) isc_task_sendanddetach(&task, (isc_event_t **)dev); else isc_task_send(task, (isc_event_t **)dev); } /* * Call accept() on a socket, to get the new file descriptor. The listen * socket is used as a prototype to create a new isc_socket_t. The new * socket has one outstanding reference. The task receiving the event * will be detached from just after the event is delivered. * * On entry to this function, the event delivered is the internal * readable event, and the first item on the accept_list should be * the done event we want to send. If the list is empty, this is a no-op, * so just unlock and return. */ static void internal_accept(isc_task_t *me, isc_event_t *ev) { isc__socket_t *sock; isc__socketmgr_t *manager; isc_socket_newconnev_t *dev; isc_task_t *task; ISC_SOCKADDR_LEN_T addrlen; int fd; isc_result_t result = ISC_R_SUCCESS; char strbuf[ISC_STRERRORSIZE]; const char *err = "accept"; UNUSED(me); sock = ev->ev_sender; INSIST(VALID_SOCKET(sock)); LOCK(&sock->lock); socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_ACCEPTLOCK, "internal_accept called, locked socket"); manager = sock->manager; INSIST(VALID_MANAGER(manager)); INSIST(sock->listener); INSIST(sock->pending_accept == 1); sock->pending_accept = 0; INSIST(sock->references > 0); sock->references--; /* the internal event is done with this socket */ if (sock->references == 0) { UNLOCK(&sock->lock); destroy(&sock); return; } /* * Get the first item off the accept list. * If it is empty, unlock the socket and return. */ dev = ISC_LIST_HEAD(sock->accept_list); if (dev == NULL) { UNLOCK(&sock->lock); return; } /* * Try to accept the new connection. If the accept fails with * EAGAIN or EINTR, simply poke the watcher to watch this socket * again. Also ignore ECONNRESET, which has been reported to * be spuriously returned on Linux 2.2.19 although it is not * a documented error for accept(). ECONNABORTED has been * reported for Solaris 8. The rest are thrown in not because * we have seen them but because they are ignored by other * daemons such as BIND 8 and Apache. */ addrlen = sizeof(NEWCONNSOCK(dev)->peer_address.type); memset(&NEWCONNSOCK(dev)->peer_address.type, 0, addrlen); fd = accept(sock->fd, &NEWCONNSOCK(dev)->peer_address.type.sa, (void *)&addrlen); #ifdef F_DUPFD /* * Leave a space for stdio to work in. */ if (fd >= 0 && fd < 20) { int new, tmp; new = fcntl(fd, F_DUPFD, 20); tmp = errno; (void)close(fd); errno = tmp; fd = new; err = "accept/fcntl"; } #endif if (fd < 0) { if (SOFT_ERROR(errno)) goto soft_error; switch (errno) { case ENFILE: case EMFILE: isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_TOOMANYFDS, "%s: too many open file descriptors", err); goto soft_error; case ENOBUFS: case ENOMEM: case ECONNRESET: case ECONNABORTED: case EHOSTUNREACH: case EHOSTDOWN: case ENETUNREACH: case ENETDOWN: case ECONNREFUSED: #ifdef EPROTO case EPROTO: #endif #ifdef ENONET case ENONET: #endif goto soft_error; default: break; } isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_accept: %s() %s: %s", err, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); fd = -1; result = ISC_R_UNEXPECTED; } else { if (addrlen == 0U) { UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_accept(): " "accept() failed to return " "remote address"); (void)close(fd); goto soft_error; } else if (NEWCONNSOCK(dev)->peer_address.type.sa.sa_family != sock->pf) { UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_accept(): " "accept() returned peer address " "family %u (expected %u)", NEWCONNSOCK(dev)->peer_address. type.sa.sa_family, sock->pf); (void)close(fd); goto soft_error; } else if (fd >= (int)manager->maxsocks) { isc_log_iwrite(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_TOOMANYFDS, "accept: " "file descriptor exceeds limit (%d/%u)", fd, manager->maxsocks); (void)close(fd); goto soft_error; } } if (fd != -1) { NEWCONNSOCK(dev)->peer_address.length = addrlen; NEWCONNSOCK(dev)->pf = sock->pf; } /* * Pull off the done event. */ ISC_LIST_UNLINK(sock->accept_list, dev, ev_link); /* * Poke watcher if there are more pending accepts. */ if (!ISC_LIST_EMPTY(sock->accept_list)) select_poke(sock->manager, sock->fd, SELECT_POKE_ACCEPT); UNLOCK(&sock->lock); if (fd != -1) { result = make_nonblock(fd); if (result != ISC_R_SUCCESS) { (void)close(fd); fd = -1; } } /* * -1 means the new socket didn't happen. */ if (fd != -1) { int lockid = FDLOCK_ID(fd); NEWCONNSOCK(dev)->fd = fd; NEWCONNSOCK(dev)->bound = 1; NEWCONNSOCK(dev)->connected = 1; /* * Use minimum mtu if possible. */ use_min_mtu(NEWCONNSOCK(dev)); /* * Ensure DSCP settings are inherited across accept. */ setdscp(NEWCONNSOCK(dev), sock->dscp); /* * Save away the remote address */ dev->address = NEWCONNSOCK(dev)->peer_address; LOCK(&manager->fdlock[lockid]); manager->fds[fd] = NEWCONNSOCK(dev); manager->fdstate[fd] = MANAGED; UNLOCK(&manager->fdlock[lockid]); LOCK(&manager->lock); #ifdef USE_SELECT if (manager->maxfd < fd) manager->maxfd = fd; #endif socket_log(sock, &NEWCONNSOCK(dev)->peer_address, CREATION, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_ACCEPTEDCXN, "accepted connection, new socket %p", dev->newsocket); ISC_LIST_APPEND(manager->socklist, NEWCONNSOCK(dev), link); UNLOCK(&manager->lock); inc_stats(manager->stats, sock->statsindex[STATID_ACCEPT]); inc_stats(manager->stats, sock->statsindex[STATID_ACTIVE]); } else { inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]); NEWCONNSOCK(dev)->references--; free_socket((isc__socket_t **)&dev->newsocket); } /* * Fill in the done event details and send it off. */ dev->result = result; task = dev->ev_sender; dev->ev_sender = sock; isc_task_sendanddetach(&task, ISC_EVENT_PTR(&dev)); return; soft_error: select_poke(sock->manager, sock->fd, SELECT_POKE_ACCEPT); UNLOCK(&sock->lock); inc_stats(manager->stats, sock->statsindex[STATID_ACCEPTFAIL]); return; } static void internal_recv(isc_task_t *me, isc_event_t *ev) { isc_socketevent_t *dev; isc__socket_t *sock; INSIST(ev->ev_type == ISC_SOCKEVENT_INTR); sock = ev->ev_sender; INSIST(VALID_SOCKET(sock)); LOCK(&sock->lock); socket_log(sock, NULL, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALRECV, "internal_recv: task %p got event %p", me, ev); INSIST(sock->pending_recv == 1); sock->pending_recv = 0; INSIST(sock->references > 0); sock->references--; /* the internal event is done with this socket */ if (sock->references == 0) { UNLOCK(&sock->lock); destroy(&sock); return; } /* * Try to do as much I/O as possible on this socket. There are no * limits here, currently. */ dev = ISC_LIST_HEAD(sock->recv_list); while (dev != NULL) { switch (doio_recv(sock, dev)) { case DOIO_SOFT: goto poke; case DOIO_EOF: /* * read of 0 means the remote end was closed. * Run through the event queue and dispatch all * the events with an EOF result code. */ do { dev->result = ISC_R_EOF; send_recvdone_event(sock, &dev); dev = ISC_LIST_HEAD(sock->recv_list); } while (dev != NULL); goto poke; case DOIO_SUCCESS: case DOIO_HARD: send_recvdone_event(sock, &dev); break; } dev = ISC_LIST_HEAD(sock->recv_list); } poke: if (!ISC_LIST_EMPTY(sock->recv_list)) select_poke(sock->manager, sock->fd, SELECT_POKE_READ); UNLOCK(&sock->lock); } static void internal_send(isc_task_t *me, isc_event_t *ev) { isc_socketevent_t *dev; isc__socket_t *sock; INSIST(ev->ev_type == ISC_SOCKEVENT_INTW); /* * Find out what socket this is and lock it. */ sock = (isc__socket_t *)ev->ev_sender; INSIST(VALID_SOCKET(sock)); LOCK(&sock->lock); socket_log(sock, NULL, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALSEND, "internal_send: task %p got event %p", me, ev); INSIST(sock->pending_send == 1); sock->pending_send = 0; INSIST(sock->references > 0); sock->references--; /* the internal event is done with this socket */ if (sock->references == 0) { UNLOCK(&sock->lock); destroy(&sock); return; } /* * Try to do as much I/O as possible on this socket. There are no * limits here, currently. */ dev = ISC_LIST_HEAD(sock->send_list); while (dev != NULL) { switch (doio_send(sock, dev)) { case DOIO_SOFT: goto poke; case DOIO_HARD: case DOIO_SUCCESS: send_senddone_event(sock, &dev); break; } dev = ISC_LIST_HEAD(sock->send_list); } poke: if (!ISC_LIST_EMPTY(sock->send_list)) select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE); UNLOCK(&sock->lock); } static void internal_fdwatch_write(isc_task_t *me, isc_event_t *ev) { isc__socket_t *sock; int more_data; INSIST(ev->ev_type == ISC_SOCKEVENT_INTW); /* * Find out what socket this is and lock it. */ sock = (isc__socket_t *)ev->ev_sender; INSIST(VALID_SOCKET(sock)); LOCK(&sock->lock); socket_log(sock, NULL, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALSEND, "internal_fdwatch_write: task %p got event %p", me, ev); INSIST(sock->pending_send == 1); UNLOCK(&sock->lock); more_data = (sock->fdwatchcb)(me, (isc_socket_t *)sock, sock->fdwatcharg, ISC_SOCKFDWATCH_WRITE); LOCK(&sock->lock); sock->pending_send = 0; INSIST(sock->references > 0); sock->references--; /* the internal event is done with this socket */ if (sock->references == 0) { UNLOCK(&sock->lock); destroy(&sock); return; } if (more_data) select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE); UNLOCK(&sock->lock); } static void internal_fdwatch_read(isc_task_t *me, isc_event_t *ev) { isc__socket_t *sock; int more_data; INSIST(ev->ev_type == ISC_SOCKEVENT_INTR); /* * Find out what socket this is and lock it. */ sock = (isc__socket_t *)ev->ev_sender; INSIST(VALID_SOCKET(sock)); LOCK(&sock->lock); socket_log(sock, NULL, IOEVENT, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_INTERNALRECV, "internal_fdwatch_read: task %p got event %p", me, ev); INSIST(sock->pending_recv == 1); UNLOCK(&sock->lock); more_data = (sock->fdwatchcb)(me, (isc_socket_t *)sock, sock->fdwatcharg, ISC_SOCKFDWATCH_READ); LOCK(&sock->lock); sock->pending_recv = 0; INSIST(sock->references > 0); sock->references--; /* the internal event is done with this socket */ if (sock->references == 0) { UNLOCK(&sock->lock); destroy(&sock); return; } if (more_data) select_poke(sock->manager, sock->fd, SELECT_POKE_READ); UNLOCK(&sock->lock); } /* * Process read/writes on each fd here. Avoid locking * and unlocking twice if both reads and writes are possible. */ static void process_fd(isc__socketmgr_t *manager, int fd, isc_boolean_t readable, isc_boolean_t writeable) { isc__socket_t *sock; isc_boolean_t unlock_sock; isc_boolean_t unwatch_read = ISC_FALSE, unwatch_write = ISC_FALSE; int lockid = FDLOCK_ID(fd); /* * If the socket is going to be closed, don't do more I/O. */ LOCK(&manager->fdlock[lockid]); if (manager->fdstate[fd] == CLOSE_PENDING) { UNLOCK(&manager->fdlock[lockid]); (void)unwatch_fd(manager, fd, SELECT_POKE_READ); (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE); return; } sock = manager->fds[fd]; unlock_sock = ISC_FALSE; if (readable) { if (sock == NULL) { unwatch_read = ISC_TRUE; goto check_write; } unlock_sock = ISC_TRUE; LOCK(&sock->lock); if (!SOCK_DEAD(sock)) { if (sock->listener) dispatch_accept(sock); else dispatch_recv(sock); } unwatch_read = ISC_TRUE; } check_write: if (writeable) { if (sock == NULL) { unwatch_write = ISC_TRUE; goto unlock_fd; } if (!unlock_sock) { unlock_sock = ISC_TRUE; LOCK(&sock->lock); } if (!SOCK_DEAD(sock)) { if (sock->connecting) dispatch_connect(sock); else dispatch_send(sock); } unwatch_write = ISC_TRUE; } if (unlock_sock) UNLOCK(&sock->lock); unlock_fd: UNLOCK(&manager->fdlock[lockid]); if (unwatch_read) (void)unwatch_fd(manager, fd, SELECT_POKE_READ); if (unwatch_write) (void)unwatch_fd(manager, fd, SELECT_POKE_WRITE); } #ifdef USE_KQUEUE static isc_boolean_t process_fds(isc__socketmgr_t *manager, struct kevent *events, int nevents) { int i; isc_boolean_t readable, writable; isc_boolean_t done = ISC_FALSE; #ifdef USE_WATCHER_THREAD isc_boolean_t have_ctlevent = ISC_FALSE; #endif if (nevents == manager->nevents) { /* * This is not an error, but something unexpected. If this * happens, it may indicate the need for increasing * ISC_SOCKET_MAXEVENTS. */ manager_log(manager, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_INFO, "maximum number of FD events (%d) received", nevents); } for (i = 0; i < nevents; i++) { REQUIRE(events[i].ident < manager->maxsocks); #ifdef USE_WATCHER_THREAD if (events[i].ident == (uintptr_t)manager->pipe_fds[0]) { have_ctlevent = ISC_TRUE; continue; } #endif readable = ISC_TF(events[i].filter == EVFILT_READ); writable = ISC_TF(events[i].filter == EVFILT_WRITE); process_fd(manager, events[i].ident, readable, writable); } #ifdef USE_WATCHER_THREAD if (have_ctlevent) done = process_ctlfd(manager); #endif return (done); } #elif defined(USE_EPOLL) static isc_boolean_t process_fds(isc__socketmgr_t *manager, struct epoll_event *events, int nevents) { int i; isc_boolean_t done = ISC_FALSE; #ifdef USE_WATCHER_THREAD isc_boolean_t have_ctlevent = ISC_FALSE; #endif if (nevents == manager->nevents) { manager_log(manager, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_INFO, "maximum number of FD events (%d) received", nevents); } for (i = 0; i < nevents; i++) { REQUIRE(events[i].data.fd < (int)manager->maxsocks); #ifdef USE_WATCHER_THREAD if (events[i].data.fd == manager->pipe_fds[0]) { have_ctlevent = ISC_TRUE; continue; } #endif if ((events[i].events & EPOLLERR) != 0 || (events[i].events & EPOLLHUP) != 0) { /* * epoll does not set IN/OUT bits on an erroneous * condition, so we need to try both anyway. This is a * bit inefficient, but should be okay for such rare * events. Note also that the read or write attempt * won't block because we use non-blocking sockets. */ events[i].events |= (EPOLLIN | EPOLLOUT); } process_fd(manager, events[i].data.fd, (events[i].events & EPOLLIN) != 0, (events[i].events & EPOLLOUT) != 0); } #ifdef USE_WATCHER_THREAD if (have_ctlevent) done = process_ctlfd(manager); #endif return (done); } #elif defined(USE_DEVPOLL) static isc_boolean_t process_fds(isc__socketmgr_t *manager, struct pollfd *events, int nevents) { int i; isc_boolean_t done = ISC_FALSE; #ifdef USE_WATCHER_THREAD isc_boolean_t have_ctlevent = ISC_FALSE; #endif if (nevents == manager->nevents) { manager_log(manager, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_INFO, "maximum number of FD events (%d) received", nevents); } for (i = 0; i < nevents; i++) { REQUIRE(events[i].fd < (int)manager->maxsocks); #ifdef USE_WATCHER_THREAD if (events[i].fd == manager->pipe_fds[0]) { have_ctlevent = ISC_TRUE; continue; } #endif process_fd(manager, events[i].fd, (events[i].events & POLLIN) != 0, (events[i].events & POLLOUT) != 0); } #ifdef USE_WATCHER_THREAD if (have_ctlevent) done = process_ctlfd(manager); #endif return (done); } #elif defined(USE_SELECT) static void process_fds(isc__socketmgr_t *manager, int maxfd, fd_set *readfds, fd_set *writefds) { int i; REQUIRE(maxfd <= (int)manager->maxsocks); for (i = 0; i < maxfd; i++) { #ifdef USE_WATCHER_THREAD if (i == manager->pipe_fds[0] || i == manager->pipe_fds[1]) continue; #endif /* USE_WATCHER_THREAD */ process_fd(manager, i, FD_ISSET(i, readfds), FD_ISSET(i, writefds)); } } #endif #ifdef USE_WATCHER_THREAD static isc_boolean_t process_ctlfd(isc__socketmgr_t *manager) { int msg, fd; for (;;) { select_readmsg(manager, &fd, &msg); manager_log(manager, IOEVENT, isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_WATCHERMSG, "watcher got message %d " "for socket %d"), msg, fd); /* * Nothing to read? */ if (msg == SELECT_POKE_NOTHING) break; /* * Handle shutdown message. We really should * jump out of this loop right away, but * it doesn't matter if we have to do a little * more work first. */ if (msg == SELECT_POKE_SHUTDOWN) return (ISC_TRUE); /* * This is a wakeup on a socket. Look * at the event queue for both read and write, * and decide if we need to watch on it now * or not. */ wakeup_socket(manager, fd, msg); } return (ISC_FALSE); } /* * This is the thread that will loop forever, always in a select or poll * call. * * When select returns something to do, track down what thread gets to do * this I/O and post the event to it. */ static isc_threadresult_t watcher(void *uap) { isc__socketmgr_t *manager = uap; isc_boolean_t done; int cc; #ifdef USE_KQUEUE const char *fnname = "kevent()"; #elif defined (USE_EPOLL) const char *fnname = "epoll_wait()"; #elif defined(USE_DEVPOLL) isc_result_t result; const char *fnname = "ioctl(DP_POLL)"; struct dvpoll dvp; int pass; #elif defined (USE_SELECT) const char *fnname = "select()"; int maxfd; int ctlfd; #endif char strbuf[ISC_STRERRORSIZE]; #ifdef ISC_SOCKET_USE_POLLWATCH pollstate_t pollstate = poll_idle; #endif #if defined (USE_SELECT) /* * Get the control fd here. This will never change. */ ctlfd = manager->pipe_fds[0]; #endif done = ISC_FALSE; while (!done) { do { #ifdef USE_KQUEUE cc = kevent(manager->kqueue_fd, NULL, 0, manager->events, manager->nevents, NULL); #elif defined(USE_EPOLL) cc = epoll_wait(manager->epoll_fd, manager->events, manager->nevents, -1); #elif defined(USE_DEVPOLL) /* * Re-probe every thousand calls. */ if (manager->calls++ > 1000U) { result = isc_resource_getcurlimit( isc_resource_openfiles, &manager->open_max); if (result != ISC_R_SUCCESS) manager->open_max = 64; manager->calls = 0; } for (pass = 0; pass < 2; pass++) { dvp.dp_fds = manager->events; dvp.dp_nfds = manager->nevents; if (dvp.dp_nfds >= manager->open_max) dvp.dp_nfds = manager->open_max - 1; #ifndef ISC_SOCKET_USE_POLLWATCH dvp.dp_timeout = -1; #else if (pollstate == poll_idle) dvp.dp_timeout = -1; else dvp.dp_timeout = ISC_SOCKET_POLLWATCH_TIMEOUT; #endif /* ISC_SOCKET_USE_POLLWATCH */ cc = ioctl(manager->devpoll_fd, DP_POLL, &dvp); if (cc == -1 && errno == EINVAL) { /* * {OPEN_MAX} may have dropped. Look * up the current value and try again. */ result = isc_resource_getcurlimit( isc_resource_openfiles, &manager->open_max); if (result != ISC_R_SUCCESS) manager->open_max = 64; } else break; } #elif defined(USE_SELECT) LOCK(&manager->lock); memmove(manager->read_fds_copy, manager->read_fds, manager->fd_bufsize); memmove(manager->write_fds_copy, manager->write_fds, manager->fd_bufsize); maxfd = manager->maxfd + 1; UNLOCK(&manager->lock); cc = select(maxfd, manager->read_fds_copy, manager->write_fds_copy, NULL, NULL); #endif /* USE_KQUEUE */ if (cc < 0 && !SOFT_ERROR(errno)) { isc__strerror(errno, strbuf, sizeof(strbuf)); FATAL_ERROR(__FILE__, __LINE__, "%s %s: %s", fnname, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } #if defined(USE_DEVPOLL) && defined(ISC_SOCKET_USE_POLLWATCH) if (cc == 0) { if (pollstate == poll_active) pollstate = poll_checking; else if (pollstate == poll_checking) pollstate = poll_idle; } else if (cc > 0) { if (pollstate == poll_checking) { /* * XXX: We'd like to use a more * verbose log level as it's actually an * unexpected event, but the kernel bug * reportedly happens pretty frequently * (and it can also be a false positive) * so it would be just too noisy. */ manager_log(manager, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_DEBUG(1), "unexpected POLL timeout"); } pollstate = poll_active; } #endif } while (cc < 0); #if defined(USE_KQUEUE) || defined (USE_EPOLL) || defined (USE_DEVPOLL) done = process_fds(manager, manager->events, cc); #elif defined(USE_SELECT) process_fds(manager, maxfd, manager->read_fds_copy, manager->write_fds_copy); /* * Process reads on internal, control fd. */ if (FD_ISSET(ctlfd, manager->read_fds_copy)) done = process_ctlfd(manager); #endif } manager_log(manager, TRACE, "%s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_EXITING, "watcher exiting")); return ((isc_threadresult_t)0); } #endif /* USE_WATCHER_THREAD */ void isc__socketmgr_setreserved(isc_socketmgr_t *manager0, isc_uint32_t reserved) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; REQUIRE(VALID_MANAGER(manager)); manager->reserved = reserved; } void isc__socketmgr_maxudp(isc_socketmgr_t *manager0, int maxudp) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; REQUIRE(VALID_MANAGER(manager)); manager->maxudp = maxudp; } /* * Create a new socket manager. */ static isc_result_t setup_watcher(isc_mem_t *mctx, isc__socketmgr_t *manager) { isc_result_t result; #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) char strbuf[ISC_STRERRORSIZE]; #endif #ifdef USE_KQUEUE manager->nevents = ISC_SOCKET_MAXEVENTS; manager->events = isc_mem_get(mctx, sizeof(struct kevent) * manager->nevents); if (manager->events == NULL) return (ISC_R_NOMEMORY); manager->kqueue_fd = kqueue(); if (manager->kqueue_fd == -1) { result = isc__errno2result(errno); isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "kqueue %s: %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); isc_mem_put(mctx, manager->events, sizeof(struct kevent) * manager->nevents); return (result); } #ifdef USE_WATCHER_THREAD result = watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ); if (result != ISC_R_SUCCESS) { close(manager->kqueue_fd); isc_mem_put(mctx, manager->events, sizeof(struct kevent) * manager->nevents); return (result); } #endif /* USE_WATCHER_THREAD */ #elif defined(USE_EPOLL) manager->nevents = ISC_SOCKET_MAXEVENTS; manager->events = isc_mem_get(mctx, sizeof(struct epoll_event) * manager->nevents); if (manager->events == NULL) return (ISC_R_NOMEMORY); manager->epoll_fd = epoll_create(manager->nevents); if (manager->epoll_fd == -1) { result = isc__errno2result(errno); isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "epoll_create %s: %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); isc_mem_put(mctx, manager->events, sizeof(struct epoll_event) * manager->nevents); return (result); } #ifdef USE_WATCHER_THREAD result = watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ); if (result != ISC_R_SUCCESS) { close(manager->epoll_fd); isc_mem_put(mctx, manager->events, sizeof(struct epoll_event) * manager->nevents); return (result); } #endif /* USE_WATCHER_THREAD */ #elif defined(USE_DEVPOLL) manager->nevents = ISC_SOCKET_MAXEVENTS; result = isc_resource_getcurlimit(isc_resource_openfiles, &manager->open_max); if (result != ISC_R_SUCCESS) manager->open_max = 64; manager->calls = 0; manager->events = isc_mem_get(mctx, sizeof(struct pollfd) * manager->nevents); if (manager->events == NULL) return (ISC_R_NOMEMORY); /* * Note: fdpollinfo should be able to support all possible FDs, so * it must have maxsocks entries (not nevents). */ manager->fdpollinfo = isc_mem_get(mctx, sizeof(pollinfo_t) * manager->maxsocks); if (manager->fdpollinfo == NULL) { isc_mem_put(mctx, manager->events, sizeof(struct pollfd) * manager->nevents); return (ISC_R_NOMEMORY); } memset(manager->fdpollinfo, 0, sizeof(pollinfo_t) * manager->maxsocks); manager->devpoll_fd = open("/dev/poll", O_RDWR); if (manager->devpoll_fd == -1) { result = isc__errno2result(errno); isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "open(/dev/poll) %s: %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); isc_mem_put(mctx, manager->events, sizeof(struct pollfd) * manager->nevents); isc_mem_put(mctx, manager->fdpollinfo, sizeof(pollinfo_t) * manager->maxsocks); return (result); } #ifdef USE_WATCHER_THREAD result = watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ); if (result != ISC_R_SUCCESS) { close(manager->devpoll_fd); isc_mem_put(mctx, manager->events, sizeof(struct pollfd) * manager->nevents); isc_mem_put(mctx, manager->fdpollinfo, sizeof(pollinfo_t) * manager->maxsocks); return (result); } #endif /* USE_WATCHER_THREAD */ #elif defined(USE_SELECT) UNUSED(result); #if ISC_SOCKET_MAXSOCKETS > FD_SETSIZE /* * Note: this code should also cover the case of MAXSOCKETS <= * FD_SETSIZE, but we separate the cases to avoid possible portability * issues regarding howmany() and the actual representation of fd_set. */ manager->fd_bufsize = howmany(manager->maxsocks, NFDBITS) * sizeof(fd_mask); #else manager->fd_bufsize = sizeof(fd_set); #endif manager->read_fds = NULL; manager->read_fds_copy = NULL; manager->write_fds = NULL; manager->write_fds_copy = NULL; manager->read_fds = isc_mem_get(mctx, manager->fd_bufsize); if (manager->read_fds != NULL) manager->read_fds_copy = isc_mem_get(mctx, manager->fd_bufsize); if (manager->read_fds_copy != NULL) manager->write_fds = isc_mem_get(mctx, manager->fd_bufsize); if (manager->write_fds != NULL) { manager->write_fds_copy = isc_mem_get(mctx, manager->fd_bufsize); } if (manager->write_fds_copy == NULL) { if (manager->write_fds != NULL) { isc_mem_put(mctx, manager->write_fds, manager->fd_bufsize); } if (manager->read_fds_copy != NULL) { isc_mem_put(mctx, manager->read_fds_copy, manager->fd_bufsize); } if (manager->read_fds != NULL) { isc_mem_put(mctx, manager->read_fds, manager->fd_bufsize); } return (ISC_R_NOMEMORY); } memset(manager->read_fds, 0, manager->fd_bufsize); memset(manager->write_fds, 0, manager->fd_bufsize); #ifdef USE_WATCHER_THREAD (void)watch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ); manager->maxfd = manager->pipe_fds[0]; #else /* USE_WATCHER_THREAD */ manager->maxfd = 0; #endif /* USE_WATCHER_THREAD */ #endif /* USE_KQUEUE */ return (ISC_R_SUCCESS); } static void cleanup_watcher(isc_mem_t *mctx, isc__socketmgr_t *manager) { #ifdef USE_WATCHER_THREAD isc_result_t result; result = unwatch_fd(manager, manager->pipe_fds[0], SELECT_POKE_READ); if (result != ISC_R_SUCCESS) { UNEXPECTED_ERROR(__FILE__, __LINE__, "epoll_ctl(DEL) %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed")); } #endif /* USE_WATCHER_THREAD */ #ifdef USE_KQUEUE close(manager->kqueue_fd); isc_mem_put(mctx, manager->events, sizeof(struct kevent) * manager->nevents); #elif defined(USE_EPOLL) close(manager->epoll_fd); isc_mem_put(mctx, manager->events, sizeof(struct epoll_event) * manager->nevents); #elif defined(USE_DEVPOLL) close(manager->devpoll_fd); isc_mem_put(mctx, manager->events, sizeof(struct pollfd) * manager->nevents); isc_mem_put(mctx, manager->fdpollinfo, sizeof(pollinfo_t) * manager->maxsocks); #elif defined(USE_SELECT) if (manager->read_fds != NULL) isc_mem_put(mctx, manager->read_fds, manager->fd_bufsize); if (manager->read_fds_copy != NULL) isc_mem_put(mctx, manager->read_fds_copy, manager->fd_bufsize); if (manager->write_fds != NULL) isc_mem_put(mctx, manager->write_fds, manager->fd_bufsize); if (manager->write_fds_copy != NULL) isc_mem_put(mctx, manager->write_fds_copy, manager->fd_bufsize); #endif /* USE_KQUEUE */ } isc_result_t isc__socketmgr_create(isc_mem_t *mctx, isc_socketmgr_t **managerp) { return (isc__socketmgr_create2(mctx, managerp, 0)); } isc_result_t isc__socketmgr_create2(isc_mem_t *mctx, isc_socketmgr_t **managerp, unsigned int maxsocks) { int i; isc__socketmgr_t *manager; #ifdef USE_WATCHER_THREAD char strbuf[ISC_STRERRORSIZE]; #endif isc_result_t result; REQUIRE(managerp != NULL && *managerp == NULL); #ifdef USE_SHARED_MANAGER if (socketmgr != NULL) { /* Don't allow maxsocks to be updated */ if (maxsocks > 0 && socketmgr->maxsocks != maxsocks) return (ISC_R_EXISTS); socketmgr->refs++; *managerp = (isc_socketmgr_t *)socketmgr; return (ISC_R_SUCCESS); } #endif /* USE_SHARED_MANAGER */ if (maxsocks == 0) maxsocks = ISC_SOCKET_MAXSOCKETS; manager = isc_mem_get(mctx, sizeof(*manager)); if (manager == NULL) return (ISC_R_NOMEMORY); /* zero-clear so that necessary cleanup on failure will be easy */ memset(manager, 0, sizeof(*manager)); manager->maxsocks = maxsocks; manager->reserved = 0; manager->maxudp = 0; manager->fds = isc_mem_get(mctx, manager->maxsocks * sizeof(isc__socket_t *)); if (manager->fds == NULL) { result = ISC_R_NOMEMORY; goto free_manager; } manager->fdstate = isc_mem_get(mctx, manager->maxsocks * sizeof(int)); if (manager->fdstate == NULL) { result = ISC_R_NOMEMORY; goto free_manager; } manager->stats = NULL; manager->common.methods = &socketmgrmethods; manager->common.magic = ISCAPI_SOCKETMGR_MAGIC; manager->common.impmagic = SOCKET_MANAGER_MAGIC; manager->mctx = NULL; memset(manager->fds, 0, manager->maxsocks * sizeof(isc_socket_t *)); ISC_LIST_INIT(manager->socklist); result = isc_mutex_init(&manager->lock); if (result != ISC_R_SUCCESS) goto free_manager; manager->fdlock = isc_mem_get(mctx, FDLOCK_COUNT * sizeof(isc_mutex_t)); if (manager->fdlock == NULL) { result = ISC_R_NOMEMORY; goto cleanup_lock; } for (i = 0; i < FDLOCK_COUNT; i++) { result = isc_mutex_init(&manager->fdlock[i]); if (result != ISC_R_SUCCESS) { while (--i >= 0) DESTROYLOCK(&manager->fdlock[i]); isc_mem_put(mctx, manager->fdlock, FDLOCK_COUNT * sizeof(isc_mutex_t)); manager->fdlock = NULL; goto cleanup_lock; } } #ifdef USE_WATCHER_THREAD if (isc_condition_init(&manager->shutdown_ok) != ISC_R_SUCCESS) { UNEXPECTED_ERROR(__FILE__, __LINE__, "isc_condition_init() %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed")); result = ISC_R_UNEXPECTED; goto cleanup_lock; } /* * Create the special fds that will be used to wake up the * select/poll loop when something internal needs to be done. */ if (pipe(manager->pipe_fds) != 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "pipe() %s: %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); result = ISC_R_UNEXPECTED; goto cleanup_condition; } RUNTIME_CHECK(make_nonblock(manager->pipe_fds[0]) == ISC_R_SUCCESS); #if 0 RUNTIME_CHECK(make_nonblock(manager->pipe_fds[1]) == ISC_R_SUCCESS); #endif #endif /* USE_WATCHER_THREAD */ #ifdef USE_SHARED_MANAGER manager->refs = 1; #endif /* USE_SHARED_MANAGER */ /* * Set up initial state for the select loop */ result = setup_watcher(mctx, manager); if (result != ISC_R_SUCCESS) goto cleanup; memset(manager->fdstate, 0, manager->maxsocks * sizeof(int)); #ifdef USE_WATCHER_THREAD /* * Start up the select/poll thread. */ if (isc_thread_create(watcher, manager, &manager->watcher) != ISC_R_SUCCESS) { UNEXPECTED_ERROR(__FILE__, __LINE__, "isc_thread_create() %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed")); cleanup_watcher(mctx, manager); result = ISC_R_UNEXPECTED; goto cleanup; } #endif /* USE_WATCHER_THREAD */ isc_mem_attach(mctx, &manager->mctx); #ifdef USE_SHARED_MANAGER socketmgr = manager; #endif /* USE_SHARED_MANAGER */ *managerp = (isc_socketmgr_t *)manager; return (ISC_R_SUCCESS); cleanup: #ifdef USE_WATCHER_THREAD (void)close(manager->pipe_fds[0]); (void)close(manager->pipe_fds[1]); #endif /* USE_WATCHER_THREAD */ #ifdef USE_WATCHER_THREAD cleanup_condition: (void)isc_condition_destroy(&manager->shutdown_ok); #endif /* USE_WATCHER_THREAD */ cleanup_lock: if (manager->fdlock != NULL) { for (i = 0; i < FDLOCK_COUNT; i++) DESTROYLOCK(&manager->fdlock[i]); } DESTROYLOCK(&manager->lock); free_manager: if (manager->fdlock != NULL) { isc_mem_put(mctx, manager->fdlock, FDLOCK_COUNT * sizeof(isc_mutex_t)); } if (manager->fdstate != NULL) { isc_mem_put(mctx, manager->fdstate, manager->maxsocks * sizeof(int)); } if (manager->fds != NULL) { isc_mem_put(mctx, manager->fds, manager->maxsocks * sizeof(isc_socket_t *)); } isc_mem_put(mctx, manager, sizeof(*manager)); return (result); } isc_result_t isc_socketmgr_getmaxsockets(isc_socketmgr_t *manager0, unsigned int *nsockp) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; REQUIRE(VALID_MANAGER(manager)); REQUIRE(nsockp != NULL); *nsockp = manager->maxsocks; return (ISC_R_SUCCESS); } void isc_socketmgr_setstats(isc_socketmgr_t *manager0, isc_stats_t *stats) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; REQUIRE(VALID_MANAGER(manager)); REQUIRE(ISC_LIST_EMPTY(manager->socklist)); REQUIRE(manager->stats == NULL); REQUIRE(isc_stats_ncounters(stats) == isc_sockstatscounter_max); isc_stats_attach(stats, &manager->stats); } void isc__socketmgr_destroy(isc_socketmgr_t **managerp) { isc__socketmgr_t *manager; int i; isc_mem_t *mctx; /* * Destroy a socket manager. */ REQUIRE(managerp != NULL); manager = (isc__socketmgr_t *)*managerp; REQUIRE(VALID_MANAGER(manager)); #ifdef USE_SHARED_MANAGER manager->refs--; if (manager->refs > 0) { *managerp = NULL; return; } socketmgr = NULL; #endif /* USE_SHARED_MANAGER */ LOCK(&manager->lock); /* * Wait for all sockets to be destroyed. */ while (!ISC_LIST_EMPTY(manager->socklist)) { #ifdef USE_WATCHER_THREAD manager_log(manager, CREATION, "%s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_SOCKETSREMAIN, "sockets exist")); WAIT(&manager->shutdown_ok, &manager->lock); #else /* USE_WATCHER_THREAD */ UNLOCK(&manager->lock); isc__taskmgr_dispatch(NULL); LOCK(&manager->lock); #endif /* USE_WATCHER_THREAD */ } UNLOCK(&manager->lock); /* * Here, poke our select/poll thread. Do this by closing the write * half of the pipe, which will send EOF to the read half. * This is currently a no-op in the non-threaded case. */ select_poke(manager, 0, SELECT_POKE_SHUTDOWN); #ifdef USE_WATCHER_THREAD /* * Wait for thread to exit. */ if (isc_thread_join(manager->watcher, NULL) != ISC_R_SUCCESS) UNEXPECTED_ERROR(__FILE__, __LINE__, "isc_thread_join() %s", isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed")); #endif /* USE_WATCHER_THREAD */ /* * Clean up. */ cleanup_watcher(manager->mctx, manager); #ifdef USE_WATCHER_THREAD (void)close(manager->pipe_fds[0]); (void)close(manager->pipe_fds[1]); (void)isc_condition_destroy(&manager->shutdown_ok); #endif /* USE_WATCHER_THREAD */ for (i = 0; i < (int)manager->maxsocks; i++) if (manager->fdstate[i] == CLOSE_PENDING) /* no need to lock */ (void)close(i); isc_mem_put(manager->mctx, manager->fds, manager->maxsocks * sizeof(isc__socket_t *)); isc_mem_put(manager->mctx, manager->fdstate, manager->maxsocks * sizeof(int)); if (manager->stats != NULL) isc_stats_detach(&manager->stats); if (manager->fdlock != NULL) { for (i = 0; i < FDLOCK_COUNT; i++) DESTROYLOCK(&manager->fdlock[i]); isc_mem_put(manager->mctx, manager->fdlock, FDLOCK_COUNT * sizeof(isc_mutex_t)); } DESTROYLOCK(&manager->lock); manager->common.magic = 0; manager->common.impmagic = 0; mctx= manager->mctx; isc_mem_put(mctx, manager, sizeof(*manager)); isc_mem_detach(&mctx); *managerp = NULL; #ifdef USE_SHARED_MANAGER socketmgr = NULL; #endif } static isc_result_t socket_recv(isc__socket_t *sock, isc_socketevent_t *dev, isc_task_t *task, unsigned int flags) { int io_state; isc_boolean_t have_lock = ISC_FALSE; isc_task_t *ntask = NULL; isc_result_t result = ISC_R_SUCCESS; dev->ev_sender = task; if (sock->type == isc_sockettype_udp) { io_state = doio_recv(sock, dev); } else { LOCK(&sock->lock); have_lock = ISC_TRUE; if (ISC_LIST_EMPTY(sock->recv_list)) io_state = doio_recv(sock, dev); else io_state = DOIO_SOFT; } switch (io_state) { case DOIO_SOFT: /* * We couldn't read all or part of the request right now, so * queue it. * * Attach to socket and to task */ isc_task_attach(task, &ntask); dev->attributes |= ISC_SOCKEVENTATTR_ATTACHED; if (!have_lock) { LOCK(&sock->lock); have_lock = ISC_TRUE; } /* * Enqueue the request. If the socket was previously not being * watched, poke the watcher to start paying attention to it. */ if (ISC_LIST_EMPTY(sock->recv_list) && !sock->pending_recv) select_poke(sock->manager, sock->fd, SELECT_POKE_READ); ISC_LIST_ENQUEUE(sock->recv_list, dev, ev_link); socket_log(sock, NULL, EVENT, NULL, 0, 0, "socket_recv: event %p -> task %p", dev, ntask); if ((flags & ISC_SOCKFLAG_IMMEDIATE) != 0) result = ISC_R_INPROGRESS; break; case DOIO_EOF: dev->result = ISC_R_EOF; /* fallthrough */ case DOIO_HARD: case DOIO_SUCCESS: if ((flags & ISC_SOCKFLAG_IMMEDIATE) == 0) send_recvdone_event(sock, &dev); break; } if (have_lock) UNLOCK(&sock->lock); return (result); } isc_result_t isc__socket_recvv(isc_socket_t *sock0, isc_bufferlist_t *buflist, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_socketevent_t *dev; isc__socketmgr_t *manager; unsigned int iocount; isc_buffer_t *buffer; REQUIRE(VALID_SOCKET(sock)); REQUIRE(buflist != NULL); REQUIRE(!ISC_LIST_EMPTY(*buflist)); REQUIRE(task != NULL); REQUIRE(action != NULL); manager = sock->manager; REQUIRE(VALID_MANAGER(manager)); iocount = isc_bufferlist_availablecount(buflist); REQUIRE(iocount > 0); INSIST(sock->bound); dev = allocate_socketevent(manager->mctx, sock, ISC_SOCKEVENT_RECVDONE, action, arg); if (dev == NULL) return (ISC_R_NOMEMORY); /* * UDP sockets are always partial read */ if (sock->type == isc_sockettype_udp) dev->minimum = 1; else { if (minimum == 0) dev->minimum = iocount; else dev->minimum = minimum; } /* * Move each buffer from the passed in list to our internal one. */ buffer = ISC_LIST_HEAD(*buflist); while (buffer != NULL) { ISC_LIST_DEQUEUE(*buflist, buffer, link); ISC_LIST_ENQUEUE(dev->bufferlist, buffer, link); buffer = ISC_LIST_HEAD(*buflist); } return (socket_recv(sock, dev, task, 0)); } isc_result_t isc__socket_recv(isc_socket_t *sock0, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_taskaction_t action, void *arg) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_socketevent_t *dev; isc__socketmgr_t *manager; REQUIRE(VALID_SOCKET(sock)); REQUIRE(action != NULL); manager = sock->manager; REQUIRE(VALID_MANAGER(manager)); INSIST(sock->bound); dev = allocate_socketevent(manager->mctx, sock, ISC_SOCKEVENT_RECVDONE, action, arg); if (dev == NULL) return (ISC_R_NOMEMORY); return (isc__socket_recv2(sock0, region, minimum, task, dev, 0)); } isc_result_t isc__socket_recv2(isc_socket_t *sock0, isc_region_t *region, unsigned int minimum, isc_task_t *task, isc_socketevent_t *event, unsigned int flags) { isc__socket_t *sock = (isc__socket_t *)sock0; event->ev_sender = sock; event->result = ISC_R_UNSET; ISC_LIST_INIT(event->bufferlist); event->region = *region; event->n = 0; event->offset = 0; event->attributes = 0; /* * UDP sockets are always partial read. */ if (sock->type == isc_sockettype_udp) event->minimum = 1; else { if (minimum == 0) event->minimum = region->length; else event->minimum = minimum; } return (socket_recv(sock, event, task, flags)); } static isc_result_t socket_send(isc__socket_t *sock, isc_socketevent_t *dev, isc_task_t *task, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, unsigned int flags) { int io_state; isc_boolean_t have_lock = ISC_FALSE; isc_task_t *ntask = NULL; isc_result_t result = ISC_R_SUCCESS; dev->ev_sender = task; set_dev_address(address, sock, dev); if (pktinfo != NULL) { dev->attributes |= ISC_SOCKEVENTATTR_PKTINFO; dev->pktinfo = *pktinfo; if (!isc_sockaddr_issitelocal(&dev->address) && !isc_sockaddr_islinklocal(&dev->address)) { socket_log(sock, NULL, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_PKTINFOPROVIDED, "pktinfo structure provided, ifindex %u " "(set to 0)", pktinfo->ipi6_ifindex); /* * Set the pktinfo index to 0 here, to let the * kernel decide what interface it should send on. */ dev->pktinfo.ipi6_ifindex = 0; } } if (sock->type == isc_sockettype_udp) io_state = doio_send(sock, dev); else { LOCK(&sock->lock); have_lock = ISC_TRUE; if (ISC_LIST_EMPTY(sock->send_list)) io_state = doio_send(sock, dev); else io_state = DOIO_SOFT; } switch (io_state) { case DOIO_SOFT: /* * We couldn't send all or part of the request right now, so * queue it unless ISC_SOCKFLAG_NORETRY is set. */ if ((flags & ISC_SOCKFLAG_NORETRY) == 0) { isc_task_attach(task, &ntask); dev->attributes |= ISC_SOCKEVENTATTR_ATTACHED; if (!have_lock) { LOCK(&sock->lock); have_lock = ISC_TRUE; } /* * Enqueue the request. If the socket was previously * not being watched, poke the watcher to start * paying attention to it. */ if (ISC_LIST_EMPTY(sock->send_list) && !sock->pending_send) select_poke(sock->manager, sock->fd, SELECT_POKE_WRITE); ISC_LIST_ENQUEUE(sock->send_list, dev, ev_link); socket_log(sock, NULL, EVENT, NULL, 0, 0, "socket_send: event %p -> task %p", dev, ntask); if ((flags & ISC_SOCKFLAG_IMMEDIATE) != 0) result = ISC_R_INPROGRESS; break; } case DOIO_HARD: case DOIO_SUCCESS: if ((flags & ISC_SOCKFLAG_IMMEDIATE) == 0) send_senddone_event(sock, &dev); break; } if (have_lock) UNLOCK(&sock->lock); return (result); } isc_result_t isc__socket_send(isc_socket_t *sock, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg) { /* * REQUIRE() checking is performed in isc_socket_sendto(). */ return (isc__socket_sendto(sock, region, task, action, arg, NULL, NULL)); } isc_result_t isc__socket_sendto(isc_socket_t *sock0, isc_region_t *region, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_socketevent_t *dev; isc__socketmgr_t *manager; REQUIRE(VALID_SOCKET(sock)); REQUIRE(region != NULL); REQUIRE(task != NULL); REQUIRE(action != NULL); manager = sock->manager; REQUIRE(VALID_MANAGER(manager)); INSIST(sock->bound); dev = allocate_socketevent(manager->mctx, sock, ISC_SOCKEVENT_SENDDONE, action, arg); if (dev == NULL) return (ISC_R_NOMEMORY); dev->region = *region; return (socket_send(sock, dev, task, address, pktinfo, 0)); } isc_result_t isc__socket_sendv(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg) { return (isc__socket_sendtov2(sock, buflist, task, action, arg, NULL, NULL, 0)); } isc_result_t isc__socket_sendtov(isc_socket_t *sock, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo) { return (isc__socket_sendtov2(sock, buflist, task, action, arg, address, pktinfo, 0)); } isc_result_t isc__socket_sendtov2(isc_socket_t *sock0, isc_bufferlist_t *buflist, isc_task_t *task, isc_taskaction_t action, void *arg, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, unsigned int flags) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_socketevent_t *dev; isc__socketmgr_t *manager; unsigned int iocount; isc_buffer_t *buffer; REQUIRE(VALID_SOCKET(sock)); REQUIRE(buflist != NULL); REQUIRE(!ISC_LIST_EMPTY(*buflist)); REQUIRE(task != NULL); REQUIRE(action != NULL); manager = sock->manager; REQUIRE(VALID_MANAGER(manager)); iocount = isc_bufferlist_usedcount(buflist); REQUIRE(iocount > 0); dev = allocate_socketevent(manager->mctx, sock, ISC_SOCKEVENT_SENDDONE, action, arg); if (dev == NULL) return (ISC_R_NOMEMORY); /* * Move each buffer from the passed in list to our internal one. */ buffer = ISC_LIST_HEAD(*buflist); while (buffer != NULL) { ISC_LIST_DEQUEUE(*buflist, buffer, link); ISC_LIST_ENQUEUE(dev->bufferlist, buffer, link); buffer = ISC_LIST_HEAD(*buflist); } return (socket_send(sock, dev, task, address, pktinfo, flags)); } isc_result_t isc__socket_sendto2(isc_socket_t *sock0, isc_region_t *region, isc_task_t *task, isc_sockaddr_t *address, struct in6_pktinfo *pktinfo, isc_socketevent_t *event, unsigned int flags) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); REQUIRE((flags & ~(ISC_SOCKFLAG_IMMEDIATE|ISC_SOCKFLAG_NORETRY)) == 0); if ((flags & ISC_SOCKFLAG_NORETRY) != 0) REQUIRE(sock->type == isc_sockettype_udp); event->ev_sender = sock; event->result = ISC_R_UNSET; ISC_LIST_INIT(event->bufferlist); event->region = *region; event->n = 0; event->offset = 0; event->attributes &= ~ISC_SOCKEVENTATTR_ATTACHED; return (socket_send(sock, event, task, address, pktinfo, flags)); } void isc__socket_cleanunix(isc_sockaddr_t *sockaddr, isc_boolean_t active) { #ifdef ISC_PLATFORM_HAVESYSUNH int s; struct stat sb; char strbuf[ISC_STRERRORSIZE]; if (sockaddr->type.sa.sa_family != AF_UNIX) return; #ifndef S_ISSOCK #if defined(S_IFMT) && defined(S_IFSOCK) #define S_ISSOCK(mode) ((mode & S_IFMT)==S_IFSOCK) #elif defined(_S_IFMT) && defined(S_IFSOCK) #define S_ISSOCK(mode) ((mode & _S_IFMT)==S_IFSOCK) #endif #endif #ifndef S_ISFIFO #if defined(S_IFMT) && defined(S_IFIFO) #define S_ISFIFO(mode) ((mode & S_IFMT)==S_IFIFO) #elif defined(_S_IFMT) && defined(S_IFIFO) #define S_ISFIFO(mode) ((mode & _S_IFMT)==S_IFIFO) #endif #endif #if !defined(S_ISFIFO) && !defined(S_ISSOCK) #error You need to define S_ISFIFO and S_ISSOCK as appropriate for your platform. See <sys/stat.h>. #endif #ifndef S_ISFIFO #define S_ISFIFO(mode) 0 #endif #ifndef S_ISSOCK #define S_ISSOCK(mode) 0 #endif if (active) { if (stat(sockaddr->type.sunix.sun_path, &sb) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, "isc_socket_cleanunix: stat(%s): %s", sockaddr->type.sunix.sun_path, strbuf); return; } if (!(S_ISSOCK(sb.st_mode) || S_ISFIFO(sb.st_mode))) { isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, "isc_socket_cleanunix: %s: not a socket", sockaddr->type.sunix.sun_path); return; } if (unlink(sockaddr->type.sunix.sun_path) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, "isc_socket_cleanunix: unlink(%s): %s", sockaddr->type.sunix.sun_path, strbuf); } return; } s = socket(AF_UNIX, SOCK_STREAM, 0); if (s < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING, "isc_socket_cleanunix: socket(%s): %s", sockaddr->type.sunix.sun_path, strbuf); return; } if (stat(sockaddr->type.sunix.sun_path, &sb) < 0) { switch (errno) { case ENOENT: /* We exited cleanly last time */ break; default: isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING, "isc_socket_cleanunix: stat(%s): %s", sockaddr->type.sunix.sun_path, strbuf); break; } goto cleanup; } if (!(S_ISSOCK(sb.st_mode) || S_ISFIFO(sb.st_mode))) { isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING, "isc_socket_cleanunix: %s: not a socket", sockaddr->type.sunix.sun_path); goto cleanup; } if (connect(s, (struct sockaddr *)&sockaddr->type.sunix, sizeof(sockaddr->type.sunix)) < 0) { switch (errno) { case ECONNREFUSED: case ECONNRESET: if (unlink(sockaddr->type.sunix.sun_path) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING, "isc_socket_cleanunix: " "unlink(%s): %s", sockaddr->type.sunix.sun_path, strbuf); } break; default: isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_WARNING, "isc_socket_cleanunix: connect(%s): %s", sockaddr->type.sunix.sun_path, strbuf); break; } } cleanup: close(s); #else UNUSED(sockaddr); UNUSED(active); #endif } isc_result_t isc__socket_permunix(isc_sockaddr_t *sockaddr, isc_uint32_t perm, isc_uint32_t owner, isc_uint32_t group) { #ifdef ISC_PLATFORM_HAVESYSUNH isc_result_t result = ISC_R_SUCCESS; char strbuf[ISC_STRERRORSIZE]; char path[sizeof(sockaddr->type.sunix.sun_path)]; #ifdef NEED_SECURE_DIRECTORY char *slash; #endif REQUIRE(sockaddr->type.sa.sa_family == AF_UNIX); INSIST(strlen(sockaddr->type.sunix.sun_path) < sizeof(path)); strcpy(path, sockaddr->type.sunix.sun_path); #ifdef NEED_SECURE_DIRECTORY slash = strrchr(path, '/'); if (slash != NULL) { if (slash != path) *slash = '\0'; else strcpy(path, "/"); } else strcpy(path, "."); #endif if (chmod(path, perm) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, "isc_socket_permunix: chmod(%s, %d): %s", path, perm, strbuf); result = ISC_R_FAILURE; } if (chown(path, owner, group) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); isc_log_write(isc_lctx, ISC_LOGCATEGORY_GENERAL, ISC_LOGMODULE_SOCKET, ISC_LOG_ERROR, "isc_socket_permunix: chown(%s, %d, %d): %s", path, owner, group, strbuf); result = ISC_R_FAILURE; } return (result); #else UNUSED(sockaddr); UNUSED(perm); UNUSED(owner); UNUSED(group); return (ISC_R_NOTIMPLEMENTED); #endif } isc_result_t isc__socket_bind(isc_socket_t *sock0, isc_sockaddr_t *sockaddr, unsigned int options) { isc__socket_t *sock = (isc__socket_t *)sock0; char strbuf[ISC_STRERRORSIZE]; int on = 1; REQUIRE(VALID_SOCKET(sock)); LOCK(&sock->lock); INSIST(!sock->bound); INSIST(!sock->dupped); if (sock->pf != sockaddr->type.sa.sa_family) { UNLOCK(&sock->lock); return (ISC_R_FAMILYMISMATCH); } /* * Only set SO_REUSEADDR when we want a specific port. */ #ifdef AF_UNIX if (sock->pf == AF_UNIX) goto bind_socket; #endif if ((options & ISC_SOCKET_REUSEADDRESS) != 0 && isc_sockaddr_getport(sockaddr) != (in_port_t)0 && setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) < 0) { UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d) %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed")); /* Press on... */ } #ifdef AF_UNIX bind_socket: #endif if (bind(sock->fd, &sockaddr->type.sa, sockaddr->length) < 0) { inc_stats(sock->manager->stats, sock->statsindex[STATID_BINDFAIL]); UNLOCK(&sock->lock); switch (errno) { case EACCES: return (ISC_R_NOPERM); case EADDRNOTAVAIL: return (ISC_R_ADDRNOTAVAIL); case EADDRINUSE: return (ISC_R_ADDRINUSE); case EINVAL: return (ISC_R_BOUND); default: isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "bind: %s", strbuf); return (ISC_R_UNEXPECTED); } } socket_log(sock, sockaddr, TRACE, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_BOUND, "bound"); sock->bound = 1; UNLOCK(&sock->lock); return (ISC_R_SUCCESS); } /* * Enable this only for specific OS versions, and only when they have repaired * their problems with it. Until then, this is is broken and needs to be * diabled by default. See RT22589 for details. */ #undef ENABLE_ACCEPTFILTER isc_result_t isc__socket_filter(isc_socket_t *sock0, const char *filter) { isc__socket_t *sock = (isc__socket_t *)sock0; #if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER) char strbuf[ISC_STRERRORSIZE]; struct accept_filter_arg afa; #else UNUSED(sock); UNUSED(filter); #endif REQUIRE(VALID_SOCKET(sock)); #if defined(SO_ACCEPTFILTER) && defined(ENABLE_ACCEPTFILTER) bzero(&afa, sizeof(afa)); strncpy(afa.af_name, filter, sizeof(afa.af_name)); if (setsockopt(sock->fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa)) == -1) { isc__strerror(errno, strbuf, sizeof(strbuf)); socket_log(sock, NULL, CREATION, isc_msgcat, ISC_MSGSET_SOCKET, ISC_MSG_FILTER, "setsockopt(SO_ACCEPTFILTER): %s", strbuf); return (ISC_R_FAILURE); } return (ISC_R_SUCCESS); #else return (ISC_R_NOTIMPLEMENTED); #endif } /* * Set up to listen on a given socket. We do this by creating an internal * event that will be dispatched when the socket has read activity. The * watcher will send the internal event to the task when there is a new * connection. * * Unlike in read, we don't preallocate a done event here. Every time there * is a new connection we'll have to allocate a new one anyway, so we might * as well keep things simple rather than having to track them. */ isc_result_t isc__socket_listen(isc_socket_t *sock0, unsigned int backlog) { isc__socket_t *sock = (isc__socket_t *)sock0; char strbuf[ISC_STRERRORSIZE]; REQUIRE(VALID_SOCKET(sock)); LOCK(&sock->lock); REQUIRE(!sock->listener); REQUIRE(sock->bound); REQUIRE(sock->type == isc_sockettype_tcp || sock->type == isc_sockettype_unix); if (backlog == 0) backlog = SOMAXCONN; if (listen(sock->fd, (int)backlog) < 0) { UNLOCK(&sock->lock); isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "listen: %s", strbuf); return (ISC_R_UNEXPECTED); } sock->listener = 1; UNLOCK(&sock->lock); return (ISC_R_SUCCESS); } /* * This should try to do aggressive accept() XXXMLG */ isc_result_t isc__socket_accept(isc_socket_t *sock0, isc_task_t *task, isc_taskaction_t action, void *arg) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_socket_newconnev_t *dev; isc__socketmgr_t *manager; isc_task_t *ntask = NULL; isc__socket_t *nsock; isc_result_t result; isc_boolean_t do_poke = ISC_FALSE; REQUIRE(VALID_SOCKET(sock)); manager = sock->manager; REQUIRE(VALID_MANAGER(manager)); LOCK(&sock->lock); REQUIRE(sock->listener); /* * Sender field is overloaded here with the task we will be sending * this event to. Just before the actual event is delivered the * actual ev_sender will be touched up to be the socket. */ dev = (isc_socket_newconnev_t *) isc_event_allocate(manager->mctx, task, ISC_SOCKEVENT_NEWCONN, action, arg, sizeof(*dev)); if (dev == NULL) { UNLOCK(&sock->lock); return (ISC_R_NOMEMORY); } ISC_LINK_INIT(dev, ev_link); result = allocate_socket(manager, sock->type, &nsock); if (result != ISC_R_SUCCESS) { isc_event_free(ISC_EVENT_PTR(&dev)); UNLOCK(&sock->lock); return (result); } /* * Attach to socket and to task. */ isc_task_attach(task, &ntask); if (isc_task_exiting(ntask)) { free_socket(&nsock); isc_task_detach(&ntask); isc_event_free(ISC_EVENT_PTR(&dev)); UNLOCK(&sock->lock); return (ISC_R_SHUTTINGDOWN); } nsock->references++; nsock->statsindex = sock->statsindex; dev->ev_sender = ntask; dev->newsocket = (isc_socket_t *)nsock; /* * Poke watcher here. We still have the socket locked, so there * is no race condition. We will keep the lock for such a short * bit of time waking it up now or later won't matter all that much. */ if (ISC_LIST_EMPTY(sock->accept_list)) do_poke = ISC_TRUE; ISC_LIST_ENQUEUE(sock->accept_list, dev, ev_link); if (do_poke) select_poke(manager, sock->fd, SELECT_POKE_ACCEPT); UNLOCK(&sock->lock); return (ISC_R_SUCCESS); } isc_result_t isc__socket_connect(isc_socket_t *sock0, isc_sockaddr_t *addr, isc_task_t *task, isc_taskaction_t action, void *arg) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_socket_connev_t *dev; isc_task_t *ntask = NULL; isc__socketmgr_t *manager; int cc; char strbuf[ISC_STRERRORSIZE]; char addrbuf[ISC_SOCKADDR_FORMATSIZE]; REQUIRE(VALID_SOCKET(sock)); REQUIRE(addr != NULL); REQUIRE(task != NULL); REQUIRE(action != NULL); manager = sock->manager; REQUIRE(VALID_MANAGER(manager)); REQUIRE(addr != NULL); if (isc_sockaddr_ismulticast(addr)) return (ISC_R_MULTICAST); LOCK(&sock->lock); REQUIRE(!sock->connecting); dev = (isc_socket_connev_t *)isc_event_allocate(manager->mctx, sock, ISC_SOCKEVENT_CONNECT, action, arg, sizeof(*dev)); if (dev == NULL) { UNLOCK(&sock->lock); return (ISC_R_NOMEMORY); } ISC_LINK_INIT(dev, ev_link); /* * Try to do the connect right away, as there can be only one * outstanding, and it might happen to complete. */ sock->peer_address = *addr; cc = connect(sock->fd, &addr->type.sa, addr->length); if (cc < 0) { /* * HP-UX "fails" to connect a UDP socket and sets errno to * EINPROGRESS if it's non-blocking. We'd rather regard this as * a success and let the user detect it if it's really an error * at the time of sending a packet on the socket. */ if (sock->type == isc_sockettype_udp && errno == EINPROGRESS) { cc = 0; goto success; } if (SOFT_ERROR(errno) || errno == EINPROGRESS) goto queue; switch (errno) { #define ERROR_MATCH(a, b) case a: dev->result = b; goto err_exit; ERROR_MATCH(EACCES, ISC_R_NOPERM); ERROR_MATCH(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL); ERROR_MATCH(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL); ERROR_MATCH(ECONNREFUSED, ISC_R_CONNREFUSED); ERROR_MATCH(EHOSTUNREACH, ISC_R_HOSTUNREACH); #ifdef EHOSTDOWN ERROR_MATCH(EHOSTDOWN, ISC_R_HOSTUNREACH); #endif ERROR_MATCH(ENETUNREACH, ISC_R_NETUNREACH); ERROR_MATCH(ENOBUFS, ISC_R_NORESOURCES); ERROR_MATCH(EPERM, ISC_R_HOSTUNREACH); ERROR_MATCH(EPIPE, ISC_R_NOTCONNECTED); ERROR_MATCH(ECONNRESET, ISC_R_CONNECTIONRESET); #undef ERROR_MATCH } sock->connected = 0; isc__strerror(errno, strbuf, sizeof(strbuf)); isc_sockaddr_format(addr, addrbuf, sizeof(addrbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "connect(%s) %d/%s", addrbuf, errno, strbuf); UNLOCK(&sock->lock); inc_stats(sock->manager->stats, sock->statsindex[STATID_CONNECTFAIL]); isc_event_free(ISC_EVENT_PTR(&dev)); return (ISC_R_UNEXPECTED); err_exit: sock->connected = 0; isc_task_send(task, ISC_EVENT_PTR(&dev)); UNLOCK(&sock->lock); inc_stats(sock->manager->stats, sock->statsindex[STATID_CONNECTFAIL]); return (ISC_R_SUCCESS); } /* * If connect completed, fire off the done event. */ success: if (cc == 0) { sock->connected = 1; sock->bound = 1; dev->result = ISC_R_SUCCESS; isc_task_send(task, ISC_EVENT_PTR(&dev)); UNLOCK(&sock->lock); inc_stats(sock->manager->stats, sock->statsindex[STATID_CONNECT]); return (ISC_R_SUCCESS); } queue: /* * Attach to task. */ isc_task_attach(task, &ntask); sock->connecting = 1; dev->ev_sender = ntask; /* * Poke watcher here. We still have the socket locked, so there * is no race condition. We will keep the lock for such a short * bit of time waking it up now or later won't matter all that much. */ if (sock->connect_ev == NULL) select_poke(manager, sock->fd, SELECT_POKE_CONNECT); sock->connect_ev = dev; UNLOCK(&sock->lock); return (ISC_R_SUCCESS); } /* * Called when a socket with a pending connect() finishes. */ static void internal_connect(isc_task_t *me, isc_event_t *ev) { isc__socket_t *sock; isc_socket_connev_t *dev; isc_task_t *task; int cc; ISC_SOCKADDR_LEN_T optlen; char strbuf[ISC_STRERRORSIZE]; char peerbuf[ISC_SOCKADDR_FORMATSIZE]; UNUSED(me); INSIST(ev->ev_type == ISC_SOCKEVENT_INTW); sock = ev->ev_sender; INSIST(VALID_SOCKET(sock)); LOCK(&sock->lock); /* * When the internal event was sent the reference count was bumped * to keep the socket around for us. Decrement the count here. */ INSIST(sock->references > 0); sock->references--; if (sock->references == 0) { UNLOCK(&sock->lock); destroy(&sock); return; } /* * Has this event been canceled? */ dev = sock->connect_ev; if (dev == NULL) { INSIST(!sock->connecting); UNLOCK(&sock->lock); return; } INSIST(sock->connecting); sock->connecting = 0; /* * Get any possible error status here. */ optlen = sizeof(cc); if (getsockopt(sock->fd, SOL_SOCKET, SO_ERROR, (void *)&cc, (void *)&optlen) < 0) cc = errno; else errno = cc; if (errno != 0) { /* * If the error is EAGAIN, just re-select on this * fd and pretend nothing strange happened. */ if (SOFT_ERROR(errno) || errno == EINPROGRESS) { sock->connecting = 1; select_poke(sock->manager, sock->fd, SELECT_POKE_CONNECT); UNLOCK(&sock->lock); return; } inc_stats(sock->manager->stats, sock->statsindex[STATID_CONNECTFAIL]); /* * Translate other errors into ISC_R_* flavors. */ switch (errno) { #define ERROR_MATCH(a, b) case a: dev->result = b; break; ERROR_MATCH(EACCES, ISC_R_NOPERM); ERROR_MATCH(EADDRNOTAVAIL, ISC_R_ADDRNOTAVAIL); ERROR_MATCH(EAFNOSUPPORT, ISC_R_ADDRNOTAVAIL); ERROR_MATCH(ECONNREFUSED, ISC_R_CONNREFUSED); ERROR_MATCH(EHOSTUNREACH, ISC_R_HOSTUNREACH); #ifdef EHOSTDOWN ERROR_MATCH(EHOSTDOWN, ISC_R_HOSTUNREACH); #endif ERROR_MATCH(ENETUNREACH, ISC_R_NETUNREACH); ERROR_MATCH(ENOBUFS, ISC_R_NORESOURCES); ERROR_MATCH(EPERM, ISC_R_HOSTUNREACH); ERROR_MATCH(EPIPE, ISC_R_NOTCONNECTED); ERROR_MATCH(ETIMEDOUT, ISC_R_TIMEDOUT); ERROR_MATCH(ECONNRESET, ISC_R_CONNECTIONRESET); #undef ERROR_MATCH default: dev->result = ISC_R_UNEXPECTED; isc_sockaddr_format(&sock->peer_address, peerbuf, sizeof(peerbuf)); isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "internal_connect: connect(%s) %s", peerbuf, strbuf); } } else { inc_stats(sock->manager->stats, sock->statsindex[STATID_CONNECT]); dev->result = ISC_R_SUCCESS; sock->connected = 1; sock->bound = 1; } sock->connect_ev = NULL; UNLOCK(&sock->lock); task = dev->ev_sender; dev->ev_sender = sock; isc_task_sendanddetach(&task, ISC_EVENT_PTR(&dev)); } isc_result_t isc__socket_getpeername(isc_socket_t *sock0, isc_sockaddr_t *addressp) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_result_t result; REQUIRE(VALID_SOCKET(sock)); REQUIRE(addressp != NULL); LOCK(&sock->lock); if (sock->connected) { *addressp = sock->peer_address; result = ISC_R_SUCCESS; } else { result = ISC_R_NOTCONNECTED; } UNLOCK(&sock->lock); return (result); } isc_result_t isc__socket_getsockname(isc_socket_t *sock0, isc_sockaddr_t *addressp) { isc__socket_t *sock = (isc__socket_t *)sock0; ISC_SOCKADDR_LEN_T len; isc_result_t result; char strbuf[ISC_STRERRORSIZE]; REQUIRE(VALID_SOCKET(sock)); REQUIRE(addressp != NULL); LOCK(&sock->lock); if (!sock->bound) { result = ISC_R_NOTBOUND; goto out; } result = ISC_R_SUCCESS; len = sizeof(addressp->type); if (getsockname(sock->fd, &addressp->type.sa, (void *)&len) < 0) { isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "getsockname: %s", strbuf); result = ISC_R_UNEXPECTED; goto out; } addressp->length = (unsigned int)len; out: UNLOCK(&sock->lock); return (result); } /* * Run through the list of events on this socket, and cancel the ones * queued for task "task" of type "how". "how" is a bitmask. */ void isc__socket_cancel(isc_socket_t *sock0, isc_task_t *task, unsigned int how) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); /* * Quick exit if there is nothing to do. Don't even bother locking * in this case. */ if (how == 0) return; LOCK(&sock->lock); /* * All of these do the same thing, more or less. * Each will: * o If the internal event is marked as "posted" try to * remove it from the task's queue. If this fails, mark it * as canceled instead, and let the task clean it up later. * o For each I/O request for that task of that type, post * its done event with status of "ISC_R_CANCELED". * o Reset any state needed. */ if (((how & ISC_SOCKCANCEL_RECV) == ISC_SOCKCANCEL_RECV) && !ISC_LIST_EMPTY(sock->recv_list)) { isc_socketevent_t *dev; isc_socketevent_t *next; isc_task_t *current_task; dev = ISC_LIST_HEAD(sock->recv_list); while (dev != NULL) { current_task = dev->ev_sender; next = ISC_LIST_NEXT(dev, ev_link); if ((task == NULL) || (task == current_task)) { dev->result = ISC_R_CANCELED; send_recvdone_event(sock, &dev); } dev = next; } } if (((how & ISC_SOCKCANCEL_SEND) == ISC_SOCKCANCEL_SEND) && !ISC_LIST_EMPTY(sock->send_list)) { isc_socketevent_t *dev; isc_socketevent_t *next; isc_task_t *current_task; dev = ISC_LIST_HEAD(sock->send_list); while (dev != NULL) { current_task = dev->ev_sender; next = ISC_LIST_NEXT(dev, ev_link); if ((task == NULL) || (task == current_task)) { dev->result = ISC_R_CANCELED; send_senddone_event(sock, &dev); } dev = next; } } if (((how & ISC_SOCKCANCEL_ACCEPT) == ISC_SOCKCANCEL_ACCEPT) && !ISC_LIST_EMPTY(sock->accept_list)) { isc_socket_newconnev_t *dev; isc_socket_newconnev_t *next; isc_task_t *current_task; dev = ISC_LIST_HEAD(sock->accept_list); while (dev != NULL) { current_task = dev->ev_sender; next = ISC_LIST_NEXT(dev, ev_link); if ((task == NULL) || (task == current_task)) { ISC_LIST_UNLINK(sock->accept_list, dev, ev_link); NEWCONNSOCK(dev)->references--; free_socket((isc__socket_t **)&dev->newsocket); dev->result = ISC_R_CANCELED; dev->ev_sender = sock; isc_task_sendanddetach(&current_task, ISC_EVENT_PTR(&dev)); } dev = next; } } /* * Connecting is not a list. */ if (((how & ISC_SOCKCANCEL_CONNECT) == ISC_SOCKCANCEL_CONNECT) && sock->connect_ev != NULL) { isc_socket_connev_t *dev; isc_task_t *current_task; INSIST(sock->connecting); sock->connecting = 0; dev = sock->connect_ev; current_task = dev->ev_sender; if ((task == NULL) || (task == current_task)) { sock->connect_ev = NULL; dev->result = ISC_R_CANCELED; dev->ev_sender = sock; isc_task_sendanddetach(&current_task, ISC_EVENT_PTR(&dev)); } } UNLOCK(&sock->lock); } isc_sockettype_t isc__socket_gettype(isc_socket_t *sock0) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); return (sock->type); } isc_boolean_t isc__socket_isbound(isc_socket_t *sock0) { isc__socket_t *sock = (isc__socket_t *)sock0; isc_boolean_t val; REQUIRE(VALID_SOCKET(sock)); LOCK(&sock->lock); val = ((sock->bound) ? ISC_TRUE : ISC_FALSE); UNLOCK(&sock->lock); return (val); } void isc__socket_ipv6only(isc_socket_t *sock0, isc_boolean_t yes) { isc__socket_t *sock = (isc__socket_t *)sock0; #if defined(IPV6_V6ONLY) int onoff = yes ? 1 : 0; #else UNUSED(yes); UNUSED(sock); #endif REQUIRE(VALID_SOCKET(sock)); INSIST(!sock->dupped); #ifdef IPV6_V6ONLY if (sock->pf == AF_INET6) { if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&onoff, sizeof(int)) < 0) { char strbuf[ISC_STRERRORSIZE]; isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_V6ONLY) " "%s: %s", sock->fd, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } } FIX_IPV6_RECVPKTINFO(sock); /* AIX */ #endif } static void setdscp(isc__socket_t *sock, isc_dscp_t dscp) { #if defined(IP_TOS) || defined(IPV6_TCLASS) int value = dscp << 2; #endif sock->dscp = dscp; #ifdef IP_TOS if (sock->pf == AF_INET) { if (setsockopt(sock->fd, IPPROTO_IP, IP_TOS, (void *)&value, sizeof(value)) < 0) { char strbuf[ISC_STRERRORSIZE]; isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IP_TOS, %.02x) " "%s: %s", sock->fd, value >> 2, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } } #endif #ifdef IPV6_TCLASS if (sock->pf == AF_INET6) { if (setsockopt(sock->fd, IPPROTO_IPV6, IPV6_TCLASS, (void *)&value, sizeof(value)) < 0) { char strbuf[ISC_STRERRORSIZE]; isc__strerror(errno, strbuf, sizeof(strbuf)); UNEXPECTED_ERROR(__FILE__, __LINE__, "setsockopt(%d, IPV6_TCLASS, %.02x) " "%s: %s", sock->fd, dscp >> 2, isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, ISC_MSG_FAILED, "failed"), strbuf); } } #endif } void isc__socket_dscp(isc_socket_t *sock0, isc_dscp_t dscp) { isc__socket_t *sock = (isc__socket_t *)sock0; REQUIRE(VALID_SOCKET(sock)); REQUIRE(dscp < 0x40); #if !defined(IP_TOS) && !defined(IPV6_TCLASS) UNUSED(dscp); #else if (dscp < 0) return; /* The DSCP value must not be changed once it has been set. */ if (isc_dscp_check_value != -1) INSIST(dscp == isc_dscp_check_value); #endif #ifdef notyet REQUIRE(!sock->dupped); #endif setdscp(sock, dscp); } isc_socketevent_t * isc_socket_socketevent(isc_mem_t *mctx, void *sender, isc_eventtype_t eventtype, isc_taskaction_t action, void *arg) { return (allocate_socketevent(mctx, sender, eventtype, action, arg)); } #ifndef USE_WATCHER_THREAD /* * In our assumed scenario, we can simply use a single static object. * XXX: this is not true if the application uses multiple threads with * 'multi-context' mode. Fixing this is a future TODO item. */ static isc_socketwait_t swait_private; int isc__socketmgr_waitevents(isc_socketmgr_t *manager0, struct timeval *tvp, isc_socketwait_t **swaitp) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; int n; #ifdef USE_KQUEUE struct timespec ts, *tsp; #endif #ifdef USE_EPOLL int timeout; #endif #ifdef USE_DEVPOLL isc_result_t result; int pass; struct dvpoll dvp; #endif REQUIRE(swaitp != NULL && *swaitp == NULL); #ifdef USE_SHARED_MANAGER if (manager == NULL) manager = socketmgr; #endif if (manager == NULL) return (0); #ifdef USE_KQUEUE if (tvp != NULL) { ts.tv_sec = tvp->tv_sec; ts.tv_nsec = tvp->tv_usec * 1000; tsp = &ts; } else tsp = NULL; swait_private.nevents = kevent(manager->kqueue_fd, NULL, 0, manager->events, manager->nevents, tsp); n = swait_private.nevents; #elif defined(USE_EPOLL) if (tvp != NULL) timeout = tvp->tv_sec * 1000 + (tvp->tv_usec + 999) / 1000; else timeout = -1; swait_private.nevents = epoll_wait(manager->epoll_fd, manager->events, manager->nevents, timeout); n = swait_private.nevents; #elif defined(USE_DEVPOLL) /* * Re-probe every thousand calls. */ if (manager->calls++ > 1000U) { result = isc_resource_getcurlimit(isc_resource_openfiles, &manager->open_max); if (result != ISC_R_SUCCESS) manager->open_max = 64; manager->calls = 0; } for (pass = 0; pass < 2; pass++) { dvp.dp_fds = manager->events; dvp.dp_nfds = manager->nevents; if (dvp.dp_nfds >= manager->open_max) dvp.dp_nfds = manager->open_max - 1; if (tvp != NULL) { dvp.dp_timeout = tvp->tv_sec * 1000 + (tvp->tv_usec + 999) / 1000; } else dvp.dp_timeout = -1; n = ioctl(manager->devpoll_fd, DP_POLL, &dvp); if (n == -1 && errno == EINVAL) { /* * {OPEN_MAX} may have dropped. Look * up the current value and try again. */ result = isc_resource_getcurlimit( isc_resource_openfiles, &manager->open_max); if (result != ISC_R_SUCCESS) manager->open_max = 64; } else break; } swait_private.nevents = n; #elif defined(USE_SELECT) memmove(manager->read_fds_copy, manager->read_fds, manager->fd_bufsize); memmove(manager->write_fds_copy, manager->write_fds, manager->fd_bufsize); swait_private.readset = manager->read_fds_copy; swait_private.writeset = manager->write_fds_copy; swait_private.maxfd = manager->maxfd + 1; n = select(swait_private.maxfd, swait_private.readset, swait_private.writeset, NULL, tvp); #endif *swaitp = &swait_private; return (n); } isc_result_t isc__socketmgr_dispatch(isc_socketmgr_t *manager0, isc_socketwait_t *swait) { isc__socketmgr_t *manager = (isc__socketmgr_t *)manager0; REQUIRE(swait == &swait_private); #ifdef USE_SHARED_MANAGER if (manager == NULL) manager = socketmgr; #endif if (manager == NULL) return (ISC_R_NOTFOUND); #if defined(USE_KQUEUE) || defined(USE_EPOLL) || defined(USE_DEVPOLL) (void)process_fds(manager, manager->events, swait->nevents); return (ISC_R_SUCCESS); #elif defined(USE_SELECT) process_fds(manager, swait->maxfd, swait->readset, swait->writeset); return (ISC_R_SUCCESS); #endif } #endif /* USE_WATCHER_THREAD */ void isc__socket_setname(isc_socket_t *socket0, const char *name, void *tag) { isc__socket_t *socket = (isc__socket_t *)socket0; /* * Name 'socket'. */ REQUIRE(VALID_SOCKET(socket)); LOCK(&socket->lock); memset(socket->name, 0, sizeof(socket->name)); strncpy(socket->name, name, sizeof(socket->name) - 1); socket->tag = tag; UNLOCK(&socket->lock); } const char * isc__socket_getname(isc_socket_t *socket0) { isc__socket_t *socket = (isc__socket_t *)socket0; return (socket->name); } void * isc__socket_gettag(isc_socket_t *socket0) { isc__socket_t *socket = (isc__socket_t *)socket0; return (socket->tag); } isc_result_t isc__socket_register(void) { return (isc_socket_register(isc__socketmgr_create)); } int isc__socket_getfd(isc_socket_t *socket0) { isc__socket_t *socket = (isc__socket_t *)socket0; return ((short) socket->fd); } #if defined(HAVE_LIBXML2) || defined(HAVE_JSON) static const char * _socktype(isc_sockettype_t type) { if (type == isc_sockettype_udp) return ("udp"); else if (type == isc_sockettype_tcp) return ("tcp"); else if (type == isc_sockettype_unix) return ("unix"); else if (type == isc_sockettype_fdwatch) return ("fdwatch"); else return ("not-initialized"); } #endif #ifdef HAVE_LIBXML2 #define TRY0(a) do { xmlrc = (a); if (xmlrc < 0) goto error; } while(/*CONSTCOND*/0) int isc_socketmgr_renderxml(isc_socketmgr_t *mgr0, xmlTextWriterPtr writer) { isc__socketmgr_t *mgr = (isc__socketmgr_t *)mgr0; isc__socket_t *sock = NULL; char peerbuf[ISC_SOCKADDR_FORMATSIZE]; isc_sockaddr_t addr; ISC_SOCKADDR_LEN_T len; int xmlrc; LOCK(&mgr->lock); #ifdef USE_SHARED_MANAGER TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "references")); TRY0(xmlTextWriterWriteFormatString(writer, "%d", mgr->refs)); TRY0(xmlTextWriterEndElement(writer)); #endif /* USE_SHARED_MANAGER */ TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "sockets")); sock = ISC_LIST_HEAD(mgr->socklist); while (sock != NULL) { LOCK(&sock->lock); TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "socket")); TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "id")); TRY0(xmlTextWriterWriteFormatString(writer, "%p", sock)); TRY0(xmlTextWriterEndElement(writer)); if (sock->name[0] != 0) { TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "name")); TRY0(xmlTextWriterWriteFormatString(writer, "%s", sock->name)); TRY0(xmlTextWriterEndElement(writer)); /* name */ } TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "references")); TRY0(xmlTextWriterWriteFormatString(writer, "%d", sock->references)); TRY0(xmlTextWriterEndElement(writer)); TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "type", ISC_XMLCHAR _socktype(sock->type))); if (sock->connected) { isc_sockaddr_format(&sock->peer_address, peerbuf, sizeof(peerbuf)); TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "peer-address", ISC_XMLCHAR peerbuf)); } len = sizeof(addr); if (getsockname(sock->fd, &addr.type.sa, (void *)&len) == 0) { isc_sockaddr_format(&addr, peerbuf, sizeof(peerbuf)); TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "local-address", ISC_XMLCHAR peerbuf)); } TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "states")); if (sock->pending_recv) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "pending-receive")); if (sock->pending_send) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "pending-send")); if (sock->pending_accept) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "pending_accept")); if (sock->listener) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "listener")); if (sock->connected) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "connected")); if (sock->connecting) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "connecting")); if (sock->bound) TRY0(xmlTextWriterWriteElement(writer, ISC_XMLCHAR "state", ISC_XMLCHAR "bound")); TRY0(xmlTextWriterEndElement(writer)); /* states */ TRY0(xmlTextWriterEndElement(writer)); /* socket */ UNLOCK(&sock->lock); sock = ISC_LIST_NEXT(sock, link); } TRY0(xmlTextWriterEndElement(writer)); /* sockets */ error: if (sock != NULL) UNLOCK(&sock->lock); UNLOCK(&mgr->lock); return (xmlrc); } #endif /* HAVE_LIBXML2 */ #ifdef HAVE_JSON #define CHECKMEM(m) do { \ if (m == NULL) { \ result = ISC_R_NOMEMORY;\ goto error;\ } \ } while(/*CONSTCOND*/0) isc_result_t isc_socketmgr_renderjson(isc_socketmgr_t *mgr0, json_object *stats) { isc_result_t result = ISC_R_SUCCESS; isc__socketmgr_t *mgr = (isc__socketmgr_t *)mgr0; isc__socket_t *sock = NULL; char peerbuf[ISC_SOCKADDR_FORMATSIZE]; isc_sockaddr_t addr; ISC_SOCKADDR_LEN_T len; json_object *obj, *array = json_object_new_array(); CHECKMEM(array); LOCK(&mgr->lock); #ifdef USE_SHARED_MANAGER obj = json_object_new_int(mgr->refs); CHECKMEM(obj); json_object_object_add(stats, "references", obj); #endif /* USE_SHARED_MANAGER */ sock = ISC_LIST_HEAD(mgr->socklist); while (sock != NULL) { json_object *states, *entry = json_object_new_object(); char buf[255]; CHECKMEM(entry); json_object_array_add(array, entry); LOCK(&sock->lock); sprintf(buf, "%p", sock); obj = json_object_new_string(buf); CHECKMEM(obj); json_object_object_add(entry, "id", obj); if (sock->name[0] != 0) { obj = json_object_new_string(sock->name); CHECKMEM(obj); json_object_object_add(entry, "name", obj); } obj = json_object_new_int(sock->references); CHECKMEM(obj); json_object_object_add(entry, "references", obj); obj = json_object_new_string(_socktype(sock->type)); CHECKMEM(obj); json_object_object_add(entry, "type", obj); if (sock->connected) { isc_sockaddr_format(&sock->peer_address, peerbuf, sizeof(peerbuf)); obj = json_object_new_string(peerbuf); CHECKMEM(obj); json_object_object_add(entry, "peer-address", obj); } len = sizeof(addr); if (getsockname(sock->fd, &addr.type.sa, (void *)&len) == 0) { isc_sockaddr_format(&addr, peerbuf, sizeof(peerbuf)); obj = json_object_new_string(peerbuf); CHECKMEM(obj); json_object_object_add(entry, "local-address", obj); } states = json_object_new_array(); CHECKMEM(states); json_object_object_add(entry, "states", states); if (sock->pending_recv) { obj = json_object_new_string("pending-receive"); CHECKMEM(obj); json_object_array_add(states, obj); } if (sock->pending_send) { obj = json_object_new_string("pending-send"); CHECKMEM(obj); json_object_array_add(states, obj); } if (sock->pending_accept) { obj = json_object_new_string("pending-accept"); CHECKMEM(obj); json_object_array_add(states, obj); } if (sock->listener) { obj = json_object_new_string("listener"); CHECKMEM(obj); json_object_array_add(states, obj); } if (sock->connected) { obj = json_object_new_string("connected"); CHECKMEM(obj); json_object_array_add(states, obj); } if (sock->connecting) { obj = json_object_new_string("connecting"); CHECKMEM(obj); json_object_array_add(states, obj); } if (sock->bound) { obj = json_object_new_string("bound"); CHECKMEM(obj); json_object_array_add(states, obj); } UNLOCK(&sock->lock); sock = ISC_LIST_NEXT(sock, link); } json_object_object_add(stats, "sockets", array); array = NULL; result = ISC_R_SUCCESS; error: if (array != NULL) json_object_put(array); if (sock != NULL) UNLOCK(&sock->lock); UNLOCK(&mgr->lock); return (result); } #endif /* HAVE_JSON */ #include "../socket_api.c"
26.136806
100
0.697566
[ "object" ]
437ac73fc4f5ff1a51cb62dfe95609dd146e7e3c
5,465
h
C
3rdparty/Floating-Point-Root-Finder/include/Distance.h
LamWS/ClothSimulation
008b24fa96005cbe7ccae27a765d19e5f68a3ef2
[ "MIT" ]
5
2021-11-10T08:39:34.000Z
2022-03-06T10:21:49.000Z
3rdparty/Floating-Point-Root-Finder/include/Distance.h
LamWS/ClothSimulation
008b24fa96005cbe7ccae27a765d19e5f68a3ef2
[ "MIT" ]
1
2020-01-17T07:14:52.000Z
2020-01-17T07:14:52.000Z
Distance.h
Reimilia/DiscreteElasticRods
1651b29ec41d03e2fa9898148f1a70a5e2845537
[ "Apache-2.0" ]
null
null
null
#ifndef DISTANCE_H #define DISTANCE_H #include <Eigen/Core> #include <Eigen/Geometry> #include <algorithm> #include <set> class Distance { public: // Efficiently calculates whether or not a point p is closer to than eta distance to the plane spanned by vertices q0, q1, and q2. // This method does not require any floating point divisions and so is significantly faster than computing the distance itself. static bool vertexPlaneDistanceLessThan(const Eigen::Vector3d &p, const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, const Eigen::Vector3d &q2, double eta) { Eigen::Vector3d c = (q1-q0).cross(q2-q0); return c.dot(p-q0)*c.dot(p-q0) < eta*eta*c.dot(c); } // Efficiently calculates whether or not the line spanned by vertices (p0, p1) is closer than eta distance to the line spanned by vertices (q0, q1). // This method does not require any floating point divisions and so is significantly faster than computing the distance itself. static bool lineLineDistanceLessThan(const Eigen::Vector3d &p0, const Eigen::Vector3d &p1, const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, double eta) { Eigen::Vector3d c = (p1-p0).cross(q1-q0); return c.dot(q0-p0)*c.dot(q0-p0) < eta*eta*c.dot(c); } // Computes the vector between a point p and the closest point to p on the triangle (q0, q1, q2). Also returns the barycentric coordinates of this closest point on the triangle; // q0bary is the barycentric coordinate of q0, etc. (The distance from p to the triangle is the norm of this vector.) static Eigen::Vector3d vertexFaceDistance(const Eigen::Vector3d &p, const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, const Eigen::Vector3d &q2, double &q0bary, double &q1bary, double &q2bary) { Eigen::Vector3d ab = q1-q0; Eigen::Vector3d ac = q2-q0; Eigen::Vector3d ap = p-q0; double d1 = ab.dot(ap); double d2 = ac.dot(ap); // corner and edge cases if(d1 <= 0 && d2 <= 0) { q0bary = 1.0; q1bary = 0.0; q2bary = 0.0; return q0-p; } Eigen::Vector3d bp = p-q1; double d3 = ab.dot(bp); double d4 = ac.dot(bp); if(d3 >= 0 && d4 <= d3) { q0bary = 0.0; q1bary = 1.0; q2bary = 0.0; return q1-p; } double vc = d1*d4 - d3*d2; if((vc <= 0) && (d1 >= 0) && (d3 <= 0)) { double v = d1 / (d1-d3); q0bary = 1.0 - v; q1bary = v; q2bary = 0; return (q0 + v*ab)-p; } Eigen::Vector3d cp = p-q2; double d5 = ab.dot(cp); double d6 = ac.dot(cp); if(d6 >= 0 && d5 <= d6) { q0bary = 0; q1bary = 0; q2bary = 1.0; return q2-p; } double vb = d5*d2 - d1*d6; if((vb <= 0) && (d2 >= 0) && (d6 <= 0)) { double w = d2/(d2-d6); q0bary = 1-w; q1bary = 0; q2bary = w; return (q0 + w*ac)-p; } double va = d3*d6 - d5*d4; if((va <= 0) && (d4-d3 >= 0) && (d5-d6 >= 0)) { double w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); q0bary = 0; q1bary = 1.0 - w; q2bary = w; return (q1 + w*(q2-q1))-p; } // face case double denom = 1.0 / (va + vb + vc); double v = vb * denom; double w = vc * denom; double u = 1.0 - v - w; q0bary = u; q1bary = v; q2bary = w; return (u*q0 + v*q1 + w*q2)-p; } // Computes the shotest vector between a segment (p0, p1) and segment (q0, q1). Also returns the barycentric coordinates of the closest points on both segments; p0bary is the barycentric // coordinate of p0, etc. (The distance between the segments is the norm of this vector). static Eigen::Vector3d edgeEdgeDistance(const Eigen::Vector3d &p0, const Eigen::Vector3d &p1, const Eigen::Vector3d &q0, const Eigen::Vector3d &q1, double &p0bary, double &p1bary, double &q0bary, double &q1bary) { Eigen::Vector3d d1 = p1-p0; Eigen::Vector3d d2 = q1-q0; Eigen::Vector3d r = p0-q0; double a = d1.squaredNorm(); double e = d2.squaredNorm(); double f = d2.dot(r); double s,t; double c = d1.dot(r); double b = d1.dot(d2); double denom = a*e-b*b; if(denom != 0.0) { s = clamp( (b*f-c*e)/denom ); } else { //parallel edges and/or degenerate edges; values of s doesn't matter s = 0; } double tnom = b*s + f; if(tnom < 0 || e == 0) { t = 0; if(a == 0) s = 0; else s = clamp(-c/a); } else if(tnom > e) { t = 1.0; if(a == 0) s = 0; else s = clamp( (b-c)/a ); } else t = tnom/e; Eigen::Vector3d c1 = p0 + s*d1; Eigen::Vector3d c2 = q0 + t*d2; p0bary = 1.0-s; p1bary = s; q0bary = 1.0-t; q1bary = t; return c2-c1; } // Computes the shortest distance between a triangle mesh and itself, i.e. the shortest distance between a vertex and a face that does not contain that vertex, or of an edge and another edge that // does not share a vertex. The mesh has verts1.size()/3 vertices, stored as consecutive triplets in the vector verts, and faces stored as vertex indices in the columns of faces. This method assumes // that each vertex is part of at least one triangle. // Distances between primitives *all* of whose vertices are in fixedVerts are ignored. static double meshSelfDistance(const Eigen::VectorXd &verts, const Eigen::Matrix3Xi &faces, const std::set<int> &fixedVerts); private: static double clamp(double u) { return std::min(1.0, std::max(u, 0.0)); } }; #endif
28.763158
200
0.605672
[ "mesh", "geometry", "vector" ]
438531cef7a4acf767ab8a3d3c3743c8f32707cf
10,389
h
C
third_party/txt/src/txt/paragraph.h
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
third_party/txt/src/txt/paragraph.h
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
third_party/txt/src/txt/paragraph.h
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017 Google Inc. * * 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 LIB_TXT_SRC_PARAGRAPH_H_ #define LIB_TXT_SRC_PARAGRAPH_H_ #include <set> #include <utility> #include <vector> #include "font_collection.h" #include "lib/fxl/compiler_specific.h" #include "lib/fxl/macros.h" #include "minikin/LineBreaker.h" #include "paint_record.h" #include "paragraph_style.h" #include "styled_runs.h" #include "third_party/gtest/include/gtest/gtest_prod.h" #include "third_party/skia/include/core/SkRect.h" #include "utils/WindowsUtils.h" class SkCanvas; namespace txt { using GlyphID = uint32_t; // Paragraph provides Layout, metrics, and painting capabilites for text. Once a // Paragraph is constructed with ParagraphBuilder::Build(), an example basic // workflow can be this: // // std::unique_ptr<Paragraph> paragraph = paragraph_builder.Build(); // paragraph->Layout(<somewidthgoeshere>); // paragraph->Paint(<someSkCanvas>, <xpos>, <ypos>); class Paragraph { public: // Constructor. It is highly recommended to construct a paragraph with a // ParagraphBuilder. Paragraph(); ~Paragraph(); enum Affinity { UPSTREAM, DOWNSTREAM }; struct PositionWithAffinity { const size_t position; const Affinity affinity; PositionWithAffinity(size_t p, Affinity a) : position(p), affinity(a) {} }; struct TextBox { const SkRect rect; const TextDirection direction; TextBox(SkRect r, TextDirection d) : rect(r), direction(d) {} }; template <typename T> struct Range { Range(T s, T e) : start(s), end(e) {} T start, end; bool operator==(const Range<T>& other) const { return start == other.start && end == other.end; } }; // Minikin Layout doLayout() and LineBreaker addStyleRun() has an // O(N^2) (according to benchmarks) time complexity where N is the total // number of characters. However, this is not significant for reasonably sized // paragraphs. It is currently recommended to break up very long paragraphs // (10k+ characters) to ensure speedy layout. // // Layout calculates the positioning of all the glyphs. Must call this method // before Painting and getting any statistics from this class. void Layout(double width, bool force = false); // Paints the Laid out text onto the supplied SkCanvas at (x, y) offset from // the origin. Only valid after Layout() is called. void Paint(SkCanvas* canvas, double x, double y); // Getter for paragraph_style_. const ParagraphStyle& GetParagraphStyle() const; // Returns the number of characters/unicode characters. AKA text_.size() size_t TextSize() const; // Returns the height of the laid out paragraph. NOTE this is not a tight // bounding height of the glyphs, as some glyphs do not reach as low as they // can. double GetHeight() const; // Returns the width provided in the Layout() method. This is the maximum // width any line in the laid out paragraph can occupy. We expect that // GetMaxWidth() >= GetLayoutWidth(). double GetMaxWidth() const; // Distance from top of paragraph to the Alphabetic baseline of the first // line. Used for alphabetic fonts (A-Z, a-z, greek, etc.) double GetAlphabeticBaseline() const; // Distance from top of paragraph to the Ideographic baseline of the first // line. Used for ideographic fonts (Chinese, Japanese, Korean, etc.) double GetIdeographicBaseline() const; // Returns the total width covered by the paragraph without linebreaking. double GetMaxIntrinsicWidth() const; // Currently, calculated similarly to as GetLayoutWidth(), however this is not // nessecarily 100% correct in all cases. // // Returns the actual max width of the longest line after Layout(). double GetMinIntrinsicWidth() const; // Returns a vector of bounding boxes that enclose all text between start and // end glyph indexes, including start and excluding end. std::vector<TextBox> GetRectsForRange(size_t start, size_t end) const; // Returns the index of the glyph that corresponds to the provided coordinate, // with the top left corner as the origin, and +y direction as down. PositionWithAffinity GetGlyphPositionAtCoordinate(double dx, double dy) const; // Finds the first and last glyphs that define a word containing the glyph at // index offset. Range<size_t> GetWordBoundary(size_t offset) const; // Returns the number of lines the paragraph takes up. If the text exceeds the // amount width and maxlines provides, Layout() truncates the extra text from // the layout and this will return the max lines allowed. size_t GetLineCount() const; // Checks if the layout extends past the maximum lines and had to be // truncated. bool DidExceedMaxLines() const; // Sets the needs_layout_ to dirty. When Layout() is called, a new Layout will // be performed when this is set to true. Can also be used to prevent a new // Layout from being calculated by setting to false. void SetDirty(bool dirty = true); private: friend class ParagraphBuilder; FRIEND_TEST(ParagraphTest, SimpleParagraph); FRIEND_TEST(ParagraphTest, SimpleRedParagraph); FRIEND_TEST(ParagraphTest, RainbowParagraph); FRIEND_TEST(ParagraphTest, DefaultStyleParagraph); FRIEND_TEST(ParagraphTest, BoldParagraph); FRIEND_TEST_WINDOWS_DISABLED(ParagraphTest, LeftAlignParagraph); FRIEND_TEST_WINDOWS_DISABLED(ParagraphTest, RightAlignParagraph); FRIEND_TEST_WINDOWS_DISABLED(ParagraphTest, CenterAlignParagraph); FRIEND_TEST_WINDOWS_DISABLED(ParagraphTest, JustifyAlignParagraph); FRIEND_TEST(ParagraphTest, DecorationsParagraph); FRIEND_TEST(ParagraphTest, ItalicsParagraph); FRIEND_TEST(ParagraphTest, ChineseParagraph); FRIEND_TEST(ParagraphTest, DISABLED_ArabicParagraph); FRIEND_TEST(ParagraphTest, SpacingParagraph); FRIEND_TEST(ParagraphTest, LongWordParagraph); FRIEND_TEST(ParagraphTest, KernScaleParagraph); FRIEND_TEST_WINDOWS_DISABLED(ParagraphTest, NewlineParagraph); FRIEND_TEST_WINDOWS_DISABLED(ParagraphTest, EmojiParagraph); FRIEND_TEST(ParagraphTest, HyphenBreakParagraph); FRIEND_TEST(ParagraphTest, RepeatLayoutParagraph); FRIEND_TEST(ParagraphTest, Ellipsize); // Starting data to layout. std::vector<uint16_t> text_; StyledRuns runs_; ParagraphStyle paragraph_style_; std::shared_ptr<FontCollection> font_collection_; minikin::LineBreaker breaker_; mutable std::unique_ptr<icu::BreakIterator> word_breaker_; struct LineRange { LineRange(size_t s, size_t e, bool h) : start(s), end(e), hard_break(h) {} size_t start, end; bool hard_break; }; std::vector<LineRange> line_ranges_; std::vector<double> line_widths_; // Stores the result of Layout(). std::vector<PaintRecord> records_; std::vector<double> line_heights_; std::vector<double> line_baselines_; bool did_exceed_max_lines_; struct BidiRun { BidiRun(size_t s, size_t e, TextDirection d, const TextStyle& st) : start(s), end(e), direction(d), style(st) {} const size_t start, end; const TextDirection direction; const TextStyle& style; bool is_rtl() const { return direction == TextDirection::rtl; } }; struct GlyphPosition { Range<size_t> code_units; Range<double> x_pos; GlyphPosition(double x_start, double x_advance, size_t code_unit_index, size_t code_unit_width); }; struct GlyphLine { // Glyph positions sorted by x coordinate. const std::vector<GlyphPosition> positions; const size_t total_code_units; GlyphLine(std::vector<GlyphPosition>&& p, size_t tcu); }; struct CodeUnitRun { // Glyph positions sorted by code unit index. std::vector<GlyphPosition> positions; Range<size_t> code_units; Range<double> x_pos; size_t line_number; SkPaint::FontMetrics font_metrics; TextDirection direction; CodeUnitRun(std::vector<GlyphPosition>&& p, Range<size_t> cu, Range<double> x, size_t line, const SkPaint::FontMetrics& metrics, TextDirection dir); }; // Holds the laid out x positions of each glyph. std::vector<GlyphLine> glyph_lines_; // Holds the positions of each range of code units in the text. // Sorted in code unit index order. std::vector<CodeUnitRun> code_unit_runs_; // The max width of the paragraph as provided in the most recent Layout() // call. double width_ = -1.0f; double max_intrinsic_width_ = 0; double min_intrinsic_width_ = 0; double alphabetic_baseline_ = FLT_MAX; double ideographic_baseline_ = FLT_MAX; bool needs_layout_ = true; struct WaveCoordinates { double x_start; double y_start; double x_end; double y_end; WaveCoordinates(double x_s, double y_s, double x_e, double y_e) : x_start(x_s), y_start(y_s), x_end(x_e), y_end(y_e) {} }; // Passes in the text and Styled Runs. text_ and runs_ will later be passed // into breaker_ in InitBreaker(), which is called in Layout(). void SetText(std::vector<uint16_t> text, StyledRuns runs); void SetParagraphStyle(const ParagraphStyle& style); void SetFontCollection(std::shared_ptr<FontCollection> font_collection); // Break the text into lines. bool ComputeLineBreaks(); // Break the text into runs based on LTR/RTL text direction. bool ComputeBidiRuns(std::vector<BidiRun>* result); // Calculate the starting X offset of a line based on the line's width and // alignment. double GetLineXOffset(size_t line); // Creates and draws the decorations onto the canvas. void PaintDecorations(SkCanvas* canvas, double x, double y, size_t record_index); FXL_DISALLOW_COPY_AND_ASSIGN(Paragraph); }; } // namespace txt #endif // LIB_TXT_SRC_PARAGRAPH_H_
34.062295
80
0.725575
[ "vector" ]
438efbfe80717e21201a0645150f03089bf7ffcd
17,496
c
C
interfaces/dia/objects/KAOS/metaandorrel.c
krattai/monoflow
d777b8f345c5f2910114af7a186dc3bb6fe14aaf
[ "BSD-2-Clause" ]
1
2021-05-04T16:35:42.000Z
2021-05-04T16:35:42.000Z
interfaces/dia/objects/KAOS/metaandorrel.c
krattai/monoflow
d777b8f345c5f2910114af7a186dc3bb6fe14aaf
[ "BSD-2-Clause" ]
null
null
null
interfaces/dia/objects/KAOS/metaandorrel.c
krattai/monoflow
d777b8f345c5f2910114af7a186dc3bb6fe14aaf
[ "BSD-2-Clause" ]
1
2021-05-04T16:35:35.000Z
2021-05-04T16:35:35.000Z
/* Dia -- an diagram creation/manipulation program * Copyright (C) 1998 Alexander Larsson * * Objects for drawing KAOS goal diagrams. * This class supports the whole goal specialization hierarchy * Copyright (C) 2002 Christophe Ponsard * * Based on SADT box object * Copyright (C) 2000, 2001 Cyrille Chepelov * * Forked from Flowchart toolbox -- objects for drawing flowcharts. * Copyright (C) 1999 James Henstridge. * * 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. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <assert.h> #include <math.h> #include <string.h> #include <stdio.h> #include <glib.h> #include "intl.h" #include "object.h" #include "connection.h" #include "diarenderer.h" #include "handle.h" #include "arrows.h" #include "properties.h" #include "dia_image.h" #include "pixmaps/contributes.xpm" typedef struct _Maor Maor; typedef enum { MAOR_AND_REF, MAOR_AND_COMP_REF, MAOR_OR_REF, MAOR_OR_COMP_REF, MAOR_OPER_REF } MaorType; struct _Maor { Connection connection; ConnectionPoint connector; Handle text_handle; gchar *text; Point text_pos; real text_width; MaorType type; int init; }; #define MAOR_WIDTH 0.1 #define MAOR_DASHLEN 0.5 #define MAOR_FONTHEIGHT 0.7 #define MAOR_ARROWLEN 0.8 #define MAOR_ARROWWIDTH 0.5 #define HANDLE_MOVE_TEXT (HANDLE_CUSTOM1) #define MAOR_FG_COLOR color_black #define MAOR_BG_COLOR color_white #define MAOR_ICON_WIDTH 1.0 #define MAOR_ICON_HEIGHT 1.0 #define MAOR_REF_WIDTH 1.0 #define MAOR_REF_HEIGHT 1.0 static DiaFont *maor_font = NULL; static ObjectChange* maor_move_handle(Maor *maor, Handle *handle, Point *to, ConnectionPoint *cp, HandleMoveReason reason, ModifierKeys modifiers); static ObjectChange* maor_move(Maor *maor, Point *to); static void maor_select(Maor *maor, Point *clicked_point, DiaRenderer *interactive_renderer); static void maor_draw(Maor *maor, DiaRenderer *renderer); static DiaObject *maor_create(Point *startpoint, void *user_data, Handle **handle1, Handle **handle2); static real maor_distance_from(Maor *maor, Point *point); static void maor_update_data(Maor *maor); static void maor_destroy(Maor *maor); static DiaObject *maor_load(ObjectNode obj_node, int version, const char *filename); static PropDescription *maor_describe_props(Maor *mes); static void maor_get_props(Maor * maor, GPtrArray *props); static void maor_set_props(Maor *maor, GPtrArray *props); static void compute_and(Point *p, double w, double h, BezPoint *bpl); static void compute_or(Point *p, double w, double h, BezPoint *bpl); static void compute_oper(Point *p, double w, double h, Point *pl); static void draw_agent_icon(Maor *maor, double w, double h, DiaRenderer *renderer); static ObjectTypeOps maor_type_ops = { (CreateFunc) maor_create, (LoadFunc) maor_load,/*using_properties*/ /* load */ (SaveFunc) object_save_using_properties, /* save */ (GetDefaultsFunc) NULL, (ApplyDefaultsFunc) NULL }; DiaObjectType kaos_maor_type = { "KAOS - maor", /* name */ 0, /* version */ (char **)contributes_xpm, /* pixmap */ &maor_type_ops /* ops */ }; static ObjectOps maor_ops = { (DestroyFunc) maor_destroy, (DrawFunc) maor_draw, (DistanceFunc) maor_distance_from, (SelectFunc) maor_select, (CopyFunc) object_copy_using_properties, (MoveFunc) maor_move, (MoveHandleFunc) maor_move_handle, (GetPropertiesFunc) object_create_props_dialog, (ApplyPropertiesDialogFunc) object_apply_props_from_dialog, (ObjectMenuFunc) NULL, (DescribePropsFunc) maor_describe_props, (GetPropsFunc) maor_get_props, (SetPropsFunc) maor_set_props, (TextEditFunc) 0, (ApplyPropertiesListFunc) object_apply_props, }; static PropEnumData prop_maor_type_data[] = { { N_("AND Refinement"), MAOR_AND_REF }, { N_("Complete AND Refinement"), MAOR_AND_REF }, { N_("OR Refinement"), MAOR_OR_REF }, { N_("Operationalization"), MAOR_OPER_REF }, { NULL, 0} }; static PropDescription maor_props[] = { CONNECTION_COMMON_PROPERTIES, { "text", PROP_TYPE_STRING, PROP_FLAG_VISIBLE, N_("Text:"), NULL, NULL }, { "type", PROP_TYPE_ENUM, PROP_FLAG_VISIBLE|PROP_FLAG_NO_DEFAULTS, N_("Type:"), NULL, prop_maor_type_data }, { "text_pos", PROP_TYPE_POINT, 0, "text_pos:", NULL,NULL }, PROP_DESC_END }; static PropDescription * maor_describe_props(Maor *maor) { if (maor_props[0].quark == 0) prop_desc_list_calculate_quarks(maor_props); return maor_props; } static PropOffset maor_offsets[] = { CONNECTION_COMMON_PROPERTIES_OFFSETS, { "text", PROP_TYPE_STRING, offsetof(Maor, text) }, { "type", PROP_TYPE_ENUM, offsetof(Maor,type)}, { "text_pos", PROP_TYPE_POINT, offsetof(Maor,text_pos) }, { NULL, 0, 0 } }; static void maor_get_props(Maor * maor, GPtrArray *props) { object_get_props_from_offsets(&maor->connection.object,maor_offsets, props); } static void maor_set_props(Maor *maor, GPtrArray *props) { if (maor->init==-1) { maor->init++; return; } object_set_props_from_offsets(&maor->connection.object,maor_offsets, props); maor_update_data(maor); } static real maor_distance_from(Maor *maor, Point *point) { Point *endpoints; real d1,d2; endpoints = &maor->connection.endpoints[0]; d1 = distance_line_point(&endpoints[0], &endpoints[1], MAOR_WIDTH, point); d2 = distance_point_point(&endpoints[0], point) - MAOR_REF_WIDTH/2.0; if (d2<0) d2=0; if (d1<d2) return d1; else return d2; } static void maor_select(Maor *maor, Point *clicked_point, DiaRenderer *interactive_renderer) { connection_update_handles(&maor->connection); } static ObjectChange* maor_move_handle(Maor *maor, Handle *handle, Point *to, ConnectionPoint *cp, HandleMoveReason reason, ModifierKeys modifiers) { Point p1, p2; Point *endpoints; assert(maor!=NULL); assert(handle!=NULL); assert(to!=NULL); if (handle->id == HANDLE_MOVE_TEXT) { maor->text_pos = *to; } else { endpoints = &maor->connection.endpoints[0]; p1.x = 0.5*(endpoints[0].x + endpoints[1].x); p1.y = 0.5*(endpoints[0].y + endpoints[1].y); connection_move_handle(&maor->connection, handle->id, to, cp, reason, modifiers); connection_adjust_for_autogap(&maor->connection); p2.x = 0.5*(endpoints[0].x + endpoints[1].x); p2.y = 0.5*(endpoints[0].y + endpoints[1].y); point_sub(&p2, &p1); point_add(&maor->text_pos, &p2); } maor_update_data(maor); return NULL; } static ObjectChange* maor_move(Maor *maor, Point *to) { Point start_to_end; Point *endpoints = &maor->connection.endpoints[0]; Point delta; delta = *to; point_sub(&delta, &endpoints[0]); start_to_end = endpoints[1]; point_sub(&start_to_end, &endpoints[0]); endpoints[1] = endpoints[0] = *to; point_add(&endpoints[1], &start_to_end); point_add(&maor->text_pos, &delta); maor_update_data(maor); return NULL; } static void compute_and(Point *p, double w, double h, BezPoint *bpl) { Point ref; ref.x=p->x-w/2; ref.y=p->y-h/2; bpl[0].type=BEZ_MOVE_TO; bpl[0].p1.x=ref.x; bpl[0].p1.y=ref.y+h; bpl[1].type=BEZ_LINE_TO; bpl[1].p1.x=ref.x+w/20; bpl[1].p1.y=ref.y+h/2; bpl[2].type=BEZ_CURVE_TO; bpl[2].p3.x=ref.x+w/2; bpl[2].p3.y=ref.y; bpl[2].p1.x=bpl[1].p1.x+w*0.15; bpl[2].p1.y=bpl[1].p1.y-h/2; bpl[2].p2.x=bpl[2].p3.x-w/4; bpl[2].p2.y=bpl[2].p3.y; bpl[3].type=BEZ_CURVE_TO; bpl[3].p3.x=ref.x+w*19/20; bpl[3].p3.y=ref.y+h/2; bpl[3].p1.x=bpl[2].p3.x+w/4; bpl[3].p1.y=bpl[2].p3.y; bpl[3].p2.x=bpl[3].p3.x-w*0.15; bpl[3].p2.y=bpl[3].p3.y-h/2; bpl[4].type=BEZ_LINE_TO; bpl[4].p1.x=ref.x+w; bpl[4].p1.y=ref.y+h; bpl[5].type=BEZ_LINE_TO; bpl[5].p1.x=ref.x; bpl[5].p1.y=ref.y+h; } static void compute_or(Point *p, double w, double h, BezPoint *bpl) { Point ref; ref.x=p->x-w/2; ref.y=p->y-h/2; bpl[0].type=BEZ_MOVE_TO; bpl[0].p1.x=ref.x; bpl[0].p1.y=ref.y+h; bpl[1].type=BEZ_CURVE_TO; bpl[1].p3.x=ref.x+w/2; bpl[1].p3.y=ref.y; bpl[1].p1.x=bpl[0].p1.x; bpl[1].p1.y=bpl[0].p1.y-h/2; bpl[1].p2.x=bpl[1].p3.x-w/2; bpl[1].p2.y=bpl[1].p3.y+h/4; bpl[2].type=BEZ_CURVE_TO; bpl[2].p3.x=ref.x+w; bpl[2].p3.y=ref.y+h; bpl[2].p1.x=bpl[1].p3.x+w/2; bpl[2].p1.y=bpl[1].p3.y+h/4; bpl[2].p2.x=bpl[2].p3.x; bpl[2].p2.y=bpl[2].p3.y-w/2; bpl[3].type=BEZ_CURVE_TO; bpl[3].p3.x=ref.x; bpl[3].p3.y=ref.y+h; bpl[3].p1.x=bpl[2].p3.x-w/2; bpl[3].p1.y=bpl[2].p3.y-h/4; bpl[3].p2.x=bpl[3].p3.x+w/2; bpl[3].p2.y=bpl[3].p3.y-h/4; } static void compute_oper(Point *p, double w, double h, Point *pl) { Point ref; double wd=w/2; double hd=h/2; double s30=sin(M_PI/6)*wd; double c30=cos(M_PI/6)*hd; ref.x=p->x; ref.y=p->y; pl[0].x=ref.x; pl[0].y=ref.y-hd; pl[1].x=ref.x+c30; pl[1].y=ref.y-s30; pl[2].x=ref.x+c30; pl[2].y=ref.y+s30; pl[3].x=ref.x; pl[3].y=ref.y+hd; pl[4].x=ref.x-c30; pl[4].y=ref.y+s30; pl[5].x=ref.x-c30; pl[5].y=ref.y-s30; pl[6].x=pl[0].x; pl[6].y=pl[0].y; } static void draw_agent_icon(Maor *maor, double w, double h, DiaRenderer *renderer) { DiaRendererClass *renderer_ops = DIA_RENDERER_GET_CLASS (renderer); double rx,ry; Point ref,c,p1,p2; ref=maor->connection.endpoints[0]; rx=ref.x; ry=ref.y-h*0.2; /* head */ c.x=rx; c.y=ry; renderer_ops->fill_ellipse(renderer,&c,h/5,h/5,&MAOR_FG_COLOR); /* body */ p1.x=rx; p1.y=ry; p2.x=p1.x; p2.y=p1.y+3.5*h/10; renderer_ops->draw_line(renderer,&p1,&p2,&MAOR_FG_COLOR); /* arms */ p1.x=rx-1.5*h/10; p1.y=ry+2.2*h/10; p2.x=rx+1.5*h/10; p2.y=p1.y; renderer_ops->draw_line(renderer,&p1,&p2,&MAOR_FG_COLOR); /* left leg */ p1.x=rx; p1.y=ry+3.5*h/10; p2.x=p1.x-h/10; p2.y=p1.y+2*h/10; renderer_ops->draw_line(renderer,&p1,&p2,&MAOR_FG_COLOR); /* right leg */ p1.x=rx; p1.y=ry+3.5*h/10; p2.x=p1.x+h/10; p2.y=p1.y+2*h/10; renderer_ops->draw_line(renderer,&p1,&p2,&MAOR_FG_COLOR); } /* drawing here -- TBD inverse flow ?? */ static void maor_draw(Maor *maor, DiaRenderer *renderer) { DiaRendererClass *renderer_ops = DIA_RENDERER_GET_CLASS (renderer); Point *endpoints, p1, p2, pm; Arrow arrow; BezPoint bpl[6]; Point pl[7]; gchar *mname = g_strdup(maor->text); /* some asserts */ assert(maor != NULL); assert(renderer != NULL); /* arrow type */ arrow.type = ARROW_FILLED_TRIANGLE; arrow.length = MAOR_ARROWLEN; arrow.width = MAOR_ARROWWIDTH; endpoints = &maor->connection.endpoints[0]; /* some computations */ p1 = endpoints[0]; /* could reverse direction here */ p2 = endpoints[1]; pm.x=(p1.x+p2.x)/2; pm.y=(p1.y+p2.y)/2; /** drawing directed line **/ renderer_ops->set_linewidth(renderer, MAOR_WIDTH); renderer_ops->set_linecaps(renderer, LINECAPS_BUTT); renderer_ops->set_linestyle(renderer, LINESTYLE_SOLID); renderer_ops->draw_line_with_arrows(renderer,&p1,&p2,MAOR_WIDTH,&MAOR_FG_COLOR,NULL,&arrow); /** drawing vector decoration **/ /* and ref */ switch (maor->type) { case MAOR_AND_REF: compute_and(&p1,MAOR_REF_WIDTH,MAOR_REF_HEIGHT,bpl); renderer_ops->fill_bezier(renderer,bpl,6,&MAOR_BG_COLOR); renderer_ops->draw_bezier(renderer,bpl,6,&MAOR_FG_COLOR); break; case MAOR_AND_COMP_REF: compute_and(&p1,MAOR_REF_WIDTH,MAOR_REF_HEIGHT,bpl); renderer_ops->fill_bezier(renderer,bpl,6,&MAOR_FG_COLOR); break; case MAOR_OR_REF: compute_or(&p1,MAOR_REF_WIDTH,MAOR_REF_HEIGHT,bpl); renderer_ops->fill_bezier(renderer,bpl,4,&MAOR_BG_COLOR); renderer_ops->draw_bezier(renderer,bpl,4,&MAOR_FG_COLOR); break; case MAOR_OR_COMP_REF: compute_or(&p1,MAOR_REF_WIDTH,MAOR_REF_HEIGHT,bpl); renderer_ops->fill_bezier(renderer,bpl,4,&MAOR_FG_COLOR); break; case MAOR_OPER_REF: compute_oper(&p1,MAOR_REF_WIDTH,MAOR_REF_HEIGHT,pl); renderer_ops->fill_polygon(renderer,pl,7,&MAOR_BG_COLOR); renderer_ops->draw_polygon(renderer,pl,7,&MAOR_FG_COLOR); draw_agent_icon(maor,MAOR_REF_WIDTH,MAOR_REF_HEIGHT,renderer); break; } /** writing text on arrow (maybe not a good idea) **/ renderer_ops->set_font(renderer,maor_font,MAOR_FONTHEIGHT); if (mname && strlen(mname) != 0) renderer_ops->draw_string(renderer,mname,&maor->text_pos, ALIGN_CENTER,&color_black); if (mname) g_free(mname); } /* creation here */ static DiaObject * maor_create(Point *startpoint, void *user_data, Handle **handle1, Handle **handle2) { Maor *maor; Connection *conn; LineBBExtras *extra; DiaObject *obj; if (maor_font == NULL) { maor_font = dia_font_new_from_style(DIA_FONT_SANS, MAOR_FONTHEIGHT); } maor = g_malloc0(sizeof(Maor)); conn = &maor->connection; conn->endpoints[0] = *startpoint; conn->endpoints[1] = *startpoint; conn->endpoints[1].y -= 2; obj = &conn->object; extra = &conn->extra_spacing; switch (GPOINTER_TO_INT(user_data)) { case 1: maor->type=MAOR_AND_REF; break; case 2: maor->type=MAOR_AND_COMP_REF; break; case 3: maor->type=MAOR_OR_REF; break; case 4: maor->type=MAOR_OR_COMP_REF; break; case 5: maor->type=MAOR_OPER_REF; break; default: maor->type=MAOR_AND_REF; break; } obj->type = &kaos_maor_type; obj->ops = &maor_ops; /* connectionpoint init */ connection_init(conn, 3, 1); /* added one connection point (3rd handle for text move) */ obj->connections[0] = &maor->connector; maor->connector.object = obj; maor->connector.connected = NULL; maor->text = g_strdup(""); maor->text_width = 0.0; maor->text_pos.x = 0.5*(conn->endpoints[0].x + conn->endpoints[1].x); maor->text_pos.y = 0.5*(conn->endpoints[0].y + conn->endpoints[1].y); maor->text_handle.id = HANDLE_MOVE_TEXT; maor->text_handle.type = HANDLE_MINOR_CONTROL; maor->text_handle.connect_type = HANDLE_NONCONNECTABLE; maor->text_handle.connected_to = NULL; obj->handles[2] = &maor->text_handle; extra->start_long = extra->start_trans = extra->end_long = MAOR_WIDTH/2.0; extra->end_trans = MAX(MAOR_WIDTH,MAOR_ARROWLEN)/2.0; maor_update_data(maor); *handle1 = obj->handles[0]; *handle2 = obj->handles[1]; /* bug workaround */ if (GPOINTER_TO_INT(user_data)!=0) maor->init=-1; else maor->init=0; return &maor->connection.object; } static void maor_destroy(Maor *maor) { connection_destroy(&maor->connection); g_free(maor->text); } static void maor_update_data(Maor *maor) { Connection *conn = &maor->connection; DiaObject *obj = &conn->object; Rectangle rect; Point p1,p2,p3,p4; if (connpoint_is_autogap(conn->endpoint_handles[0].connected_to) || connpoint_is_autogap(conn->endpoint_handles[1].connected_to)) { connection_adjust_for_autogap(conn); } obj->position = conn->endpoints[0]; maor->text_handle.pos = maor->text_pos; connection_update_handles(conn); connection_update_boundingbox(conn); maor->text_width = dia_font_string_width(maor->text, maor_font, MAOR_FONTHEIGHT); /* endpoint */ p1 = conn->endpoints[0]; p2 = conn->endpoints[1]; /* connection point */ maor->connector.pos.x=p1.x; maor->connector.pos.y=p1.y+MAOR_ICON_HEIGHT/2; /* Add boundingbox for mid image: */ p3.x=(p1.x+p2.x)/2.0-MAOR_ICON_WIDTH/2; p3.y=(p1.y+p2.y)/2.0-MAOR_ICON_HEIGHT/2; p4.x=p3.x+MAOR_ICON_WIDTH; p4.y=p3.y+MAOR_ICON_HEIGHT; rect.left=p3.x; rect.right=p4.x; rect.top=p3.y; rect.bottom=p4.y; rectangle_union(&obj->bounding_box, &rect); /* Add boundingbox for end image: */ p1 = conn->endpoints[0]; p2 = conn->endpoints[1]; p3.x=p1.x-MAOR_REF_WIDTH*1.1/2; /* 1.1 factor to be safe (fix for or) */ p3.y=p1.y-MAOR_REF_HEIGHT*1.1/2; p4.x=p3.x+MAOR_REF_WIDTH*1.1; p4.y=p3.y+MAOR_REF_HEIGHT*1.1; rect.left=p3.x; rect.right=p4.x; rect.top=p3.y; rect.bottom=p4.y; rectangle_union(&obj->bounding_box, &rect); /* Add boundingbox for text: */ rect.left = maor->text_pos.x-maor->text_width/2; rect.right = rect.left + maor->text_width; rect.top = maor->text_pos.y - dia_font_ascent(maor->text, maor_font, MAOR_FONTHEIGHT); rect.bottom = rect.top + MAOR_FONTHEIGHT; rectangle_union(&obj->bounding_box, &rect); } static DiaObject * maor_load(ObjectNode obj_node, int version, const char *filename) { return object_load_using_properties(&kaos_maor_type, obj_node,version,filename); }
27.167702
95
0.668324
[ "object", "vector" ]
438f368eebf5b4899f6898260f41d641ae25a9e9
11,235
h
C
VipVideo-iPhone/Pods/Headers/Public/AXWebViewController/AXWebViewController.h
daojianmahun/VipVideo-iPhone
be3178c423ee930e960944cc26c6d96cbe68aeb0
[ "MIT" ]
282
2018-07-09T08:30:33.000Z
2022-03-21T15:30:05.000Z
VipVideo-iPhone/Pods/Headers/Public/AXWebViewController/AXWebViewController.h
daojianmahun/VipVideo-iPhone
be3178c423ee930e960944cc26c6d96cbe68aeb0
[ "MIT" ]
6
2018-08-07T07:32:09.000Z
2021-01-28T07:11:45.000Z
VipVideo-iPhone/Pods/Headers/Public/AXWebViewController/AXWebViewController.h
daojianmahun/VipVideo-iPhone
be3178c423ee930e960944cc26c6d96cbe68aeb0
[ "MIT" ]
111
2018-07-10T03:16:30.000Z
2022-02-15T08:58:21.000Z
// // AXWebViewController.h // AXWebViewController // // Created by ai on 15/12/22. // Copyright © 2015年 devedbox. 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 __IPHONE_8_0 #define __IPHONE_8_0 80000 #endif #ifndef __IPHONE_9_0 #define __IPHONE_9_0 90000 #endif #ifndef AX_WEB_VIEW_CONTROLLER_USING_WEBKIT #define AX_WEB_VIEW_CONTROLLER_USING_WEBKIT __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0 // #define AX_WEB_VIEW_CONTROLLER_USING_WEBKIT 1 #endif #ifndef AX_WEB_VIEW_CONTROLLER_DEFINES_PROXY #define AX_WEB_VIEW_CONTROLLER_DEFINES_PROXY AX_WEB_VIEW_CONTROLLER_USING_WEBKIT #endif #ifndef AX_WEB_VIEW_CONTROLLER_AVAILABLITY #define AX_WEB_VIEW_CONTROLLER_AVAILABLITY BOOL AX_WEB_VIEW_CONTROLLER_iOS8_0_AVAILABLE(void);\ BOOL AX_WEB_VIEW_CONTROLLER_iOS9_0_AVAILABLE(void);\ BOOL AX_WEB_VIEW_CONTROLLER_iOS10_0_AVAILABLE(void); #endif #import <UIKit/UIKit.h> #import <NJKWebViewProgress/NJKWebViewProgress.h> #import <NJKWebViewProgress/NJKWebViewProgressView.h> #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT #import <WebKit/WebKit.h> #import "AXSecurityPolicy.h" #endif #ifndef AX_REQUIRES_SUPER #if __has_attribute(objc_requires_super) #define AX_REQUIRES_SUPER __attribute__((objc_requires_super)) #else #define AX_REQUIRES_SUPER #endif #endif /* http://www.dudas.co.uk/ns_requires_super/: -- __attribute((objc_requires_super)) was first introduced as work in progress into CLANG in September 2012 and was documented in October 2013. On both OS X and iOS there is now a NS_REQUIRES_SUPER macro that conditionally wraps the objc_requires_super attribute depending on compiler support. Once a method declaration is appended with this macro, the compiler will produce a warning if super is not called by a subclass overriding the method. */ NS_ASSUME_NONNULL_BEGIN @class AXWebViewController; typedef NS_ENUM(NSInteger, AXWebViewControllerNavigationType) { /// Navigation bar items. AXWebViewControllerNavigationBarItem, /// Tool bar items. AXWebViewControllerNavigationToolItem }; @protocol AXWebViewControllerDelegate <NSObject> @optional /// Called when web view will go back. /// /// @param webViewController a web view controller. - (void)webViewControllerWillGoBack:(AXWebViewController *)webViewController; /// Called when web view will go forward. /// /// @param webViewController a web view controller. - (void)webViewControllerWillGoForward:(AXWebViewController *)webViewController; /// Called when web view will reload. /// /// @param webViewController a web view controller. - (void)webViewControllerWillReload:(AXWebViewController *)webViewController; /// Called when web view will stop load. /// /// @param webViewController a web view controller. - (void)webViewControllerWillStop:(AXWebViewController *)webViewController; /// Called when web view did start loading. /// /// @param webViewController a web view controller. - (void)webViewControllerDidStartLoad:(AXWebViewController *)webViewController; /// Called when web view did finish loading. /// /// @param webViewController a web view controller. - (void)webViewControllerDidFinishLoad:(AXWebViewController *)webViewController; /// Called when web viw did fail loading. /// /// @param webViewController a web view controller. /// /// @param error a failed loading error. - (void)webViewController:(AXWebViewController *)webViewController didFailLoadWithError:(NSError *)error; @end AX_WEB_VIEW_CONTROLLER_AVAILABLITY; #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT typedef NSURLSessionAuthChallengeDisposition (^WKWebViewDidReceiveAuthenticationChallengeHandler)(WKWebView *webView, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential); API_AVAILABLE(ios(8.0)) @interface AXWebViewController : UIViewController <WKUIDelegate, WKNavigationDelegate> { @protected WKWebView *_webView; NSURL *_URL; } #else API_AVAILABLE(ios(7.0)) @interface AXWebViewController : UIViewController <UIWebViewDelegate> { @protected UIWebView *_webView; NSURL *_URL; } #endif /// Delegate. @property(assign, nonatomic) id<AXWebViewControllerDelegate>delegate; #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT /// WebKit web view. @property(readonly, nonatomic) WKWebView *webView; #else /// Web view. @property(readonly, nonatomic) UIWebView *webView; #endif #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT /// Default is NO. Enabled to allow present alert views. @property(assign, nonatomic) BOOL enabledWebViewUIDelegate; #endif /// Open app link in app store app. Default is NO. @property(assign, nonatomic) BOOL reviewsAppInAppStore; /// Max length of title string content. Default is 10. @property(assign, nonatomic) NSUInteger maxAllowedTitleLength; /// Time out internal. @property(assign, nonatomic) NSTimeInterval timeoutInternal; /// Cache policy. @property(assign, nonatomic) NSURLRequestCachePolicy cachePolicy; /// The based initialized url of the web view controller if any. @property(readonly, nonatomic) NSURL *URL; /// Shows tool bar. Default is YES. @property(assign, nonatomic) BOOL showsToolBar; /// Shows background description label. Default is YES. @property(assign, nonatomic) BOOL showsBackgroundLabel; /// Shows navigation close bar button item. Default is YES. @property(assign, nonatomic) BOOL showsNavigationCloseBarButtonItem; /// Shows the title of navigation back bar button item. Default is YES. @property(assign, nonatomic) BOOL showsNavigationBackBarButtonItemTitle; /// Check url can open default YES, only work after iOS 8. @property(assign, nonatomic) BOOL checkUrlCanOpen API_AVAILABLE(ios(8.0)); /// Navigation type. @property(assign, nonatomic) AXWebViewControllerNavigationType navigationType; /// Navigation close bar button item. @property(readwrite, nonatomic) UIBarButtonItem *navigationCloseItem; /// Get a instance of `AXWebViewController` by a url string. /// /// @param urlString a string of url to be loaded. /// /// @return a instance `AXWebViewController`. - (instancetype)initWithAddress:(NSString*)urlString; /// Get a instance of `AXWebViewController` by a url. /// /// @param URL a URL to be loaded. /// /// @return a instance of `AXWebViewController`. - (instancetype)initWithURL:(NSURL*)URL; /// Get a instance of `AXWebViewController` by a url request. /// /// @param request a URL request to be loaded. /// /// @return a instance of `AXWebViewController`. - (instancetype)initWithRequest:(NSURLRequest *)request; #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT /// Get a instance of `AXWebViewController` by a url and configuration of web view. /// /// @param URL a URL to be loaded. /// @param configuration configuration instance of WKWebViewConfiguration to create web view. /// /// @return a instance of `AXWebViewController`. - (instancetype)initWithURL:(NSURL *)URL configuration:(WKWebViewConfiguration *)configuration; /// Get a instance of `AXWebViewController` by a request and configuration of web view. /// /// @param request a URL request to be loaded. /// @param configuration configuration instance of WKWebViewConfiguration to create web view. /// /// @return a instance of `AXWebViewController`. - (instancetype)initWithRequest:(NSURLRequest *)request configuration:(WKWebViewConfiguration *)configuration; #endif /// Get a instance of `AXWebViewController` by a HTML string and a base URL. /// /// @param HTMLString a HTML string object. /// @param baseURL a baseURL to be loaded. /// /// @return a instance of `AXWebViewController`. - (instancetype)initWithHTMLString:(NSString *)HTMLString baseURL:(NSURL * _Nullable)baseURL; /// Load a new url. /// /// @param URL a new url. - (void)loadURL:(NSURL*)URL; /// Load a new html string. /// /// @param HTMLString a encoded html string. /// @param baseURL base url of bundle. - (void)loadHTMLString:(NSString *)HTMLString baseURL:(NSURL *)baseURL; @end @interface AXWebViewController (SubclassingHooks) /// Called when web view will go back. Do not call this directly. Same to the bottom methods. /// @discussion 使用的时候需要子类化,并且调用super的方法!切记!!! /// - (void)willGoBack AX_REQUIRES_SUPER; /// Called when web view will go forward. Do not call this directly. /// - (void)willGoForward AX_REQUIRES_SUPER; /// Called when web view will reload. Do not call this directly. /// - (void)willReload AX_REQUIRES_SUPER; /// Called when web view will stop load. Do not call this directly. /// - (void)willStop AX_REQUIRES_SUPER; /// Called when web view did start loading. Do not call this directly. /// - (void)didStartLoad AX_REQUIRES_SUPER NS_DEPRECATED_IOS(2_0, 8_0); #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT /// Called when web view(WKWebView) did start loading. Do not call this directly. /// /// @param navigation Navigation object of the current request info. - (void)didStartLoadWithNavigation:(WKNavigation *)navigation AX_REQUIRES_SUPER NS_AVAILABLE(10_10, 8_0); #endif /// Called when web view did finish loading. Do not call this directly. /// - (void)didFinishLoad AX_REQUIRES_SUPER; /// Called when web viw did fail loading. Do not call this directly. /// /// @param error a failed loading error. - (void)didFailLoadWithError:(NSError *)error AX_REQUIRES_SUPER; @end /** WebCache clearing. */ @interface AXWebViewController (WebCache) /// Clear cache data of web view. /// /// @param completion completion block. + (void)clearWebCacheCompletion:(dispatch_block_t _Nullable)completion; @end /** Accessibility to background label. */ @interface AXWebViewController (BackgroundLabel) /// Description label of web content's info. /// @property(readonly, nonatomic) UILabel *descriptionLabel; @end #if AX_WEB_VIEW_CONTROLLER_USING_WEBKIT @interface AXWebViewController (Security) /// Challenge handler for the credential. @property(copy, nonatomic, nullable) WKWebViewDidReceiveAuthenticationChallengeHandler challengeHandler; /// The security policy used by created session to evaluate server trust for secure connections. /// `AXWebViewController` uses the `defaultPolicy` unless otherwise specified. @property(readwrite, nonatomic, nullable) AXSecurityPolicy *securityPolicy; @end #endif NS_ASSUME_NONNULL_END
39.840426
442
0.77668
[ "object" ]
438f6457cba5b4178636c6dbdfe51f8e0c888658
1,997
h
C
ios/ios_src/SearchResultPoi/View/GeoNamesSearchResultPoiView.h
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
69
2017-06-07T10:47:03.000Z
2022-03-24T08:33:33.000Z
ios/ios_src/SearchResultPoi/View/GeoNamesSearchResultPoiView.h
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
23
2017-06-07T10:47:00.000Z
2020-07-09T10:31:17.000Z
ios/ios_src/SearchResultPoi/View/GeoNamesSearchResultPoiView.h
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
31
2017-08-12T13:19:32.000Z
2022-01-04T20:33:40.000Z
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #pragma once #import <UIKit/UIKit.h> #include <vector> #include "Types.h" #include "AppRunner.h" #include "SearchResultModel.h" #include "SearchResultPoiViewInterop.h" #include "SearchResultPoiView.h" @class GeoNamesSearchResultPoiView; @interface GeoNamesSearchResultPoiView : UIView<SearchResultPoiView> { UIViewController* m_pController; float m_stateChangeAnimationTimeSeconds; ExampleApp::Search::SdkModel::SearchResultModel m_model; ExampleApp::SearchResultPoi::View::SearchResultPoiViewInterop* m_pInterop; bool m_isPinned; float m_labelsSectionWidth; UIImage* m_pRemovePinButtonImage; UIImage* m_pRemovePinButtonHighlightImage; UIImage* m_pAddPinButtonImage; UIImage* m_pAddPinButtonHighlightImage; } - (id)initWithInterop:(ExampleApp::SearchResultPoi::View::SearchResultPoiViewInterop*)pInterop; - (ExampleApp::SearchResultPoi::View::SearchResultPoiViewInterop*) getInterop; - (BOOL) consumesTouch:(UITouch *)touch; - (void) setContent:(const ExampleApp::Search::SdkModel::SearchResultModel*)pModel :(bool)isPinned; - (void) updateImage:(const std::string&)url :(bool)success bytes:(const std::vector<Byte>*)bytes; - (void) setFullyActive; - (void) setFullyInactive; - (void) setActiveStateToIntermediateValue:(float)activeState; @property (nonatomic, retain) UIView* pCloseButtonContainer; @property (nonatomic, retain) UIButton* pCloseButton; @property (nonatomic, retain) UIButton* pPinButton; @property (nonatomic, retain) UIView* pDropPinContainer; @property (nonatomic, retain) UIView* pControlContainer; @property (nonatomic, retain) UIView* pTitleCardContainer; @property (nonatomic, retain) UILabel* pTitleLabel; @property (nonatomic, retain) UIScrollView* pLabelsContainer; @property (nonatomic, retain) UIView* pTagIconContainer; @property (nonatomic, retain) UILabel* pCountryContent; @property (nonatomic, retain) UIView* pTitleCardHeaderLine; @end
32.209677
99
0.783676
[ "vector" ]
43948403ceb0a72fef9060b5cb5098d76e48dee6
1,395
h
C
KeepingYouAwake/Battery Status/KYABatteryStatus.h
fatt92/KeepingYouAwake
cd687b6972b220e9067d50e66646742e06634c1c
[ "MIT" ]
1
2020-09-15T12:18:00.000Z
2020-09-15T12:18:00.000Z
KeepingYouAwake/Battery Status/KYABatteryStatus.h
fatt92/KeepingYouAwake
cd687b6972b220e9067d50e66646742e06634c1c
[ "MIT" ]
null
null
null
KeepingYouAwake/Battery Status/KYABatteryStatus.h
fatt92/KeepingYouAwake
cd687b6972b220e9067d50e66646742e06634c1c
[ "MIT" ]
1
2019-04-02T15:32:17.000Z
2019-04-02T15:32:17.000Z
// // KYABatteryStatus.h // KeepingYouAwake // // Created by Marcel Dierkes on 21.12.15. // Copyright © 2015 Marcel Dierkes. All rights reserved. // #import <Foundation/Foundation.h> extern const CGFloat KYABatteryStatusUnavailable; typedef void(^KYABatteryStatusChangeBlock)(CGFloat capacity); /** * An object that represents the current battery capacity. */ @interface KYABatteryStatus : NSObject /** * Returns YES if the current device actually has a built-in battery. */ @property (nonatomic, readonly, getter=isBatteryStatusAvailable) BOOL batteryStatusAvailable; /** * Returns the current battery charging level of the internal battery, or KYABatteryStatusUnavailable. */ @property (nonatomic, readonly) CGFloat currentCapacity; /** * An optional block that will be called when the power source changes and registerForCapacityChanges was called. */ @property (copy, nonatomic, nullable) KYABatteryStatusChangeBlock capacityChangeHandler; /** * Registers the current instance with the runloop to receive power source change notifications. * * The capacityChangeHandler block will be called when a power source change occurs. */ - (void)registerForCapacityChangesIfNeeded; /** * Unregisters the current instance from all capacity change notifications. * This method will automatically be called on dealloc. */ - (void)unregisterFromCapacityChanges; @end
28.469388
114
0.773477
[ "object" ]
4397875beb9681c60fcece183ca74e758911e4d1
37,675
c
C
misc/gif.c
chatziko/bitmap
91094bb8b16bc356e9ae3bb2004457149cf75271
[ "MIT" ]
null
null
null
misc/gif.c
chatziko/bitmap
91094bb8b16bc356e9ae3bb2004457149cf75271
[ "MIT" ]
null
null
null
misc/gif.c
chatziko/bitmap
91094bb8b16bc356e9ae3bb2004457149cf75271
[ "MIT" ]
null
null
null
/* Compile like so: gcc -Wall -DTEST gif.c ../bmp.c -o giftest References: http://www.w3.org/Graphics/GIF/spec-gif89a.txt Nelson, M.R. : "LZW Data Compression", Dr. Dobb's Journal, October 1989. http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art011 http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <stdint.h> #include <float.h> #include <string.h> #include <math.h> #include <time.h> #include <assert.h> #include "../bmp.h" #include "gif.h" int gif_verbose = 0; #pragma pack(push, 1) /* Don't use any padding */ struct gif_triplet { uint8_t r, g, b; }; typedef struct { /* header */ struct { char signature[3]; char version[3]; } header; enum {gif_87a, gif_89a} version; /* logical screen descriptor */ struct { unsigned short width; unsigned short height; unsigned char fields; unsigned char background; unsigned char par; /* pixel aspect ratio */ } lsd; GIF *gif; } GIF_FILE; /* GIF Graphic Control Extension */ typedef struct { unsigned char block_size; unsigned char fields; unsigned short delay; unsigned char trans_index; unsigned char terminator; } GIF_GCE; /* GIF Image Descriptor */ typedef struct { unsigned char separator; unsigned short left; unsigned short top; unsigned short width; unsigned short height; unsigned char fields; } GIF_ID; typedef struct { unsigned char block_size; char app_id[8]; char auth_code[3]; } GIF_APP_EXT; typedef struct { uint8_t len; uint8_t index; uint16_t reps; } NAB_BLOCK; typedef struct { unsigned char block_size; unsigned short grid_left; unsigned short grid_top; unsigned short grid_width; unsigned short grid_height; unsigned char text_fg; unsigned char text_bg; } GIF_TXT_EXT; #pragma pack(pop) /* Already defined in bmp.c for the GIF and PCX code, but duplicated here because I need to reconsider the API */ static int cnt_comp_mask(const void*ap, const void*bp); static int count_colors_build_palette(Bitmap *b, struct gif_triplet rgb[256]); static int bsrch_palette_lookup(struct gif_triplet rgb[], int c, int imin, int imax); static int comp_rgb(const void *ap, const void *bp); static int gif_read_image(FILE *fp, GIF_FILE *gif, struct gif_triplet *ct, int sct); static int gif_read_tbid(FILE *fp, GIF_FILE *gif, GIF_ID *gif_id, GIF_GCE *gce, struct gif_triplet *ct, int sct); static unsigned char *gif_data_sub_blocks(FILE *fp, int *r_tsize); static unsigned char *lzw_decode_bytes(unsigned char *bytes, int data_len, int code_size, int *out_len); static void output(FILE *outfile, const char *fmt, ...) { if(gif_verbose) { va_list arg; va_start(arg, fmt); vfprintf(outfile, fmt, arg); va_end(arg); } } static GIF *gif_load_fp(FILE *fp) { GIF_FILE file; /* From the packed fields in the logical screen descriptor */ size_t gct, col_res, sort_flag, sgct; float aspect_ratio; struct gif_triplet *palette = NULL; unsigned char trailer; file.gif = NULL; /* Section 17. Header. */ if(fread(&file.header, sizeof file.header, 1, fp) != 1) { output(stderr, "error: unable to read header\n"); return NULL; } if(memcmp(file.header.signature, "GIF", 3)){ output(stderr, "error: not a GIF\n"); return NULL; } if(!memcmp(file.header.version, "87a", 3)){ output(stdout, "GIF 87a\n"); file.version = gif_87a; } else if(!memcmp(file.header.version, "89a", 3)){ output(stdout, "GIF 89a\n"); file.version = gif_89a; } else { output(stderr, "error: invalid version number\n"); return NULL; } /* Section 18. Logical Screen Descriptor. */ /* Ugh, the compiler I used added a padding byte */ assert(sizeof file.lsd == 7); assert(sizeof *palette == 3); if(fread(&file.lsd, sizeof file.lsd, 1, fp) != 1) { output(stderr, "error: unable to read Logical Screen Descriptor\n"); return NULL; } gct = !!(file.lsd.fields & 0x80); col_res = ((file.lsd.fields >> 4) & 0x07) + 1; sort_flag = !!(file.lsd.fields & 0x08); sgct = file.lsd.fields & 0x07; if(gct) { /* raise 2 to the power of [sgct+1] */ sgct = 1 << (sgct + 1); } if(file.lsd.par == 0) { aspect_ratio = 0.0f; } else { aspect_ratio = ((float)file.lsd.par + 15.0f)/64.0f; } if(gif_verbose) { output(stdout, "Width .......................: %u\n", file.lsd.width); output(stdout, "Height ......................: %u\n", file.lsd.height); output(stdout, "Fields ......................: 0x%X\n", file.lsd.fields); output(stdout, " Global color table ..: %d\n", gct); output(stdout, " Color Resolution ....: %d\n", col_res); output(stdout, " Sort Flag ...........: %d\n", sort_flag); output(stdout, " Size of GCT .........: %d\n", sgct); output(stdout, "Background ..................: %u\n", file.lsd.background); output(stdout, "Px Aspect Ratio .............: %u\n", file.lsd.par); output(stdout, " Calculated ..........: %.4f\n", aspect_ratio); } file.gif = gif_create(file.lsd.width, file.lsd.height); if(gct) { /* Section 19. Global Color Table. */ struct gif_triplet *bg; palette = calloc(sgct, sizeof *palette); if(fread(palette, sizeof *palette, sgct, fp) != sgct) { output(stderr, "error: unable to read Global Color Table\n"); free(palette); return NULL; } output(stdout, "Global Color Table: %d entries\n", sgct); if(gif_verbose > 1) { size_t i; for(i = 0; i < sgct; i++) { output(stdout, " %3d: %02X %02X %02X\n", i, palette[i].r, palette[i].g, palette[i].b); } } /* Set the Bitmap's color to the background color.*/ bg = &palette[file.lsd.background]; file.gif->background = bm_rgb(bg->r, bg->g, bg->b); } else { /* what? */ file.gif->background = 0; palette = NULL; } for(;;) { long pos = ftell(fp); if(!gif_read_image(fp, &file, palette, sgct)) { fseek(fp, pos, SEEK_SET); break; } } if(palette) free(palette); /* Section 27. Trailer. */ if((fread(&trailer, 1, 1, fp) != 1) || trailer != 0x3B) { output(stderr, "error: trailer is not 0x3B\n"); gif_free(file.gif); return NULL; } output(stdout, "Trailer: %02X\n", trailer); return file.gif; } static int gif_read_extension(FILE *fp, GIF_FILE *file, GIF_GCE *gce) { unsigned char introducer, label; if((fread(&introducer, 1, 1, fp) != 1) || introducer != 0x21) { return 0; } if(fread(&label, 1, 1, fp) != 1) { return 0; } output(stdout, "# Introducer ..........: 0x%02X\n", introducer); output(stdout, "# Label ...............: 0x%02X\n", label); if(label == 0xF9) { /* 23. Graphic Control Extension. */ if(fread(gce, sizeof *gce, 1, fp) != 1) { output(stderr, "warning: unable to read Graphic Control Extension\n"); return 0; } if(gif_verbose) { output(stdout, "Graphic Control Extension:\n"); output(stdout, " Terminator ..........: 0x%02X\n", gce->terminator); output(stdout, " Block Size ..........: %d\n", gce->block_size); output(stdout, " Fields ..............: 0x%02X\n", gce->fields); output(stdout, " Dispose ......: %d\n", (gce->fields >> 2) & 0x07); output(stdout, " User Input ...: %d\n", !!(gce->fields & 0x02)); output(stdout, " Transparent ..: %d\n", gce->fields & 0x01); output(stdout, " Delay ...............: %u\n", gce->delay); output(stdout, " Transparent Index ...: %d\n", gce->trans_index); } } else if(label == 0xFE) { /* Section 24. Comment Extension. */ int len; unsigned char *bytes = gif_data_sub_blocks(fp, &len); output(stdout, "Comment Extension: (%d bytes)\n '%s'\n", len, bytes); } else if(label == 0x01) { /* Section 25. Plain Text Extension. */ GIF_TXT_EXT te; int len; unsigned char *bytes; if(fread(&te, sizeof te, 1, fp) != 1) { output(stderr, "warning: unable to read Text Extension\n"); return 0; } bytes = gif_data_sub_blocks(fp, &len); (void)bytes; output(stdout, "Text Extension: (%d bytes)\n", len); } else if(label == 0xFF) { /* Section 26. Application Extension. */ GIF_APP_EXT ae; int len; unsigned char *bytes; if(fread(&ae, sizeof ae, 1, fp) != 1) { output(stderr, "warning: unable to read Application Extension\n"); return 0; } char app_id[9]; char auth_code[4]; memcpy(app_id, ae.app_id, 8); app_id[8] = '\0'; memcpy(auth_code, ae.auth_code, 3); auth_code[3] = '\0'; bytes = gif_data_sub_blocks(fp, &len); output(stdout, "Application Extension: (%d bytes) app_id:'%s' auth_code:'%s'\n", len, app_id, auth_code); if(!strcmp(app_id, "NETSCAPE")) { // && !strcmp(auth_code, "2.0")) { /* https://en.wikipedia.org/wiki/GIF#Animated_GIF http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ int index = bytes[0]; assert(index == 1); file->gif->repetitions = (bytes[2] << 8) | bytes[1]; output(stdout, "Got a NETSCAPE application extension: index:%d; repetitions:%d\n", index, file->gif->repetitions); } } else { output(stdout, "error: unknown label 0x%02X\n", label); } return 1; } /* Section 20. Image Descriptor. */ static int gif_read_image(FILE *fp, GIF_FILE *file, struct gif_triplet *ct, int sct) { GIF_GCE gce; GIF_ID gif_id; /* Packed fields in the Image Descriptor */ size_t lct, intl, sort, slct; memset(&gce, 0, sizeof gce); if(file->version >= gif_89a) { for(;;) { long pos = ftell(fp); if(!gif_read_extension(fp, file, &gce)) { fseek(fp, pos, SEEK_SET); break; } } } if(fread(&gif_id, sizeof gif_id, 1, fp) != 1) { return 0; /* no more blocks to read */ } if(gif_id.separator != 0x2C) { output(stderr, "error: block is not an image descriptor (0x%02X)\n", gif_id.separator); return 0; } lct = !!(gif_id.fields & 0x80); intl = !!(gif_id.fields & 0x40); sort = !!(gif_id.fields & 0x20); slct = gif_id.fields & 0x07; if(lct) { /* Section 21. Local Color Table. */ /* raise 2 to the power of [slct+1] */ slct = 1 << (slct + 1); ct = calloc(slct, sizeof *ct); if(fread(ct, sizeof *ct, slct, fp) != slct) { output(stderr, "error: unable to read local color table\n"); free(ct); return 0; } output(stdout, "Local Color Table: %d entries\n", slct); if(gif_verbose > 1) { size_t i; for(i = 0; i < slct; i++) { output(stdout, " %3d: %02X %02X %02X\n", i, ct[i].r, ct[i].g, ct[i].b); } } sct = slct; } if(gif_verbose) { output(stdout, "Image Descriptor:\n"); output(stdout, " Left ................: %d\n", gif_id.left); output(stdout, " Top .................: %d\n", gif_id.top); output(stdout, " Width ...............: %d\n", gif_id.width); output(stdout, " Height ..............: %d\n", gif_id.height); output(stdout, " Fields ..............: 0x%02X\n", gif_id.fields); output(stdout, " LCT ..........: %d\n", lct); output(stdout, " Interlace ....: %d\n", intl); output(stdout, " Sort .........: %d\n", sort); output(stdout, " Size of LCT ..: %d\n", slct); } if(!gif_read_tbid(fp, file, &gif_id, &gce, ct, sct)) { return 0; /* what? */ } if(lct) { free(ct); } return 1; } /* Section 15. Data Sub-blocks. */ static unsigned char *gif_data_sub_blocks(FILE *fp, int *r_tsize) { unsigned char *buffer = NULL, *pos, size; int tsize = 0; if(r_tsize) *r_tsize = 0; if(fread(&size, 1, 1, fp) != 1) { return NULL; } buffer = realloc(buffer, 1); while(size > 0) { if(gif_verbose > 2) { output(stdout, " Size ................: %d (%d)\n", size, tsize); } buffer = realloc(buffer, tsize + size + 1); pos = buffer + tsize; if(fread(pos, sizeof *pos, size, fp) != size) { free(buffer); return NULL; } tsize += size; if(fread(&size, 1, 1, fp) != 1) { free(buffer); return NULL; } } if(r_tsize) *r_tsize = tsize; buffer[tsize] = '\0'; return buffer; } /* Section 22. Table Based Image Data. */ static int gif_read_tbid(FILE *fp, GIF_FILE *file, GIF_ID *gif_id, GIF_GCE *gce, struct gif_triplet *ct, int sct) { int len, rv = 1; unsigned char *bytes, min_code_size; if(fread(&min_code_size, 1, 1, fp) != 1) { return 0; } output(stdout, "Table Based Image Data:\n"); output(stdout, " Minimum Code Size ...: %d\n", min_code_size); bytes = gif_data_sub_blocks(fp, &len); if(bytes && len > 0) { int i, outlen, x, y; /* Packed fields in the Image Descriptor */ int lct, intl, sort, slct; /* Packed fields in the Graphic Control Extension */ int dispose = 0, user_in = 0, trans_flag = 0; lct = !!(gif_id->fields & 0x80); intl = !!(gif_id->fields & 0x40); sort = !!(gif_id->fields & 0x20); slct = gif_id->fields & 0x07; (void)lct; (void)sort; (void)slct; if(gce->block_size) { /* gce->block_size will be 4 if the GCE is present, 0 otherwise */ dispose = (gce->fields >> 2) & 0x07; user_in = !!(gce->fields & 0x02); (void)user_in; trans_flag = gce->fields & 0x01; } if(gif_id->top + gif_id->height > file->gif->h || gif_id->left + gif_id->width > file->gif->w) { output(stderr, "error: this image descriptor doesn't fall within the bounds of the image"); return 0; } output(stdout, "Data block: %d bytes\n", len); if(gif_verbose > 1) { for(i = 0; i < len; i++) { output(stdout, "%02X ", bytes[i]); } output(stdout, "\n"); } unsigned int background = 0; if(trans_flag) { /* Mmmm, my bitmap module won't be able to handle situations where different image blocks in the GIF has different transparent colors */ struct gif_triplet *bg = &ct[gce->trans_index]; background = bm_rgb(bg->r, bg->g, bg->b); } if(dispose == 2) { GIF_FRAME *frame = gif_new_frame(file->gif); Bitmap *b = frame->image; bm_set_color(b, background); bm_clear(b); frame->delay = gce->delay; frame->trans = gce->fields & 0x01; } else if(dispose != 3) { /* dispose = 0 or 1; if dispose is 3, we leave the new image */ GIF_FRAME *frame; if(file->gif->n) { frame = &file->gif->frames[file->gif->n - 1]; frame = gif_add_frame(file->gif, frame->image); } else { frame = gif_new_frame(file->gif); } frame->delay = gce->delay; frame->trans = gce->fields & 0x01; Bitmap *b = frame->image; unsigned char *decoded = lzw_decode_bytes(bytes, len, min_code_size, &outlen); if(decoded) { if(gif_verbose > 1) { for(i = 0; i < outlen; i++) { output(stdout, "%02X ", decoded[i]); } output(stdout, "\n"); } if(outlen != gif_id->width * gif_id->height) { /* Shouldn't happen unless the file is corrupt */ output(stderr, "error: %d decoded bytes does not fit dimensions %d x %d pixels\n", outlen, gif_id->width, gif_id->height); rv = 0; } else { /* Vars for interlacing: */ int grp = 1, /* Group we're in */ inty = 0, /* Y we're currently at */ inti = 8, /* amount by which we should increment inty */ truey; /* True Y, taking interlacing and the image descriptor into account */ output(stdout, "%d decoded bytes; %d x %d pixels\n", outlen, gif_id->width, gif_id->height); for(i = 0, y = 0; y < gif_id->height && rv; y++) { /* Appendix E. Interlaced Images. */ if(intl) { truey = inty + gif_id->top; inty += inti; if(inty >= gif_id->height) { switch(++grp) { case 2: inti = 8; inty = 4; break; case 3: inti = 4; inty = 2; break; case 4: inti = 2; inty = 1;break; } } } else { truey = y + gif_id->top; } assert(truey >= 0 && truey < file->gif->h); for(x = 0; x < gif_id->width && rv; x++, i++) { int c = decoded[i]; if(c < sct) { struct gif_triplet *rgb = &ct[c]; assert(x + gif_id->left >= 0 && x + gif_id->left < file->gif->w); if(!trans_flag || c != gce->trans_index) { bm_set(b, x + gif_id->left, truey, bm_rgb(rgb->r, rgb->g, rgb->b)); } } else { /* Decode error */ rv = 0; } } } } free(decoded); } } free(bytes); } return rv; } typedef struct { int prev; int code; } gif_dict; static int lzw_read_code(unsigned char bytes[], int bits, int *pos) { int i, bi, code = 0; assert(pos); for(i = *pos, bi=1; i < *pos + bits; i++, bi <<=1) { int byte = i >> 3; int bit = i & 0x07; if(bytes[byte] & (1 << bit)) code |= bi; } *pos = i; return code; } static unsigned char *lzw_decode_bytes(unsigned char *bytes, int data_len, int code_size, int *out_len) { unsigned char *out = NULL; int out_size = 32; int outp = 0; int base_size = code_size; int pos = 0, code, old = -1; /* Clear and end of stream codes */ int clr = 1 << code_size; int end = clr + 1; /* Dictionary */ int di, dict_size = 1 << (code_size + 1); gif_dict *dict = realloc(NULL, dict_size * sizeof *dict); /* Stack so we don't need to recurse down the dictionary */ int stack_size = 2; unsigned char *stack = realloc(NULL, stack_size); int sp = 0; int sym = -1, ptr; *out_len = 0; out = realloc(NULL, out_size); /* Initialize the dictionary */ for(di = 0; di < dict_size; di++) { dict[di].prev = -1; dict[di].code = di; } di = end + 1; code = lzw_read_code(bytes, code_size + 1, &pos); while((pos >> 3) <= data_len + 1) { if(code == clr) { code_size = base_size; dict_size = 1 << (code_size + 1); di = end + 1; code = lzw_read_code(bytes, code_size + 1, &pos); old = -1; continue; } else if(code == end) { break; } if(code > di) { /* Shouldn't happen, unless file corrupted */ output(stderr, "error: code (%02Xh) is outside dictionary (%02Xh); code size: %d\n", code, di, code_size); free(dict); free(stack); free(out); return NULL; } if(code == di) { /* Code is not in the table */ ptr = old; stack[sp++] = sym; } else { /* Code is in the table */ ptr = code; } /* Walk down the dictionary and push the codes onto a stack */ while(ptr >= 0) { stack[sp++] = dict[ptr].code; if(sp == stack_size) { stack_size <<= 1; stack = realloc(stack, stack_size); } ptr = dict[ptr].prev; } sym = stack[sp-1]; /* Output the decoded bytes */ while(sp > 0) { out[outp++] = stack[--sp]; if(outp == out_size) { out_size <<= 1; out = realloc(out, out_size); } } /* update the dictionary */ if(old >= 0) { if(di < dict_size) { dict[di].prev = old; dict[di].code = sym; di++; } /* Resize the dictionary? */ if(di == dict_size && code_size < 11) { code_size++; dict_size = 1 << (code_size + 1); dict = realloc(dict, dict_size * sizeof *dict); } } old = code; code = lzw_read_code(bytes, code_size + 1, &pos); } free(stack); free(dict); *out_len = outp; return out; } static void lzw_emit_code(unsigned char **buffer, int *buf_size, int *pos, int c, int bits) { int i, m; for(i = *pos, m = 1; i < *pos + bits; i++, m <<= 1) { int byte = i >> 3; int bit = i & 0x07; if(!bit) { if(byte == *buf_size) { *buf_size <<= 1; *buffer = realloc(*buffer, *buf_size); } (*buffer)[byte] = 0x00; } if(c & m) (*buffer)[byte] |= (1 << bit); } *pos += bits; } static unsigned char *lzw_encode_bytes(unsigned char *bytes, int data_len, int code_size, int *out_len) { int base_size = code_size; /* Clear and end of stream codes */ int clr = 1 << code_size; int end = clr + 1; /* dictionary */ int i, di, dict_size = 1 << (code_size + 1); gif_dict *dict = realloc(NULL, dict_size * sizeof *dict); int buf_size = 4; int pos = 0; unsigned char *buffer = realloc(NULL, buf_size); *out_len = 0; /* Initialize the dictionary */ for(di = 0; di < dict_size; di++) { dict[di].prev = -1; dict[di].code = di; } di = end+1; dict[clr].prev = -1; dict[clr].code = -1; dict[end].prev = -1; dict[end].code = -1; int ii = 0; int string = -1; int prev = clr; lzw_emit_code(&buffer, &buf_size, &pos, clr, code_size + 1); for(ii = 0; ii < data_len; ii++) { int character; reread: character = bytes[ii]; /* Find it in the dictionary; If the entry is in the dict, it can't be before dict[string], therefore we can eliminate the first couple of entries. */ int res = -1; for(i = string>0?string:0; i < di; i++) { if(dict[i].prev == string && dict[i].code == character) { res = i; break; } } if(res >= 0) { /* Found */ string = res; prev = res; } else { /* Not found */ lzw_emit_code(&buffer, &buf_size, &pos, prev, code_size + 1); /* update the dictionary */ if(di == dict_size) { /* Resize the dictionary */ if(code_size < 11) { code_size++; dict_size = 1 << (code_size + 1); dict = realloc(dict, dict_size * sizeof *dict); } else { /* lzw_emit_code a clear code */ lzw_emit_code(&buffer, &buf_size, &pos, clr,code_size + 1); code_size = base_size; dict_size = 1 << (code_size + 1); di = end + 1; string = -1; prev = clr; goto reread; } } dict[di].prev = string; dict[di].code = character; di++; string = character; prev = character; } } lzw_emit_code(&buffer, &buf_size, &pos, prev,code_size + 1); lzw_emit_code(&buffer, &buf_size, &pos, end,code_size + 1); /* Total length */ int tlen = (pos >> 3); if(pos & 0x07) tlen++; *out_len = tlen; free(dict); return buffer; } GIF *gif_load(const char *filename) { FILE *fp = fopen(filename, "rb"); GIF *gif; if(!fp) { output(stderr, "error: unable to open %s\n", filename); return NULL; } gif = gif_load_fp(fp); fclose(fp); return gif; } static int gif_save_fp(GIF *g, FILE *f) { GIF_FILE file; GIF_GCE gce; GIF_ID gif_id; unsigned int nc, sgct, bg; struct gif_triplet gct[256]; unsigned char code_size = 0x08; Bitmap *b = g->n > 0 ? g->frames[0].image : NULL; if(!b) return 0; memcpy(file.header.signature, "GIF", 3); memcpy(file.header.version, "89a", 3); file.version = gif_89a; file.lsd.width = g->w; file.lsd.height = g->h; file.lsd.background = 0; file.lsd.par = 0; /* Using global color table, color resolution = 8-bits */ file.lsd.fields = 0xF0; unsigned int palette[256], q; if(g->palette) { nc = g->palette_size; assert(nc > 0); /* You must have at least some colors in your palette */ bg = b->color & 0x00FFFFFF; for(q = 0; q < nc; q++) { bm_get_rgb(g->palette[q], &gct[q].r, &gct[q].g, &gct[q].b); } qsort(gct, nc, sizeof gct[0], comp_rgb); for(q = 0; q < nc; q++) { palette[q] = (gct[q].r << 16) | (gct[q].g << 8) | gct[q].b; } } else { nc = count_colors_build_palette(b, gct); if(nc < 0) { /* Too many colors */ sgct = 256; file.lsd.fields |= 0x07; for(nc = 0; nc < 256; nc++) { /* FIXME: Octree color quantization My color quantization method is to just choose random pixels, and hope for the best. */ int c = bm_get(b, rand()%b->w, rand()%b->h); gct[nc].r = (c >> 16) & 0xFF; gct[nc].g = (c >> 8) & 0xFF; gct[nc].b = (c >> 0) & 0xFF; } } qsort(gct, nc, sizeof gct[0], comp_rgb); for(q = 0; q < nc; q++) { palette[q] = (gct[q].r << 16) | (gct[q].g << 8) | gct[q].b; } } if(nc > 128) { sgct = 256; file.lsd.fields |= 0x07; } else if(nc > 64) { sgct = 128; file.lsd.fields |= 0x06; code_size = 7; } else if(nc > 32) { sgct = 64; file.lsd.fields |= 0x05; code_size = 6; } else if(nc > 16) { sgct = 32; file.lsd.fields |= 0x04; code_size = 5; } else if(nc > 8) { sgct = 16; file.lsd.fields |= 0x03; code_size = 4; } else { sgct = 8; file.lsd.fields |= 0x02; code_size = 3; } /* See if we can find the background color in the palette */ bg = b->color & 0x00FFFFFF; q = bsrch_palette_lookup(gct, bg, 0, nc - 1); if(q >= 0) { file.lsd.background = q; } if(fwrite(&file.header, sizeof file.header, 1, f) != 1) { output(stderr, "error: unable to write header.\n"); return 0; } if(fwrite(&file.lsd, sizeof file.lsd, 1, f) != 1) { output(stderr, "error: unable to write logical screen descriptor.\n"); return 0; } if(fwrite(gct, sizeof *gct, sgct, f) != sgct) { output(stderr, "error: unable to write global color table.\n"); return 0; } if(g->repetitions != 1) { /* Netscape Application Block for looping animations https://en.wikipedia.org/wiki/GIF#Animated_GIF http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension */ GIF_APP_EXT ae; NAB_BLOCK nab; fputc(0x21, f); fputc(0xFF, f); ae.block_size = 0x0B; memcpy(ae.app_id, "NETSCAPE", 8); memcpy(ae.auth_code, "2.0", 3); nab.len = 3; nab.index = 1; nab.reps = g->repetitions; assert(sizeof nab == 4); if(fwrite(&ae, sizeof ae, 1, f) != 1 || fwrite(&nab, sizeof nab, 1, f) != 1) { output(stderr, "error: unable to write Netscape Application Block.\n"); return 0; } fputc(0x00, f); /* terminating block */ } unsigned char *pixels = malloc(g->w * g->h); int fi; for(fi = 0; fi < g->n; fi++) { b = g->frames[fi].image; assert(b->w == g->w && b->h == g->h); bm_reduce_palette(b, palette, nc); /* Map the pixels in the image to their palette indices */ int x, y, p = 0; for(y = 0; y < b->h; y++) { for(x = 0; x < b->w; x++) { unsigned int i; int c = bm_get(b, x, y); i = bsrch_palette_lookup(gct, c, 0, nc - 1); /* At this point in time, the color MUST be in the palette */ assert(i >= 0); assert(i < sgct); pixels[p++] = i; } } assert(p == b->w * b->h); gce.block_size = 4; gce.fields = 0x04; gce.delay = g->frames[fi].delay; if(g->frames[fi].trans && bg >= 0) { gce.fields |= 0x01; gce.trans_index = bg; } else { gce.trans_index = 0; } gce.terminator = 0x00; fputc(0x21, f); fputc(0xF9, f); if(fwrite(&gce, sizeof gce, 1, f) != 1) { output(stderr, "error: unable to write graphic control extension.\n"); return 0; } gif_id.separator = 0x2C; gif_id.left = 0x00; gif_id.top = 0x00; gif_id.width = b->w; gif_id.height = b->h; /* Not using local color table or interlacing */ gif_id.fields = 0; if(fwrite(&gif_id, sizeof gif_id, 1, f) != 1) { output(stderr, "error: unable to write image descriptor.\n"); return 0; } fputc(code_size, f); /* Perform the LZW compression */ int len; unsigned char *bytes = lzw_encode_bytes(pixels, b->w * b->h, code_size, &len); /* Write out the data sub-blocks */ for(p = 0; p < len; p++) { if(p % 0xFF == 0) { /* beginning of a new block; lzw_emit_code the length byte */ if(len - p >= 0xFF) { fputc(0xFF, f); } else { fputc(len - p, f); } } fputc(bytes[p], f); } free(bytes); fputc(0x00, f); /* terminating block */ } free(pixels); fputc(0x3B, f); /* trailer byte */ return 1; } int gif_save(GIF *g, const char *filename) { FILE *fp = fopen(filename, "wb"); if(!fp) { output(stderr, "error: unable to open %s\n", filename); return 0; } gif_save_fp(g, fp); fclose(fp); return 1; } GIF *gif_create(int w, int h) { GIF *gif = malloc(sizeof *gif); gif->w = w; gif->h = h; gif->background = 0; gif->repetitions = 1; gif->a = 8; gif->n = 0; gif->frames = calloc(gif->a, sizeof *gif->frames); gif->default_delay = 2; gif->palette = 0; gif->palette_size = 0; return gif; } void gif_free(GIF *gif) { int i; for(i = 0; i < gif->n; i++) { bm_free(gif->frames[i].image); } free(gif->frames); free(gif); } GIF_FRAME *gif_add_frame(GIF *g, Bitmap *b) { if(b->w != g->w || b->h != g->h) { if(g->w > b->w || g->h > b->h) { b = bm_resample_blin(b, g->w, g->h); } else { b = bm_resample_bcub(b, g->w, g->h); } } else { b = bm_copy(b); } bm_set_color(b, g->background); if(g->n == g->a) { g->a <<= 1; g->frames = realloc(g->frames, g->a * sizeof *g->frames); } assert(g->n < g->a); memset(&g->frames[g->n], 0, sizeof g->frames[g->n]); g->frames[g->n].image = b; g->frames[g->n].delay = g->default_delay; return &g->frames[g->n++]; } GIF_FRAME *gif_new_frame(GIF *g) { Bitmap *b = bm_create(g->w, g->h); bm_set_color(b, g->background); bm_clear(b); if(g->n == g->a) { g->a <<= 1; g->frames = realloc(g->frames, g->a * sizeof *g->frames); } assert(g->n < g->a); memset(&g->frames[g->n], 0, sizeof g->frames[g->n]); g->frames[g->n].image = b; g->frames[g->n].delay = 2; return &g->frames[g->n++]; } void gif_set_palette(GIF *gif, unsigned int *palette, unsigned int palette_size) { gif->palette = palette; if(palette_size > 256) palette_size = 256; gif->palette_size = palette_size; } #if 1 /***** FIXME: These functions are already defined as static in bmp.c. I'd like to modify the API at some stage to expose the functionality via bmp.h, but the function prototypes would need some thought. Ideally, I should have a bm_quantize() function that takes care of quantizing the image and creating a palette. Rosettacode has a nice color quantization implementation based on octrees. http://rosettacode.org/wiki/Color_quantization#C *****/ static int cnt_comp_mask(const void*ap, const void*bp) { int a = *(int*)ap, b = *(int*)bp; return (a & 0x00FFFFFF) - (b & 0x00FFFFFF); } /* Variation on bm_count_colors() that builds an 8-bit palette while it is counting. * It returns -1 in case there are more than 256 colours in the palette, meaning the * image will have to be quantized first. * It also ignores the alpha values of the pixels. */ static int count_colors_build_palette(Bitmap *b, struct gif_triplet rgb[256]) { int count = 1, i, c; int npx = b->w * b->h; int *sort = malloc(npx * sizeof *sort); memcpy(sort, b->data, npx * sizeof *sort); qsort(sort, npx, sizeof(int), cnt_comp_mask); c = sort[0] & 0x00FFFFFF; rgb[0].r = (c >> 16) & 0xFF; rgb[0].g = (c >> 8) & 0xFF; rgb[0].b = (c >> 0) & 0xFF; for(i = 1; i < npx; i++){ c = sort[i] & 0x00FFFFFF; if(c != (sort[i-1]& 0x00FFFFFF)) { if(count == 256) { return -1; } rgb[count].r = (c >> 16) & 0xFF; rgb[count].g = (c >> 8) & 0xFF; rgb[count].b = (c >> 0) & 0xFF; count++; } } free(sort); return count; } /* Uses a binary search to find the index of a colour in a palette. It almost goes without saying that the palette must be sorted */ static int bsrch_palette_lookup(struct gif_triplet rgb[], int c, int imin, int imax) { c &= 0x00FFFFFF; /* Ignore the alpha value */ while(imax >= imin) { int imid = (imin + imax) >> 1; assert(imid <= 255); int c2 = (rgb[imid].r << 16) | (rgb[imid].g << 8) | rgb[imid].b; if(c == c2) return imid; else if(c2 < c) imin = imid + 1; else imax = imid - 1; } return -1; } /* Comparison function for sorting an array of rgb_triplets with qsort() */ static int comp_rgb(const void *ap, const void *bp) { const struct gif_triplet *ta = ap, *tb = bp; int a = (ta->r << 16) | (ta->g << 8) | ta->b; int b = (tb->r << 16) | (tb->g << 8) | tb->b; return a - b; } #endif /* Test program main() function */ #ifdef TEST int main(int argc, char *argv[]) { /* FIXME: The color quantization shouldn't depend on rand() :( */ srand(time(NULL)); gif_verbose = 1; if(argc < 2) { fprintf(stderr, "usage: %s file.gif\n", argv[0]); return 1; } assert(sizeof(unsigned short) == 2); GIF *gif = gif_load(argv[1]); if(gif) { char buffer[50]; int i; for(i = 0; i < gif->n; i++) { sprintf(buffer, "frame%03d.bmp", i); printf("Saving %s...\n", buffer); bm_save(gif->frames[i].image, buffer); } printf("Saving GIF output...\n"); if(!gif_save(gif, "gifout.gif")) { fprintf(stderr, "error: Unable to save GIF\n"); return 1; } gif_free(gif); } else { fprintf(stderr, "Couldn't read GIF\n"); return 1; } return 0; } #endif
30.407587
142
0.500703
[ "3d" ]
4399ef05230e3a398c9c2966436790d37868ec7f
6,327
h
C
flashlight/app/asr/tools/alignment/Utils.h
duskvirkus/flashlight
d0956077455a5dce3d70045b3f1c8d51d3ce8343
[ "MIT" ]
2,858
2021-04-15T16:56:46.000Z
2022-03-31T12:40:46.000Z
flashlight/app/asr/tools/alignment/Utils.h
duskvirkus/flashlight
d0956077455a5dce3d70045b3f1c8d51d3ce8343
[ "MIT" ]
487
2018-12-22T10:32:59.000Z
2021-04-15T07:01:13.000Z
flashlight/app/asr/tools/alignment/Utils.h
duskvirkus/flashlight
d0956077455a5dce3d70045b3f1c8d51d3ce8343
[ "MIT" ]
237
2018-12-21T20:00:36.000Z
2021-04-13T14:33:40.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ #include <codecvt> #include <locale> #include <string> #include <unordered_map> #include <vector> #include "flashlight/pkg/speech/common/Defines.h" #include "flashlight/pkg/speech/criterion/criterion.h" #include "flashlight/lib/text/dictionary/Dictionary.h" using namespace fl::pkg::speech; namespace fl { namespace app { namespace asr { namespace alignment { struct AlignedWord { std::string word; double startTimeMs; double endTimeMs; }; void remapUTFWord(std::u16string& input, int replabel) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv; // dedup labels auto it = std::unique(input.begin(), input.end()); input.resize(std::distance(input.begin(), it)); // map of replabels std::unordered_map<char16_t, int64_t> replabelMap; for (int64_t i = 1; i <= replabel; ++i) { replabelMap[utf16conv.from_bytes("<" + std::to_string(i) + ">")[0]] = i; } std::u16string output; output += input[0]; for (size_t i = 1; i < input.size(); ++i) { auto repCount = replabelMap.find(input[i]); if (repCount != replabelMap.end()) { for (auto j = 0; j < repCount->second; j++) { output += input[i - 1]; } } else { output += input[i]; } } std::swap(input, output); } std::vector<std::vector<std::string>> mapIndexToToken( af::array paths, fl::lib::text::DictionaryMap dicts) { const int B = paths.dims(1); const int T = paths.dims(0); std::vector<std::vector<std::string>> batchTokensPath; for (int b = 0; b < B; b++) { std::vector<std::string> tokens; for (int t = 0; t < T; t++) { int p = paths(t, b).scalar<int>(); if (p == -1) { break; } auto token = dicts[kTargetIdx].getEntry(p); tokens.push_back(token); } batchTokensPath.push_back(tokens); } return batchTokensPath; } std::vector<AlignedWord> postprocessCTC( const std::vector<std::string>& ltrs, int replabel, double msPerFrame) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv; std::vector<std::u16string> utf16Ltrs; for (const std::string& l : ltrs) { utf16Ltrs.push_back(utf16conv.from_bytes(l)); } std::vector<AlignedWord> alignedWords; const int T = utf16Ltrs.size(); int i = 0; while (i < T) { std::u16string currWord = utf16Ltrs[i]; int j = i; while (j + 1 < T && utf16Ltrs[i] == utf16Ltrs[j + 1]) { j += 1; } j++; double endTimeMs = msPerFrame * (j); double startTimeMs = msPerFrame * i; remapUTFWord(currWord, replabel); alignedWords.push_back( AlignedWord{utf16conv.to_bytes(currWord), startTimeMs, endTimeMs}); i = j; } return alignedWords; } std::vector<AlignedWord> postprocessASG( const std::vector<std::string>& ltrs, int replabel, double msPerFrame) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> utf16conv; std::vector<std::u16string> utf16Ltrs; for (const std::string& l : ltrs) { utf16Ltrs.push_back(utf16conv.from_bytes(l)); } std::vector<AlignedWord> alignedWords; std::u16string currWord; int stFrame = 0; bool inWord = false; int silStart = 0; for (int i = 0; i < utf16Ltrs.size(); i++) { if (utf16Ltrs[i] == utf16conv.from_bytes(kSilToken)) { if (inWord) { // found end of word, insert const double endTimeMs = msPerFrame * i; const double startTimeMs = msPerFrame * stFrame; remapUTFWord(currWord, replabel); alignedWords.push_back( {utf16conv.to_bytes(currWord), startTimeMs, endTimeMs}); inWord = false; silStart = i; } } else if (!inWord) { // starting new word stFrame = i; currWord = utf16Ltrs[i]; inWord = true; // Also insert silence if (silStart < i - 1) { alignedWords.push_back({"$", msPerFrame * silStart, msPerFrame * (i)}); } } else { // continue in same word currWord += utf16Ltrs[i]; } } // Take care of trailing silence or trailing word const double endTimeMs = msPerFrame * (utf16Ltrs.size()); if (inWord) { // we may encounter trailing word only // if we train without -surround='|' currWord += utf16Ltrs[utf16Ltrs.size() - 1]; remapUTFWord(currWord, replabel); alignedWords.push_back( {utf16conv.to_bytes(currWord), msPerFrame * stFrame, endTimeMs}); } else { alignedWords.push_back({"$", msPerFrame * silStart, endTimeMs}); } return alignedWords; return std::vector<AlignedWord>(); } // TODO T61657501 move the "wordSegmenter" function into the criterion class // once we are ready to move out of experimental std::function< std::vector<AlignedWord>(const std::vector<std::string>&, int, double)> getWordSegmenter(std::shared_ptr<SequenceCriterion> criterion) { const std::string& desc = criterion->prettyString(); const std::string asgDesc = "AutoSegmentationCriterion"; const std::string ctcDesc = "ConnectionistTemporalClassificationCriterion"; if (desc == ctcDesc) { return postprocessCTC; } else if (desc == asgDesc) { return postprocessASG; } else { throw std::invalid_argument("Alignment not supported for this criterion"); return std::function<std::vector<AlignedWord>( const std::vector<std::string>&, int, double)>(); } } // Utility function which converts the aligned words // into CTM format which is compatible with AML's alignment output. // this format can be used in several workflows later, including // segmentation workflow. std::string getCTMFormat(std::vector<AlignedWord> alignedWords) { std::stringstream ctmString; int i = 0; for (auto& alignedWord : alignedWords) { double stTimeSec = alignedWord.startTimeMs / 1000.0; double durationSec = (alignedWord.endTimeMs - alignedWord.startTimeMs) / 1000.0; ctmString << "ID A " << stTimeSec << " " << durationSec << " " << alignedWord.word; if (i < alignedWords.size() - 1) { ctmString << "\\n"; } i++; } return ctmString.str(); } } // namespace alignment } // namespace asr } // namespace app } // namespace fl
29.985782
79
0.652916
[ "vector" ]
439afa5cb1e278c09345f921004e34980aa881db
2,519
h
C
src/vulkan/buffer_descriptor.h
jekstrand/amber
21e07d7e7c99264a894698cd62c579b6f8178daa
[ "Apache-2.0" ]
161
2018-11-14T12:04:08.000Z
2022-03-31T01:08:21.000Z
src/vulkan/buffer_descriptor.h
jekstrand/amber
21e07d7e7c99264a894698cd62c579b6f8178daa
[ "Apache-2.0" ]
545
2018-11-14T03:52:30.000Z
2022-03-30T11:23:12.000Z
src/vulkan/buffer_descriptor.h
jekstrand/amber
21e07d7e7c99264a894698cd62c579b6f8178daa
[ "Apache-2.0" ]
59
2018-11-13T22:09:02.000Z
2022-01-26T22:25:29.000Z
// Copyright 2018 The Amber 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 // // 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 SRC_VULKAN_BUFFER_DESCRIPTOR_H_ #define SRC_VULKAN_BUFFER_DESCRIPTOR_H_ #include <memory> #include <unordered_map> #include <utility> #include <vector> #include "amber/result.h" #include "amber/value.h" #include "amber/vulkan_header.h" #include "src/buffer.h" #include "src/engine.h" #include "src/vulkan/buffer_backed_descriptor.h" #include "src/vulkan/pipeline.h" #include "src/vulkan/transfer_buffer.h" namespace amber { namespace vulkan { class CommandBuffer; class Device; /// Stores descriptor set and binding information for storage and uniform /// buffers. class BufferDescriptor : public BufferBackedDescriptor { public: BufferDescriptor(Buffer* buffer, DescriptorType type, Device* device, uint32_t desc_set, uint32_t binding, vulkan::Pipeline* pipeline); ~BufferDescriptor() override; void UpdateDescriptorSetIfNeeded(VkDescriptorSet descriptor_set) override; Result CreateResourceIfNeeded() override; std::vector<uint32_t> GetDynamicOffsets() override { return dynamic_offsets_; } void AddDynamicOffset(uint32_t offset) { dynamic_offsets_.push_back(offset); } std::vector<uint64_t> GetDescriptorOffsets() override { return descriptor_offsets_; } void AddDescriptorOffset(uint64_t descriptor_offset) { descriptor_offsets_.push_back(descriptor_offset); } std::vector<uint64_t> GetDescriptorRanges() override { return descriptor_ranges_; } void AddDescriptorRange(uint64_t descriptor_range) { descriptor_ranges_.push_back(descriptor_range); } BufferDescriptor* AsBufferDescriptor() override { return this; } private: std::vector<uint32_t> dynamic_offsets_; std::vector<VkDeviceSize> descriptor_offsets_; std::vector<VkDeviceSize> descriptor_ranges_; }; } // namespace vulkan } // namespace amber #endif // SRC_VULKAN_BUFFER_DESCRIPTOR_H_
31.098765
80
0.745137
[ "vector" ]
439ed1b1e9a58474dbce4c9b62f9dfbcb1bf3f59
9,488
h
C
include/devsdk/devsdk.h
jamesiotech/device-sdk-c
9d735d1f6129c08be60f72e7e36f35f4ed1f8142
[ "Apache-2.0" ]
null
null
null
include/devsdk/devsdk.h
jamesiotech/device-sdk-c
9d735d1f6129c08be60f72e7e36f35f4ed1f8142
[ "Apache-2.0" ]
null
null
null
include/devsdk/devsdk.h
jamesiotech/device-sdk-c
9d735d1f6129c08be60f72e7e36f35f4ed1f8142
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 * IoTech Ltd * * SPDX-License-Identifier: Apache-2.0 * */ #ifndef _DEVSDK_DEVSDK_H_ #define _DEVSDK_DEVSDK_H_ 1 #define DEVSDKV2 #ifdef DEVSDKV1 #error Only one of edgex/devsdk.h and devsdk/devsdk.h may be included #endif /** * @file * @brief This file defines the functions and callbacks relating to the SDK. */ #include "devsdk/devsdk-base.h" #include "iot/logger.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Prints usage information. */ void devsdk_usage (void); /* Callback functions */ /** * @brief Function called during service start operation. * @param impl The context data passed in when the service was created. * @param lc A logging client for the device service. * @param config A string map containing the the configuration specified in the service's "Driver" section. * @return true if the operation was successful, false otherwise. */ typedef bool (*devsdk_initialize) (void *impl, struct iot_logger_t *lc, const iot_data_t *config); /** * @brief Optional callback for dynamic discovery of devices. The implementation should detect devices and register them using * the devsdk_add_device API call. * @param impl The context data passed in when the service was created. */ typedef void (*devsdk_discover) (void *impl); /** * @brief Callback issued to handle GET requests for device readings. * @param impl The context data passed in when the service was created. * @param devname The name of the device to be queried. * @param protocols The location of the device to be queried. * @param nreadings The number of readings requested. * @param requests An array specifying the readings that have been requested. * @param readings An array in which to return the requested readings. * @param qparams Query Parameters which were set for this request. * @param exception Set this to an IOT_DATA_STRING to give more information if the operation fails. * @return true if the operation was successful, false otherwise. */ typedef bool (*devsdk_handle_get) ( void *impl, const char *devname, const devsdk_protocols *protocols, uint32_t nreadings, const devsdk_commandrequest *requests, devsdk_commandresult *readings, const devsdk_nvpairs *qparams, iot_data_t **exception ); /** * @brief Callback issued to handle PUT requests for setting device values. * @param impl The context data passed in when the service was created. * @param devname The name of the device to be queried. * @param protocols The location of the device to be queried. * @param nvalues The number of set operations requested. * @param requests An array specifying the resources to which to write. * @param values An array specifying the values to be written. * @param exception Set this to an IOT_DATA_STRING to give more information if the operation fails. * @return true if the operation was successful, false otherwise. */ typedef bool (*devsdk_handle_put) ( void *impl, const char *devname, const devsdk_protocols *protocols, uint32_t nvalues, const devsdk_commandrequest *requests, const iot_data_t *values[], iot_data_t **exception ); /** * @brief Callback issued during device service shutdown. The implementation should stop processing and release any resources that were being used. * @param impl The context data passed in when the service was created. * @param force A 'force' stop has been requested. An unclean shutdown may be performed if necessary. */ typedef void (*devsdk_stop) (void *impl, bool force); /** * @brief Callback function requesting that automatic events should begin. These should be generated according to the schedule given, * and posted using devsdk_post_readings(). * @param impl The context data passed in when the service was created. * @param devname The name of the device to be queried. * @param protocols The location of the device to be queried. * @param resource_name The resource on which autoevents have been configured. * @param nreadings The number of readings requested. * @param requests An array specifying the readings that have been requested. * @param interval The time between events, in milliseconds. * @param onChange If true, events should only be generated if one or more readings have changed. * @return A pointer to a data structure that will be provided in a subsequent call to the stop handler. */ typedef void * (*devsdk_autoevent_start_handler) ( void *impl, const char *devname, const devsdk_protocols *protocols, const char *resource_name, uint32_t nreadings, const devsdk_commandrequest *requests, uint64_t interval, bool onChange ); /** * @brief Callback function requesting that automatic events should cease. * @param impl The context data passed in when the service was created. * @param handle The data structure returned by a previous call to the start handler. */ typedef void (*devsdk_autoevent_stop_handler) (void *impl, void *handle); /** * @brief Callback function indicating that a new device has been added. * @param impl The context data passed in when the service was created. * @param devname The name of the new device. * @param protocols The protocol properties that comprise the device's address. * @param state The device's initial adminstate. */ typedef void (*devsdk_add_device_callback) (void *impl, const char *devname, const devsdk_protocols *protocols, bool adminEnabled); /** * @brief Callback function indicating that a device's address or adminstate has been updated. * @param impl The context data passed in when the service was created. * @param devname The name of the updated device. * @param protocols The protocol properties that comprise the device's address. * @param state The device's current adminstate. */ typedef void (*devsdk_update_device_callback) (void *impl, const char *devname, const devsdk_protocols *protocols, bool adminEnabled); /** * @brief Callback function indicating that a device has been removed. * @param impl The context data passed in when the service was created. * @param devname The name of the removed device. * @param protocols The protocol properties that comprise the device's address. */ typedef void (*devsdk_remove_device_callback) (void *impl, const char *devname, const devsdk_protocols *protocols); typedef struct devsdk_callbacks { devsdk_initialize init; devsdk_discover discover; /* NULL for no discovery */ devsdk_handle_get gethandler; devsdk_handle_put puthandler; devsdk_stop stop; devsdk_add_device_callback device_added; /* May be NULL */ devsdk_update_device_callback device_updated; /* May be NULL */ devsdk_remove_device_callback device_removed; /* May be NULL */ devsdk_autoevent_start_handler ae_starter; /* NULL for SDK-managed autoevents */ devsdk_autoevent_stop_handler ae_stopper; /* NULL for SDK-managed autoevents */ } devsdk_callbacks; /** * @brief Create a new device service. * @param defaultname The device service name, used in logging, metadata lookups and to scope configuration. This may be overridden via the commandline. * @param version The version string for this service. For information only. * @param impldata An object pointer which will be passed back whenever one of the callback functions is invoked. * @param implfns Structure containing the device implementation functions. The SDK will call these functions in order to carry out its various actions. * @param argc A pointer to argc as passed into main(). This will be adjusted to account for arguments consumed by the SDK. * @param argv argv as passed into main(). This will be adjusted to account for arguments consumed by the SDK. * @param err Nonzero reason codes will be set here in the event of errors. * @return The newly instantiated service */ devsdk_service_t *devsdk_service_new (const char *defaultname, const char *version, void *impldata, devsdk_callbacks implfns, int *argc, char **argv, devsdk_error *err); /** * @brief Start a device service. * @param svc The service to start. * @param err Nonzero reason codes will be set here in the event of errors. */ void devsdk_service_start (devsdk_service_t *svc, devsdk_error *err); /** * @brief Post readings to the core-data service. This method allows readings to be generated other than in response to a device GET invocation. * @param svc The device service. * @param device_name The name of the device that the readings have come from. * @param resource_name Name of the resource or command which defines the Event. * @param values An array of readings. These will be combined into an Event and submitted to core-data. */ void devsdk_post_readings (devsdk_service_t *svc, const char *device_name, const char *resource_name, devsdk_commandresult *values); void devsdk_add_discovered_devices (devsdk_service_t *svc, uint32_t ndevices, devsdk_discovered_device *devices); /** * @brief Stop the event service. Any automatic events will be cancelled and the rest api for the device service will be shut down. * @param svc The device service. * @param force Force stop. * @param err Nonzero reason codes will be set here in the event of errors. */ void devsdk_service_stop (devsdk_service_t *svc, bool force, devsdk_error *err); /** * @brief Free the device service object and associated resources. * @param svc The device service. */ void devsdk_service_free (devsdk_service_t *svc); #ifdef __cplusplus } #endif #endif
38.726531
152
0.759802
[ "object" ]
43a04ca0af55821267ce3f6ac253e5048b24a2be
3,972
h
C
gameplay/src/storefront/StoreListener.h
reven86/GamePlay
7e543734b86d42a40d36ffc95e4a4b5fed678056
[ "Apache-2.0" ]
7
2017-02-08T20:17:19.000Z
2020-12-26T03:11:37.000Z
gameplay/src/storefront/StoreListener.h
reven86/GamePlay
7e543734b86d42a40d36ffc95e4a4b5fed678056
[ "Apache-2.0" ]
null
null
null
gameplay/src/storefront/StoreListener.h
reven86/GamePlay
7e543734b86d42a40d36ffc95e4a4b5fed678056
[ "Apache-2.0" ]
2
2016-01-25T17:58:44.000Z
2016-08-30T15:37:34.000Z
#ifndef STORELISTENER_H_ #define STORELISTENER_H_ #include "StoreProduct.h" namespace gameplay { /** * Defines a class for handling storefront responses. * * @script{ignore} */ class StoreListener { public: /** * Constructor */ StoreListener() {}; /** * Destructor */ virtual ~StoreListener() {}; /** * Get called when information about submitted products is received from store. * * @param products List of valid products. * @param invalidProducts IDs of invalid products. These products can't purchased and should not be displayed to user. * * @see StoreFront::getProducts */ virtual void getProductsEvent( const std::vector<StoreProduct>& products, const std::vector<std::string>& invalidProducts ) {}; /** * Get called in case of error in obtaining products' information. * * @param errorCode Error code. * @param errorUTF8 UTF-8 error string. */ virtual void getProductsFailedEvent( int errorCode, const char * errorUTF8 ) {}; /** * Transaction is being processed event. * * @param productID Product for which transaction is being processed. * @param quantity Product's quantity. * * @see StoreFront::makePayment. */ virtual void paymentTransactionInProcessEvent( const char * productID, int quantity ) {}; /** * Transaction is succeeded. * You must manually call StoreFront::finishTransaction to remove transaction from the queue, * when you've done processing and validating it. * * @param productID Product for which transaction is being processed. * @param quantity Product's quantity. * @param timestamp UNIX timestamp for a transaction. * @param transactionID Transaction ID. * @param transactionObject Transaction object. * * @see StoreFront::makePayment. */ virtual void paymentTransactionSucceededEvent(const char * productID, int quantity, double timestamp, const char * transactionID, void * transactionObject) {}; /** * Transaction is failed. * * @param productID Product's ID. * @param quantity Product's quantity. * @param errorCode Error code. * @param error UTF-8 error string. * * @see StoreFront::makePayment. */ virtual void paymentTransactionFailedEvent( const char * productID, int quantity, int errorCode, const char * error ) {}; /** * Previous transaction is restored. * You must manually call StoreFront::finishTransaction to remove transaction from the queue, * when you've done processing and validating it. * * @param productID Product's ID. * @param quantity Product's quantity. * @param timestamp Original transaction's UNIX timestamp. * @param transactionID Original transaction's ID. * @param transactionObject Transaction object. * * @see StoreFront::makePayment. */ virtual void paymentTransactionRestoredEvent( const char * productID, int quantity, double timestamp, const char * transactionID, void * transactionObject ) {}; /** * Return true if the item should be consumed. * Note: this method is not called for App Store market. */ virtual bool isProductConsumable(const char * productID) { return true; }; /** * Return true if the item is a subscription. * Note: this method is not called for App Store market. */ virtual bool isSubscription(const char * productID) { return true; }; /** * Up-to-date receipt file has been returned. * * @param receiptFile Contents of receipt when receipt file was successfully requested. * @param errorCode Error code in case of any error or 0. * @param errorUTF8 Error string in UTF8 coding or empty string. */ virtual void receiptRequested(void * receiptFile, int errorCode, const char * errorUTF8) {}; }; } #endif
32.032258
164
0.667422
[ "object", "vector" ]
43a18795845e2817dbe36abc2b9e9ee9ef29435c
2,506
h
C
src/sharedLibraries/headers/LASillyInverse3MultiSelection.h
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
13
2022-01-17T16:14:26.000Z
2022-03-30T02:06:04.000Z
src/sharedLibraries/headers/LASillyInverse3MultiSelection.h
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
1
2022-01-28T23:17:14.000Z
2022-01-28T23:17:14.000Z
src/sharedLibraries/headers/LASillyInverse3MultiSelection.h
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
3
2022-01-18T02:13:53.000Z
2022-03-06T19:28:19.000Z
#ifndef SILLY_LA_INVERSE3_MULTISELECT_H #define SILLY_LA_INVERSE3_MULTISELECT_H // by Binhang, June 2017 #include "Lambda.h" #include "LambdaCreationFunctions.h" #include "LASingleMatrix.h" #include "MultiSelectionComp.h" #include "MatrixBlock.h" #include "LADimension.h" class LASillyInverse3MultiSelection : public MultiSelectionComp<MatrixBlock, SingleMatrix> { public: ENABLE_DEEP_COPY LASillyInverse3MultiSelection() {} LASillyInverse3MultiSelection(LADimension dim) : targetDim(dim) {} Lambda<bool> getSelection(Handle<SingleMatrix> checkMe) override { return makeLambda(checkMe, [](Handle<SingleMatrix>& checkMe) { return true; }); } Lambda<Vector<Handle<MatrixBlock>>> getProjection(Handle<SingleMatrix> checkMe) override { return makeLambda(checkMe, [&](Handle<SingleMatrix>& checkMe) { return this->split(checkMe); }); } private: LADimension targetDim; Vector<Handle<MatrixBlock>> split(Handle<SingleMatrix> checkMe) { MatrixBlock largeM = checkMe->getValue(); // std::cout<<"Split Function" <<std::endl; // largeM.print(); int totalRows = targetDim.blockRowSize * targetDim.blockRowNum; int totalCols = targetDim.blockColSize * targetDim.blockColNum; // std::cout<<totalRows<<", "<<totalCols<<std::endl; Vector<Handle<MatrixBlock>> result; for (int i = 0; i < targetDim.blockRowNum; i++) { for (int j = 0; j < targetDim.blockColNum; j++) { Handle<MatrixBlock> currentBlock = makeObject<MatrixBlock>( i, j, targetDim.blockRowSize, targetDim.blockColSize, totalRows, totalCols); for (int ii = 0; ii < targetDim.blockRowSize; ii++) { for (int jj = 0; jj < targetDim.blockColSize; jj++) { int finalRowIndex = i * targetDim.blockRowSize + ii; int finalColIndex = j * targetDim.blockColSize + jj; // std::cout<<"("<<finalRowIndex<<","<<finalColIndex<<")"<<endl; (*(currentBlock->getRawDataHandle()))[ii * targetDim.blockColSize + jj] = (*(largeM .getRawDataHandle()))[finalRowIndex * totalCols + finalColIndex]; } } // currentBlock->print(); result.push_back(currentBlock); } } return result; } }; #endif
38.553846
100
0.603352
[ "vector" ]
43a3764b23fd8baa5d6ddacfe085e066b800407f
2,106
c
C
crypto/ringlwe/FFT/FFT_2048_8816641.c
vscrypto/openssl-ringlwe
efeae5e1be441fdc931234068fe99deff57f6a8e
[ "OpenSSL" ]
8
2016-05-29T18:15:29.000Z
2021-04-01T08:44:41.000Z
crypto/ringlwe/FFT/FFT_2048_8816641.c
vscrypto/openssl-ringlwe
efeae5e1be441fdc931234068fe99deff57f6a8e
[ "OpenSSL" ]
null
null
null
crypto/ringlwe/FFT/FFT_2048_8816641.c
vscrypto/openssl-ringlwe
efeae5e1be441fdc931234068fe99deff57f6a8e
[ "OpenSSL" ]
2
2018-05-19T14:48:43.000Z
2019-03-13T13:53:18.000Z
/* 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. * * See LICENSE for complete information. */ /* Code to compute a Number Theoretic Transform for multiplication in the ring F_q[x] / <x^n+1>. n = 2048, q = 8816641 */ #include "FFT_includes.h" #include "FFT_constants.h" /* We use Gentleman-Sande, decimation-in-frequency FFT, for the forward FFT. Note that we will not perform the usual scambling / bit-reversal procedure here because we will invert the fourier transform using decimation-in-time. */ void FFT_forward_2048_8816641(FFTSHORT x[2048]) { const FFTSHORT n = 2048; const FFTSHORT q = 8816641; FFTSHORT index, step; FFTSHORT i,j,m; FFTSHORT t0,t1; step = 1; for (m = n>>1; m >= 1; m=m>>1) { index = 0; for (j = 0 ; j < m; ++j) { for (i = j; i < n; i += (m<<1)) { ADD_MOD(t0, x[i], x[i+m], q); ADD(t1, x[i], q - x[i+m]); MUL_MOD(x[i+m], t1, W_2048_8816641[index], q); x[i] = t0; } SUB_MODn(index, index, step, n); } step = step << 1; } } /* We use Cooley-Tukey, decimation-in-time FFT, for the inverse FFT. Note that we will not perform the usual scambling / bit-reversal procedure here because we will the forward fourier transform is using decimation-in-frequency. */ void FFT_backward_2048_8816641(FFTSHORT x[2048]) { const FFTSHORT n = 2048; const FFTSHORT q = 8816641; FFTSHORT index, step; FFTSHORT i,j,m; FFTSHORT t0,t1; step = n>>1; for (m = 1; m < n; m=m<<1) { index = 0; for (j = 0 ; j < m; ++j) { for (i = j; i < n; i += (m<<1)) { t0 = x[i]; t0 -= (t0 >= q) ? q : 0; MUL_MOD(t1, x[i+m], W_rev_2048_8816641[index], q); ADD(x[i], t0, t1); ADD(x[i+m], t0, q - t1); } SUB_MODn(index, index, step, n); } step = step >> 1; } for (i = 0; i < n; ++i) { x[i] -= (x[i] >= q) ? q : 0; } }
25.682927
107
0.604463
[ "transform" ]
43af34334625ee572581451dc2f30cf2e5032485
5,618
h
C
applications/CSharpWrapperApplication/custom_includes/model_part_wrapper.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/CSharpWrapperApplication/custom_includes/model_part_wrapper.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/CSharpWrapperApplication/custom_includes/model_part_wrapper.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// _____ _____ _ __ __ _ _ _ _ // / ____|/ ____| | \ \ / / /\ | (_) | | (_) // | | | (___ | |__ __ _ _ __ _ _\ \ /\ / / __ __ _ _ __ _ __ ___ _ __ / \ _ __ _ __ | |_ ___ __ _| |_ _ ___ _ __ // | | \___ \| '_ \ / _` | '__| '_ \ \/ \/ / '__/ _` | '_ \| '_ \ / _ \ '__/ /\ \ | '_ \| '_ \| | |/ __/ _` | __| |/ _ \| '_ | // | |____ ____) | | | | (_| | | | |_) \ /\ /| | | (_| | |_) | |_) | __/ | / ____ \| |_) | |_) | | | (_| (_| | |_| | (_) | | | | // \_____|_____/|_| |_|\__,_|_| | .__/ \/ \/ |_| \__,_| .__/| .__/ \___|_|/_/ \_\ .__/| .__/|_|_|\___\__,_|\__|_|\___/|_| |_| // | | | | | | | | | | // |_| |_| |_| |_| |_| // // // License: BSD License // license: CSharpWrapperApplication/license.txt // // Main authors: Hubert Balcerzak #ifndef KRATOSMULTIPHYSICS_MODEL_PART_WRAPPER_H #define KRATOSMULTIPHYSICS_MODEL_PART_WRAPPER_H // System includes #include <vector> // External includes // Project includes #include "includes/model_part.h" #include "id_translator.h" #include "mesh_converter.h" #include "includes/variables.h" namespace CSharpKratosWrapper { using NodeType = Kratos::Node<3>; using ElementType = Kratos::Element; using ConditionType = Kratos::Condition; using ModelPart = Kratos::ModelPart; class ModelPartWrapper { public: ModelPartWrapper(Kratos::ModelPart &mModelPart, std::vector<NodeType::Pointer> &fixedNodes) : mModelPart(mModelPart), mFixedNodes(fixedNodes), pmParentModelPart(NULL) { initialize(); } ModelPartWrapper(Kratos::ModelPart &mModelPart, std::vector<NodeType::Pointer> &fixedNodes, ModelPartWrapper *parent) : mModelPart(mModelPart), mFixedNodes(fixedNodes), pmParentModelPart(parent) { initialize(); } ~ModelPartWrapper(); ModelPartWrapper *getSubmodelPart(char *name); bool hasSubmodelPart(char *name); float *getXCoordinates(); float *getYCoordinates(); float *getZCoordinates(); int getNodesCount(); int *getTriangles(); int getTrianglesCount(); /** * Fixes and updates DISPLACEMENT variable of a node, so that final position is as given. X0 + DISPLACEMENT_X = x * @param nodeId Surface id of the node to update * @param x X coordinate * @param y Y coordinate * @param z Z coordinate */ void updateNodePos(const int nodeId, const float x, const float y, const float z); /** * Extracts new node positions and stress values */ void retrieveResults(); /** * Enables calculation of surface stress values. Call `retrieveResults` after each simulation to recalculate stress. */ void enableSurfaceStressResults(); float *getSurfaceStress(); ModelPart &getKratosModelPart(); /** * Recreates surface mesh after changes to its structure, like creation of new nodes and elements */ void recreateProcessedMesh(); ModelPartWrapper *createSubmodelPart(char *name); NodeType *createNewNode(int id, double x, double y, double z); ElementType *createNewElement(char *name, int id, int *nodeIds); ConditionType *createNew2dCondition(char *name, int id, int *nodeIds); void removeNode(int id); void removeElement(int id); void removeCondition(int id); void addNodes(int *nodeIds, int nodeCount); void addElements(int *elementIds, int elementCount); void addConditions(int *conditionIds, int elementCount); int getMaxElementId(); int getMaxNodeId(); NodeType *getNode(int id); NodeType **getNodes(); int getNumberOfNodes(); ElementType *getElement(int id); ElementType **getElements(); int getNumberOfElements(); ConditionType *getCondition(int id); ConditionType **getConditions(); int getNumberOfConditions(); IdTranslator *getIdTranslator(); double *getNodalVariable1d(Kratos::Variable<double> &variable); double *getNodalVariable3d(Kratos::Variable<Kratos::array_1d<double, 3>> &variable); bool hasNodalVariable1d(Kratos::Variable<double> &variable); bool hasNodalVariable3d(Kratos::Variable<Kratos::array_1d<double, 3>> &variable); protected: void updateMaxElementId(int maxId); void updateMaxNodeId(int maxId); private: Kratos::ModelPart &mModelPart; std::vector<NodeType::Pointer> &mFixedNodes; ModelPartWrapper *pmParentModelPart; IdTranslator idTranslator; float *pmXCoordinates; float *pmYCoordinates; float *pmZCoordinates; int *pmTriangles; int mNodesCount; int mTrianglesCount; float *pmSurfaceStress; bool mStressResultsEnabled; int mMaxElementId; int mMaxNodeId; bool mInitialized; void initialize(); void saveNodes(MeshConverter &meshConverter); void saveTriangles(MeshConverter &meshConverter); void deleteSkin(); }; }; #endif //KRATOSMULTIPHYSICS_MODEL_PART_WRAPPER_H
29.882979
133
0.56764
[ "mesh", "vector" ]
43afe43b9e070cf873fbc72fd9447231ea4ab270
13,673
c
C
c/src/core/encoder.c
alanconway/qpid-proton
8e15ea408952a00e819873c2bb90d7a922624f8a
[ "Apache-2.0" ]
null
null
null
c/src/core/encoder.c
alanconway/qpid-proton
8e15ea408952a00e819873c2bb90d7a922624f8a
[ "Apache-2.0" ]
2
2017-03-01T15:38:57.000Z
2018-09-28T13:21:34.000Z
c/src/core/encoder.c
alanconway/qpid-proton
8e15ea408952a00e819873c2bb90d7a922624f8a
[ "Apache-2.0" ]
3
2017-02-23T08:50:27.000Z
2020-05-16T00:15:00.000Z
/* * * 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. * */ #include <proton/error.h> #include <proton/object.h> #include <proton/codec.h> #include "encodings.h" #include "encoder.h" #include <string.h> #include "data.h" struct pn_encoder_t { char *output; char *position; pn_error_t *error; size_t size; unsigned null_count; }; static void pn_encoder_initialize(void *obj) { pn_encoder_t *encoder = (pn_encoder_t *) obj; encoder->output = NULL; encoder->position = NULL; encoder->error = pn_error(); encoder->size = 0; encoder->null_count = 0; } static void pn_encoder_finalize(void *obj) { pn_encoder_t *encoder = (pn_encoder_t *) obj; pn_error_free(encoder->error); } #define pn_encoder_hashcode NULL #define pn_encoder_compare NULL #define pn_encoder_inspect NULL pn_encoder_t *pn_encoder() { static const pn_class_t clazz = PN_CLASS(pn_encoder); return (pn_encoder_t *) pn_class_new(&clazz, sizeof(pn_encoder_t)); } static uint8_t pn_type2code(pn_encoder_t *encoder, pn_type_t type) { switch (type) { case PN_NULL: return PNE_NULL; case PN_BOOL: return PNE_BOOLEAN; case PN_UBYTE: return PNE_UBYTE; case PN_BYTE: return PNE_BYTE; case PN_USHORT: return PNE_USHORT; case PN_SHORT: return PNE_SHORT; case PN_UINT: return PNE_UINT; case PN_INT: return PNE_INT; case PN_CHAR: return PNE_UTF32; case PN_FLOAT: return PNE_FLOAT; case PN_LONG: return PNE_LONG; case PN_TIMESTAMP: return PNE_MS64; case PN_DOUBLE: return PNE_DOUBLE; case PN_DECIMAL32: return PNE_DECIMAL32; case PN_DECIMAL64: return PNE_DECIMAL64; case PN_DECIMAL128: return PNE_DECIMAL128; case PN_UUID: return PNE_UUID; case PN_ULONG: return PNE_ULONG; case PN_BINARY: return PNE_VBIN32; case PN_STRING: return PNE_STR32_UTF8; case PN_SYMBOL: return PNE_SYM32; case PN_LIST: return PNE_LIST32; case PN_ARRAY: return PNE_ARRAY32; case PN_MAP: return PNE_MAP32; case PN_DESCRIBED: return PNE_DESCRIPTOR; default: return pn_error_format(encoder->error, PN_ERR, "not a value type: %u\n", type); } } static uint8_t pn_node2code(pn_encoder_t *encoder, pni_node_t *node) { switch (node->atom.type) { case PN_LONG: if (-128 <= node->atom.u.as_long && node->atom.u.as_long <= 127) { return PNE_SMALLLONG; } else { return PNE_LONG; } case PN_INT: if (-128 <= node->atom.u.as_int && node->atom.u.as_int <= 127) { return PNE_SMALLINT; } else { return PNE_INT; } case PN_ULONG: if (node->atom.u.as_ulong < 256) { return PNE_SMALLULONG; } else { return PNE_ULONG; } case PN_UINT: if (node->atom.u.as_uint < 256) { return PNE_SMALLUINT; } else { return PNE_UINT; } case PN_BOOL: if (node->atom.u.as_bool) { return PNE_TRUE; } else { return PNE_FALSE; } case PN_STRING: if (node->atom.u.as_bytes.size < 256) { return PNE_STR8_UTF8; } else { return PNE_STR32_UTF8; } case PN_SYMBOL: if (node->atom.u.as_bytes.size < 256) { return PNE_SYM8; } else { return PNE_SYM32; } case PN_BINARY: if (node->atom.u.as_bytes.size < 256) { return PNE_VBIN8; } else { return PNE_VBIN32; } default: return pn_type2code(encoder, node->atom.type); } } static size_t pn_encoder_remaining(pn_encoder_t *encoder) { char * end = encoder->output + encoder->size; if (end > encoder->position) return end - encoder->position; else return 0; } static inline void pn_encoder_writef8(pn_encoder_t *encoder, uint8_t value) { if (pn_encoder_remaining(encoder)) { encoder->position[0] = value; } encoder->position++; } static inline void pn_encoder_writef16(pn_encoder_t *encoder, uint16_t value) { if (pn_encoder_remaining(encoder) >= 2) { encoder->position[0] = 0xFF & (value >> 8); encoder->position[1] = 0xFF & (value ); } encoder->position += 2; } static inline void pn_encoder_writef32(pn_encoder_t *encoder, uint32_t value) { if (pn_encoder_remaining(encoder) >= 4) { encoder->position[0] = 0xFF & (value >> 24); encoder->position[1] = 0xFF & (value >> 16); encoder->position[2] = 0xFF & (value >> 8); encoder->position[3] = 0xFF & (value ); } encoder->position += 4; } static inline void pn_encoder_writef64(pn_encoder_t *encoder, uint64_t value) { if (pn_encoder_remaining(encoder) >= 8) { encoder->position[0] = 0xFF & (value >> 56); encoder->position[1] = 0xFF & (value >> 48); encoder->position[2] = 0xFF & (value >> 40); encoder->position[3] = 0xFF & (value >> 32); encoder->position[4] = 0xFF & (value >> 24); encoder->position[5] = 0xFF & (value >> 16); encoder->position[6] = 0xFF & (value >> 8); encoder->position[7] = 0xFF & (value ); } encoder->position += 8; } static inline void pn_encoder_writef128(pn_encoder_t *encoder, char *value) { if (pn_encoder_remaining(encoder) >= 16) { memmove(encoder->position, value, 16); } encoder->position += 16; } static inline void pn_encoder_writev8(pn_encoder_t *encoder, const pn_bytes_t *value) { pn_encoder_writef8(encoder, value->size); if (pn_encoder_remaining(encoder) >= value->size) memmove(encoder->position, value->start, value->size); encoder->position += value->size; } static inline void pn_encoder_writev32(pn_encoder_t *encoder, const pn_bytes_t *value) { pn_encoder_writef32(encoder, value->size); if (pn_encoder_remaining(encoder) >= value->size) memmove(encoder->position, value->start, value->size); encoder->position += value->size; } /* True if node is an element of an array - not the descriptor. */ static bool pn_is_in_array(pn_data_t *data, pni_node_t *parent, pni_node_t *node) { return (parent && parent->atom.type == PN_ARRAY) /* In array */ && !(parent->described && !node->prev); /* Not the descriptor */ } /** True if node is the first element of an array, not the descriptor. *@pre pn_is_in_array(data, parent, node) */ static bool pn_is_first_in_array(pn_data_t *data, pni_node_t *parent, pni_node_t *node) { if (!node->prev) return !parent->described; /* First node */ return parent->described && (!pn_data_node(data, node->prev)->prev); } /** True if node is in a described list - not the descriptor. * - In this case we can omit trailing nulls */ static bool pn_is_in_described_list(pn_data_t *data, pni_node_t *parent, pni_node_t *node) { return parent && parent->atom.type == PN_LIST && parent->described; } typedef union { uint32_t i; uint32_t a[2]; uint64_t l; float f; double d; } conv_t; static int pni_encoder_enter(void *ctx, pn_data_t *data, pni_nid_t index) { pn_encoder_t *encoder = (pn_encoder_t *) ctx; pni_node_t *node = pn_data_node(data, index); pni_node_t *parent = pn_data_node(data, node->parent); pn_atom_t *atom = &node->atom; uint8_t code; conv_t c; /** In an array we don't write the code before each element, only the first. */ if (pn_is_in_array(data, parent, node)) { code = pn_type2code(encoder, parent->type); if (pn_is_first_in_array(data, parent, node)) { pn_encoder_writef8(encoder, code); } } else { code = pn_node2code(encoder, node); // Omit trailing nulls for described lists if (pn_is_in_described_list(data, parent, node)) { if (code==PNE_NULL) { encoder->null_count++; } else { // Output pending nulls, then the nodes code for (unsigned i = 0; i<encoder->null_count; i++) { pn_encoder_writef8(encoder, PNE_NULL); } encoder->null_count = 0; pn_encoder_writef8(encoder, code); } } else { pn_encoder_writef8(encoder, code); } } switch (code) { case PNE_DESCRIPTOR: case PNE_NULL: case PNE_TRUE: case PNE_FALSE: return 0; case PNE_BOOLEAN: pn_encoder_writef8(encoder, atom->u.as_bool); return 0; case PNE_UBYTE: pn_encoder_writef8(encoder, atom->u.as_ubyte); return 0; case PNE_BYTE: pn_encoder_writef8(encoder, atom->u.as_byte); return 0; case PNE_USHORT: pn_encoder_writef16(encoder, atom->u.as_ushort); return 0; case PNE_SHORT: pn_encoder_writef16(encoder, atom->u.as_short); return 0; case PNE_UINT0: return 0; case PNE_SMALLUINT: pn_encoder_writef8(encoder, atom->u.as_uint); return 0; case PNE_UINT: pn_encoder_writef32(encoder, atom->u.as_uint); return 0; case PNE_SMALLINT: pn_encoder_writef8(encoder, atom->u.as_int); return 0; case PNE_INT: pn_encoder_writef32(encoder, atom->u.as_int); return 0; case PNE_UTF32: pn_encoder_writef32(encoder, atom->u.as_char); return 0; case PNE_ULONG: pn_encoder_writef64(encoder, atom->u.as_ulong); return 0; case PNE_SMALLULONG: pn_encoder_writef8(encoder, atom->u.as_ulong); return 0; case PNE_LONG: pn_encoder_writef64(encoder, atom->u.as_long); return 0; case PNE_SMALLLONG: pn_encoder_writef8(encoder, atom->u.as_long); return 0; case PNE_MS64: pn_encoder_writef64(encoder, atom->u.as_timestamp); return 0; case PNE_FLOAT: c.f = atom->u.as_float; pn_encoder_writef32(encoder, c.i); return 0; case PNE_DOUBLE: c.d = atom->u.as_double; pn_encoder_writef64(encoder, c.l); return 0; case PNE_DECIMAL32: pn_encoder_writef32(encoder, atom->u.as_decimal32); return 0; case PNE_DECIMAL64: pn_encoder_writef64(encoder, atom->u.as_decimal64); return 0; case PNE_DECIMAL128: pn_encoder_writef128(encoder, atom->u.as_decimal128.bytes); return 0; case PNE_UUID: pn_encoder_writef128(encoder, atom->u.as_uuid.bytes); return 0; case PNE_VBIN8: pn_encoder_writev8(encoder, &atom->u.as_bytes); return 0; case PNE_VBIN32: pn_encoder_writev32(encoder, &atom->u.as_bytes); return 0; case PNE_STR8_UTF8: pn_encoder_writev8(encoder, &atom->u.as_bytes); return 0; case PNE_STR32_UTF8: pn_encoder_writev32(encoder, &atom->u.as_bytes); return 0; case PNE_SYM8: pn_encoder_writev8(encoder, &atom->u.as_bytes); return 0; case PNE_SYM32: pn_encoder_writev32(encoder, &atom->u.as_bytes); return 0; case PNE_ARRAY32: node->start = encoder->position; node->small = false; // we'll backfill the size on exit encoder->position += 4; pn_encoder_writef32(encoder, node->described ? node->children - 1 : node->children); if (node->described) pn_encoder_writef8(encoder, 0); return 0; case PNE_LIST32: case PNE_MAP32: node->start = encoder->position; node->small = false; // we'll backfill the size later encoder->position += 4; pn_encoder_writef32(encoder, node->children); return 0; default: return pn_error_format(data->error, PN_ERR, "unrecognized encoding: %u", code); } } #include <stdio.h> static int pni_encoder_exit(void *ctx, pn_data_t *data, pni_nid_t index) { pn_encoder_t *encoder = (pn_encoder_t *) ctx; pni_node_t *node = pn_data_node(data, index); char *pos; // Special case 0 length list if (node->atom.type==PN_LIST && node->children-encoder->null_count==0) { encoder->position = node->start-1; // position of list opcode pn_encoder_writef8(encoder, PNE_LIST0); encoder->null_count = 0; return 0; } switch (node->atom.type) { case PN_ARRAY: if ((node->described && node->children == 1) || (!node->described && node->children == 0)) { pn_encoder_writef8(encoder, pn_type2code(encoder, node->type)); } // Fallthrough case PN_LIST: case PN_MAP: pos = encoder->position; encoder->position = node->start; if (node->small) { // backfill size size_t size = pos - node->start - 1; pn_encoder_writef8(encoder, size); // Adjust count if (encoder->null_count) { pn_encoder_writef8(encoder, node->children-encoder->null_count); } } else { // backfill size size_t size = pos - node->start - 4; pn_encoder_writef32(encoder, size); // Adjust count if (encoder->null_count) { pn_encoder_writef32(encoder, node->children-encoder->null_count); } } encoder->position = pos; encoder->null_count = 0; return 0; default: return 0; } } ssize_t pn_encoder_encode(pn_encoder_t *encoder, pn_data_t *src, char *dst, size_t size) { encoder->output = dst; encoder->position = dst; encoder->size = size; int err = pni_data_traverse(src, pni_encoder_enter, pni_encoder_exit, encoder); if (err) return err; size_t encoded = encoder->position - encoder->output; if (encoded > size) { pn_error_format(pn_data_error(src), PN_OVERFLOW, "not enough space to encode"); return PN_OVERFLOW; } return (ssize_t)encoded; } ssize_t pn_encoder_size(pn_encoder_t *encoder, pn_data_t *src) { encoder->output = 0; encoder->position = 0; encoder->size = 0; pn_handle_t save = pn_data_point(src); int err = pni_data_traverse(src, pni_encoder_enter, pni_encoder_exit, encoder); pn_data_restore(src, save); if (err) return err; return encoder->position - encoder->output; }
32.096244
96
0.691948
[ "object" ]
43b31892554e671e5fdbcdec30a6e0128abe6fa5
1,119
h
C
include/cpu_sampler.h
giorgiozoppi/processmonitor
65a52df8a2eac9da64d6bae66dd49337bc94330a
[ "MIT" ]
null
null
null
include/cpu_sampler.h
giorgiozoppi/processmonitor
65a52df8a2eac9da64d6bae66dd49337bc94330a
[ "MIT" ]
null
null
null
include/cpu_sampler.h
giorgiozoppi/processmonitor
65a52df8a2eac9da64d6bae66dd49337bc94330a
[ "MIT" ]
null
null
null
#ifndef CPU_SAMPLER_H #define CPU_SAMPLER_H #include <functional> #include <string> namespace LinuxParser { /** * @brief This class cpuSampler has the single responsiblity to * sample the cpu over ksamples, each every 100ms and return the median. * This is pretty useful for having a better cpu utilization. * */ class CPUSampler final { public: /** * @brief Construct a new cpu Sampler object * * @param samples number of samples for cpu usage. * @param func callback for the results. */ CPUSampler(int samples, const std::function<void(float)> &func); /** * @brief start the sampling when it is finished will call back the function. * */ void Sample(); /** * @brief Sampling time * */ static constexpr int SAMPLING_TIME_MS{100}; private: // load data float LoadData() const; // convert the /proc/stat counter in vector of values std::vector<int> Split(const std::string &input) const; // number of samples int samples_; // callback std::function<void(float)> update_; }; } // namespace LinuxParser #endif
24.866667
80
0.665773
[ "object", "vector" ]
43bc28c296e2c8d77ca7488f5e64ab34dfb8a303
4,043
h
C
dbbrain/include/tencentcloud/dbbrain/v20191016/model/DescribeDBSpaceStatusResponse.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
dbbrain/include/tencentcloud/dbbrain/v20191016/model/DescribeDBSpaceStatusResponse.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
dbbrain/include/tencentcloud/dbbrain/v20191016/model/DescribeDBSpaceStatusResponse.h
TencentCloud/tencentcloud-sdk-cpp-intl-en
752c031f5ad2c96868183c5931eae3a42dd5ae6c
[ "Apache-2.0" ]
null
null
null
/* * 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_DBBRAIN_V20191016_MODEL_DESCRIBEDBSPACESTATUSRESPONSE_H_ #define TENCENTCLOUD_DBBRAIN_V20191016_MODEL_DESCRIBEDBSPACESTATUSRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Dbbrain { namespace V20191016 { namespace Model { /** * DescribeDBSpaceStatus response structure. */ class DescribeDBSpaceStatusResponse : public AbstractModel { public: DescribeDBSpaceStatusResponse(); ~DescribeDBSpaceStatusResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; /** * 获取Disk usage growth in MB. * @return Growth Disk usage growth in MB. */ int64_t GetGrowth() const; /** * 判断参数 Growth 是否已赋值 * @return Growth 是否已赋值 */ bool GrowthHasBeenSet() const; /** * 获取Available disk space in MB. * @return Remain Available disk space in MB. */ int64_t GetRemain() const; /** * 判断参数 Remain 是否已赋值 * @return Remain 是否已赋值 */ bool RemainHasBeenSet() const; /** * 获取Total disk space in MB. * @return Total Total disk space in MB. */ int64_t GetTotal() const; /** * 判断参数 Total 是否已赋值 * @return Total 是否已赋值 */ bool TotalHasBeenSet() const; /** * 获取Estimated number of available days. * @return AvailableDays Estimated number of available days. */ int64_t GetAvailableDays() const; /** * 判断参数 AvailableDays 是否已赋值 * @return AvailableDays 是否已赋值 */ bool AvailableDaysHasBeenSet() const; private: /** * Disk usage growth in MB. */ int64_t m_growth; bool m_growthHasBeenSet; /** * Available disk space in MB. */ int64_t m_remain; bool m_remainHasBeenSet; /** * Total disk space in MB. */ int64_t m_total; bool m_totalHasBeenSet; /** * Estimated number of available days. */ int64_t m_availableDays; bool m_availableDaysHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_DBBRAIN_V20191016_MODEL_DESCRIBEDBSPACESTATUSRESPONSE_H_
31.834646
83
0.473906
[ "vector", "model" ]
43c1adf6c5d0f78d4fa7fae98a5df00493357c35
2,798
h
C
third_party/blink/renderer/core/css/cssom/css_scale.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
190
2017-09-06T19:55:48.000Z
2022-02-11T22:26:29.000Z
third_party/blink/renderer/core/css/cssom/css_scale.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
30
2017-10-02T09:26:11.000Z
2021-06-05T22:06:34.000Z
third_party/blink/renderer/core/css/cssom/css_scale.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
27
2017-09-14T11:46:01.000Z
2022-03-23T09:00:53.000Z
// Copyright 2016 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 THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_SCALE_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_SCALE_H_ #include "base/macros.h" #include "third_party/blink/renderer/core/css/cssom/css_transform_component.h" #include "third_party/blink/renderer/core/css/cssom/css_unit_value.h" #include "third_party/blink/renderer/core/geometry/dom_matrix.h" namespace blink { class CSSNumericValue; class DOMMatrix; // Represents a scale value in a CSSTransformValue used for properties like // "transform". // See CSSScale.idl for more information about this class. class CORE_EXPORT CSSScale final : public CSSTransformComponent { DEFINE_WRAPPERTYPEINFO(); public: // Constructors defined in the IDL. static CSSScale* Create(const CSSNumberish&, const CSSNumberish&, ExceptionState&); static CSSScale* Create(const CSSNumberish&, const CSSNumberish&, const CSSNumberish&, ExceptionState&); // Blink-internal ways of creating CSSScales. static CSSScale* Create(CSSNumericValue* x, CSSNumericValue* y) { return MakeGarbageCollected<CSSScale>(x, y, CSSUnitValue::Create(1), true /* is2D */); } static CSSScale* Create(CSSNumericValue* x, CSSNumericValue* y, CSSNumericValue* z) { return MakeGarbageCollected<CSSScale>(x, y, z, false /* is2D */); } static CSSScale* FromCSSValue(const CSSFunctionValue&); CSSScale(CSSNumericValue* x, CSSNumericValue* y, CSSNumericValue* z, bool is2D); // Getters and setters for attributes defined in the IDL. void x(CSSNumberish& x) { x.SetCSSNumericValue(x_); } void y(CSSNumberish& y) { y.SetCSSNumericValue(y_); } void z(CSSNumberish& z) { z.SetCSSNumericValue(z_); } void setX(const CSSNumberish&, ExceptionState&); void setY(const CSSNumberish&, ExceptionState&); void setZ(const CSSNumberish&, ExceptionState&); DOMMatrix* toMatrix(ExceptionState&) const final; // Internal methods - from CSSTransformComponent. TransformComponentType GetType() const final { return kScaleType; } const CSSFunctionValue* ToCSSValue() const final; void Trace(Visitor* visitor) override { visitor->Trace(x_); visitor->Trace(y_); visitor->Trace(z_); CSSTransformComponent::Trace(visitor); } private: Member<CSSNumericValue> x_; Member<CSSNumericValue> y_; Member<CSSNumericValue> z_; DISALLOW_COPY_AND_ASSIGN(CSSScale); }; } // namespace blink #endif
33.710843
78
0.691923
[ "geometry", "transform" ]
43c7102c822abdca437b95ff128fb06acd43503e
18,140
h
C
copasi/model/CReaction.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/model/CReaction.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/model/CReaction.h
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CReaction class. * Derived from Gepasi's cstep.cpp. (C) Pedro Mendes 1995-2000. * * Converted for COPASI by Stefan Hoops 2001 */ #ifndef COPASI_CReaction #define COPASI_CReaction #include <string> #include <vector> #include "copasi/model/CAnnotation.h" #include "copasi/model/CMetab.h" #include "copasi/model/CChemEq.h" #include "copasi/model/CChemEqElement.h" #include "copasi/model/CCompartment.h" #include "copasi/utilities/CCopasiVector.h" #include "copasi/utilities/CCopasiParameterGroup.h" #include "copasi/function/CFunction.h" #include "copasi/function/CCallParameters.h" #include "copasi/function/CFunctionParameters.h" class CReadConfig; class SBase; class CFunctionDB; class CReaction : public CCopasiContainer, public CAnnotation { public: /** * Default constructor * @param const std::string & name (default: "NoName") * @param const CCopasiContainer * pParent (default: NULL) */ CReaction(const std::string & name = "NoName", const CCopasiContainer * pParent = NULL); /** * Copy constructor * @param "const CReaction &" src * @param const CCopasiContainer * pParent (default: NULL) */ CReaction(const CReaction & src, const CCopasiContainer * pParent = NULL); private: CReaction & operator= (const CReaction &); public: /** * Destructor */ virtual ~CReaction(); /** * Retrieve the units of the child object. * @return std::string units */ virtual std::string getChildObjectUnits(const CCopasiObject * pObject) const; /** * Delete */ void cleanup(); /** * Overload display name. Special treatment for reaction to * provide a shorter display */ virtual std::string getObjectDisplayName(bool regular = true, bool richtext = false) const; /** * Loads an object with data coming from a CReadConfig object. * (CReadConfig object reads an input stream) * @param pconfigbuffer reference to a CReadConfig object. * @return mFail * @see mFail */ C_INT32 load(CReadConfig & configbuffer); /** * Sets the parent of the metabolite; * @param const CCopasiContainer * pParent * @return bool success */ virtual bool setObjectParent(const CCopasiContainer * pParent); /** * Retrieve the list of deleted numeric child objects; * @return std::set< const CCopasiObject * > deletedObjects */ virtual std::set< const CCopasiObject * > getDeletedObjects() const; /** * Check whether an object must be deleted because its prerequisites can * no longer be fulfilled due to the given deleted objects * @param const DataObjectSet & deletedObjects * @return bool mustBeDeleted */ virtual bool mustBeDeleted(const DataObjectSet & deletedObjects) const; /** * Retrieves the key of the reaction * @return std::string key */ virtual const std::string & getKey() const; /** * Retrieves the chemical equation of the reaction * @return const CChemEq & chemEq */ const CChemEq & getChemEq() const; /** * Retrieves the chemical equation of the reaction * @return CChemEq & chemEq */ CChemEq & getChemEq(); /** * Retrieves the rate function of the reaction * @return "CBaseFunction &" */ const CFunction * getFunction() const; /** * Retrieves the flux of the reaction * @return const C_FLOAT64 & flux */ const C_FLOAT64 & getFlux() const; /** * Retrieves the scaled flux of the reaction * @return const C_FLOAT64 & scaledFlux */ const C_FLOAT64 & getParticleFlux() const; /** * Retrieves whether the reaction is reversible * @return bool */ bool isReversible() const; /** * Add a substrate to the reaction * @param std::string & metabKey * @param const C_FLOAT64 & multiplicity (Default 1.0) * @return bool success */ bool addSubstrate(const std::string & metabKey, const C_FLOAT64 & multiplicity = 1.0); /** * Add a product to the reaction * @param std::string & metabKey * @param const C_FLOAT64 & multiplicity (Default 1.0) * @return bool success */ bool addProduct(const std::string & metabKey, const C_FLOAT64 & multiplicity = 1.0); /** * Add a modifier to the reaction * @param std::string & metabKey * @param const C_FLOAT64 & multiplicity (Default 1.0) * @return bool success */ bool addModifier(const std::string & metabKey, const C_FLOAT64 & multiplicity = 1.0); /** * Sets the rate function of the reaction * @param const string & functionName * @return bool success */ bool setFunction(const std::string & functionName); /** * Sets the rate function of the reaction * @param CFunction * pFunction * @return bool success */ bool setFunction(CFunction * pFunction); //**************************************************************************************** /** * Retrieve the index of the given parameter name in the function call. If pType is not * NULL the type of the parameter is returned * @param const std::string & parameterName * @param CFunctionParameter::DataType * pType (default: NULL) * @return size_t index; */ size_t getParameterIndex(const std::string & parameterName, CFunctionParameter::DataType * pType = NULL) const; /** * Sets a parameter value * if updateStatus==true the status is also updated to make sure * the value is actually used (instead of a global value that may * have been used before). * if updateStatus==false only the value of the local parameter is * set, even if it is not used * @param const std::string & parameterName * @param const C_FLOAT64 & value * @param const bool & updateStatus (default: true( */ void setParameterValue(const std::string & parameterName, const C_FLOAT64 & value, const bool & updateStatus = true); /** * Retrieves a parameter value */ const C_FLOAT64 & getParameterValue(const std::string & parameterName) const; /** * Sets a parameter mapping for the indexed parameter. * @param const size_t & index * @param const std::string & key */ void setParameterMapping(const size_t & index, const std::string & key); /** * Add a parameter mapping for the indexed parameter. * @param const size_t & index * @param const std::string & key */ void addParameterMapping(const size_t & index, const std::string & key); /** * Sets a parameter mapping for the named parameter. * @param const std::string & parameterName * @param const std::string & key * @return bool success */ bool setParameterMapping(const std::string & parameterName, const std::string & key); /** * Add a parameter mapping for the named parameter. * @param const std::string & parameterName * @param const std::string & key */ void addParameterMapping(const std::string & parameterName, const std::string & key); /** * Set the mapping for the name parameter which must be of type vector * @param const std::string & parameterName * @param const std::vector<std::string> & keys */ void setParameterMappingVector(const std::string & parameterName, const std::vector<std::string> & keys); /** * Clear the parameter mapping for the named parameter. * @param const size_t & index */ void clearParameterMapping(const std::string & parameterName); /** * Clear the parameter mapping for the indexed parameter. * @param const size_t & index */ void clearParameterMapping(const size_t & index); /** * Retrieve the mappings of kinetic function parameters. */ const std::vector< std::vector<std::string> > & getParameterMappings() const {return mMetabKeyMap;} std::vector< std::vector<std::string> > & getParameterMappings() {return mMetabKeyMap;} const std::vector<std::string> & getParameterMapping(const size_t & index) const; const std::vector<std::string> & getParameterMapping(const std::string & parameterName) const; /** * Gets the list of kinetic parameter objects of the reaction/function */ const CCopasiParameterGroup & getParameters() const; /** * Gets the list of kinetic parameter objects of the reaction/function */ CCopasiParameterGroup & getParameters(); /** * Check whether the indexed parameter is a local parameter. * @param const size_t & index * @return bool isLocal */ bool isLocalParameter(const size_t & index) const; /** * Check whether the named parameter is a local parameter. * @param const std::string & parameterName * @return bool isLocal */ bool isLocalParameter(const std::string & parameterName) const; /** * We are hiding local reaction parameter which are covered by global quantities. * @param const CCopasiObjectName & cn * @return const CObjectInterface * pObject */ virtual const CObjectInterface * getObject(const CCopasiObjectName & cn) const; /** * Gets the description of what parameters the function expects. */ const CFunctionParameters & getFunctionParameters() const; /** * Sets whether the reaction is reversible * @param bool reversible */ void setReversible(bool reversible); /** * Compile the reaction, i.e., links the metabolites and parameters with the * rate function. The connection of the reaction and the function parameter mapping * to the actual metabolites is established (before compile() the chemical equation * and the reaction only hold the names of the metabolites). * @param "CCopasiVectorNS < CCompartment > &" compartments */ void compile(); /** * Calculate the kinetic function and returns the flux * @return const C_FLOAT64 & Flux */ const C_FLOAT64 & calculateFlux(); /** * Calculates the kinetic function and returns the particle flux * @return const C_FLOAT64 & ParticleFlux */ const C_FLOAT64 & calculateParticleFlux(); /** * Retrieve object referencing the particle flux * @return CCopasiObject * particleFluxReference */ CCopasiObject * getParticleFluxReference(); /** * Retrieve const object referencing the particle flux * @return CCopasiObject * particleFluxReference */ const CCopasiObject * getParticleFluxReference() const; /** * Retrieve object referencing the flux * @return CCopasiObject * fluxReference */ CCopasiObject * getFluxReference(); /** * Retrieve const object referencing the flux * @return CCopasiObject * fluxReference */ const CCopasiObject * getFluxReference() const; /** * Retrieve object referencing the propensity * @return CCopasiObject * propensityReference */ CCopasiObject * getPropensityReference(); /** * Retrieve object referencing the propensity * @return CCopasiObject * propensityReference */ const CCopasiObject * getPropensityReference() const; /** * Retrieve the call parameter given to the kinetic function. * @return const CCallParameters< C_FLOAT64 > & callParameters */ const CCallParameters< C_FLOAT64 > & getCallParameters() const; private: /** * Calculate the kinetic function */ void calculate(); public: /** * Calculate partial derivative of the flux * @param C_FLOAT64 * pXi * @param const C_FLOAT64 & derivationFactor * @param const C_FLOAT64 & resolution (unscaled resolution) * @return C_FLOAT64 partial */ C_FLOAT64 calculatePartialDerivative(C_FLOAT64 * pXi, const C_FLOAT64 & derivationFactor, const C_FLOAT64 & resolution); /** * Retrieves the number of compartments the reaction is acting in. * @return "size_t" the compartment number */ size_t getCompartmentNumber() const; /** * Retrieve the largest compartment that the reaction touches. * This is time dependent it can only be called after update initial values * has been called. Note for an empty reaction a NULL pointer is returned. * @return const CCompartment * pCompartment */ const CCompartment * getLargestCompartment() const; /** * Converts an expression tree into a CFunction object * and sets the mapping for the reaction. */ CFunction * setFunctionFromExpressionTree(const CExpression & tree, std::map<CCopasiObject*, SBase*> & copasi2sbmlmap, CFunctionDB* pFunctionDB); /** * Converts the function tree into the corresponding expression tree. * All variable nodes are replaced by object nodes. */ CEvaluationNode* getExpressionTree(); /** * Sets the SBMLId. */ void setSBMLId(const std::string& id); /** * Returns a reference to the SBML Id. */ const std::string& getSBMLId() const; /** * Friend declaration for ostream operator * @param std::ostream & os * @param const CReaction & d * @return std::ostream & os */ friend std::ostream & operator<<(std::ostream & os, const CReaction & d); void printDebug() const; /** * Set whether the reaction is to be treated as fast * @param const bool & fast */ void setFast(const bool & fast); /** * Check whether the reaction needs to be treated as fast * @ return const bool & fast */ const bool & isFast() const; private: /** * Loads a reaction from a Gepasi file */ C_INT32 loadOld(CReadConfig & configbuffer); /** * Used for loading Gepasi files. Loads the mapping for one role */ bool loadOneRole(CReadConfig & configbuffer, CFunctionParameter::Role role, C_INT32 n, const std::string & prefix); /** * Sets the scaling factor of the for the fluxes */ void setScalingFactor(); void initObjects(); /** * creates the mParamters List of CParameter objects. * mMap needs to be initialized before. */ void initializeParameters(); /** * Initializes the mMetabNameMap vectors to the right size. */ void initializeMetaboliteKeyMap(); /** * Replaces all object nodes in an expression tree by variable nodes. * The usage term of the variable nodes is recorded in terms * of CFunctionParameters that are stored in the replacementMap. * On failure a NULL pointer is returned. */ CEvaluationNode* objects2variables(const CEvaluationNode* expression, std::map<std::string, std::pair<CCopasiObject*, CFunctionParameter*> >& replacementMap, std::map<CCopasiObject*, SBase*>& copasi2sbmlmap); /** * Converts a single object node to a variable node. * The usage term of the variable nodes is recorded in terms * of CFunctionParameters that are stored in the replacementMap. * On failure a NULL pointer is returned. */ CEvaluationNodeVariable* object2variable(const CEvaluationNodeObject* objectNode, std::map<std::string, std::pair<CCopasiObject*, CFunctionParameter*> >& replacementMap, std::map<CCopasiObject*, SBase*>& copasi2sbmlmap); /** * Replaces all variable nodes in a function tree by object nodes. * On failure a NULL pointer is returned. */ CEvaluationNode* variables2objects(CEvaluationNode* expression); /** * Converts a single variable node to an object node. * On failure a NULL pointer is returned. */ CEvaluationNodeObject* variable2object(CEvaluationNodeVariable* pVariableNode); /** * Escapes double quotes and backslashes in a string and puts strings with * tabs and spaces in double quotes. */ std::string escapeId(const std::string& id); // Attributes private: /** * The default scaling factor of a reaction which is 1. */ static C_FLOAT64 mDefaultScalingFactor; /** * The chemical equation */ CChemEq mChemEq; /** * A pointer to the rate function of the reaction */ CFunction * mpFunction; /** * The flux of the reaction, as amount of substance/time */ C_FLOAT64 mFlux; CCopasiObjectReference<C_FLOAT64> *mpFluxReference; /** * The scaled flux of the reaction, as particle number/time */ C_FLOAT64 mParticleFlux; CCopasiObjectReference<C_FLOAT64> *mpParticleFluxReference; /** * The propensity of the reaction */ C_FLOAT64 mPropensity; CCopasiObjectReference<C_FLOAT64> *mpPropensityReference; /** * A pointer to the scaling factor for the flux to calculate the particle number * changes. For a single compartment reaction this is the volume of * the compartment */ const C_FLOAT64 * mScalingFactor; /** * The unit conversion factor */ const C_FLOAT64 * mUnitScalingFactor; /** * This describes the mapping of the species and parameters to the function parameters. * Here are the pointers to the actual objects and values. */ CFunctionParameterMap mMap; /** * This describes the mapping of the species to the function parameters. Here the * keys of the metabolites (as in the chemical equation) are stored. */ std::vector< std::vector< std::string > > mMetabKeyMap; /** * This is a list of parameter objects. */ CCopasiParameterGroup mParameters; /** * The id of the corresponding reaction in an SBML file. * This value is either set upon importing an SBML file, * or when the object is first exported to an SBML file. */ std::string mSBMLId; /** * This flag indicates whether the reaction is treated as fast. The interpretation of fast * is up to to the integration algorithm. */ bool mFast; }; #endif // COPASI_CReaction
28.931419
124
0.67839
[ "object", "vector", "model" ]
43ca1199915c0c529fbba85a1622e8e1d87ce9d9
2,670
h
C
lib/location/libpmel/pmel.h
jreyes1108/antelope_contrib
be2354605d8463d6067029eb16464a0bf432a41b
[ "BSD-2-Clause", "MIT" ]
30
2015-02-20T21:44:29.000Z
2021-09-27T02:53:14.000Z
lib/location/libpmel/pmel.h
jreyes1108/antelope_contrib
be2354605d8463d6067029eb16464a0bf432a41b
[ "BSD-2-Clause", "MIT" ]
14
2015-07-07T19:17:24.000Z
2020-12-19T19:18:53.000Z
lib/location/libpmel/pmel.h
jreyes1108/antelope_contrib
be2354605d8463d6067029eb16464a0bf432a41b
[ "BSD-2-Clause", "MIT" ]
46
2015-02-06T16:22:41.000Z
2022-03-30T11:46:37.000Z
#ifndef _GENLOC_PMEL_H_ #define _GENLOC_PMEL_H_ /* This structure definition should ultimately end up in location.h I put it here only temporarily */ /* This structure is used to define an indexed matrix that is called S in the original PMEL paper. The S matrix has nrow rows (normally this is ndata-4*nevents) and ncol columns. The two associative arrays, phase_index and sta_index, are used to index the columns through a double indexing scheme. The S matrix should be thought of as partitioned by columns into nphases submatrices, one for each seismic phase to solve for. phase_index contains the column index for the first element of the matrix for each named phase. Within the submatrix the RELATIVE position of the column associated with a given station is obtained from the sta_index array. e.g. if we wanted phase S for station AAK and we found the phase index was 25 and the station index was 4 we would know that 25+4 was the column position for this station:phase. */ typedef struct scmatrix { Arr *phase_index; /* Contains integer index for phase */ Arr *sta_index; /* Same for station names. */ int nphases; int nsta; int nrow,ncol; /* ncol=nsta*nphases, but we keep it anyway*/ double rmsraw,sswrodgf; int ndgf; double *scref; /* Vector of length ncol of reference station corrections (used for bias correction projectors)*/ double *sc; /* Holds a current estimate of path anomalies */ double *scbias,*scdata; /* components of sc derived from sref and data respectively */ double *S; } SCMatrix; enum FREEZE_METHOD {DEPTH_MAXARRIVALS, ALLSPACE_MAXARRIVALS, ALL_MAXARRIVALS, DEPTH_MINRMS, ALLSPACE_MINRMS, ALL_MINRMS, NOTSET }; #ifdef __cplusplus extern "C" { #endif char *make_evid_key(long); Arr *load_calibration_events(Pf *); char *get_fixlist(Arr *,long); int in_fixdepthlist(Arr *a, long *evid, int nev); Arr *get_freezearr(enum FREEZE_METHOD fm, Hypocenter *h, long *evid, Tbl **ta, int nev); Arr *parse_3D_phase(Pf *); void edit_phase_handle(Arr *,Tbl *); int pmel(int, long *, Tbl **, Hypocenter *,Arr *,Hypocenter *, SCMatrix *,Arr *,Location_options *, Pf *, Tbl **, Tbl **); Arr *create_sta_index(Arr *); SCMatrix *create_SCMatrix(Arr *,Arr *); void destroy_SCMatrix(SCMatrix *); void clear_station_corrections(Arr *); int initialize_station_corrections(Arr *, Arr *, Arr *, Hypocenter *); int compute_scref(SCMatrix *, Hypocenter *, Arr *, Arr *, Arr *); int update_scarr(SCMatrix *,Arr *); Arr *pmel_dbload_stations(Dbptr db,Pf *); #ifdef __cplusplus } #endif #endif
42.380952
78
0.712734
[ "vector" ]
43ccb181ebb81d3de3d08386f178f42e55f26f90
3,631
h
C
ext/yices/src/io/tracer.h
maelvls/ocamlyices2
554893d467a4bf3e9b0b630833b417348b15e771
[ "0BSD" ]
2
2017-04-05T13:53:54.000Z
2018-11-23T00:16:01.000Z
ext/yices/src/io/tracer.h
maelvls/ocamlyices2
554893d467a4bf3e9b0b630833b417348b15e771
[ "0BSD" ]
5
2017-04-07T14:29:10.000Z
2021-01-08T18:01:46.000Z
ext/yices/src/io/tracer.h
maelvls/ocamlyices2
554893d467a4bf3e9b0b630833b417348b15e771
[ "0BSD" ]
1
2017-04-05T16:58:14.000Z
2017-04-05T16:58:14.000Z
/* * The Yices SMT Solver. Copyright 2014 SRI International. * * This program may only be used subject to the noncommercial end user * license agreement which is downloadable along with this program. */ /* * Support for printing trace/messages depending on a verbosity level. */ #ifndef __TRACER_H #define __TRACER_H #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include "io/yices_pp.h" #include "terms/terms.h" #include "terms/types.h" /* * Tracer structure: * - an open FILE * + an optional pretty printing object * + a verbosity level (higher means more verbose) * + error codes if printing fails */ typedef struct tracer_s { FILE *file; yices_pp_t *pp; uint32_t vlevel; bool print_failed; // true if printing fails int err_code; // copy of errno when failure was reported pvector_t trace_tags; // list of tags } tracer_t; /* * Initialize to defaults */ static inline void init_trace(tracer_t *tracer) { tracer->file = stderr; tracer->pp = NULL; tracer->vlevel = 0; tracer->print_failed = false; tracer->err_code = 0; init_pvector(&tracer->trace_tags, 5); } /* * Set verbosity level */ static inline void set_trace_vlevel(tracer_t *tracer, uint32_t level) { tracer->vlevel = level; } /* * Enable a tag to trace. */ static inline void enable_trace_tag(tracer_t *tracer, const char* tag) { pvector_push(&tracer->trace_tags, strdup(tag)); } /* * Check whether the verbosity level is at least lvl * - return false if trace is NULL */ static inline bool tracing(tracer_t *tracer, uint32_t lvl) { return tracer != NULL && tracer->vlevel >= lvl; } /* * Check whether the tracing tag has been enabled. * - return false if trace is NULL; */ bool tracing_tag(tracer_t *tracer, const char *tag); /* * Change output file: * - f must be open and writable * - close the current file if it's not stderr * - reset the print_failed and err_code flags * - also close and delete the tracer->pp object if there is one */ extern void set_trace_file(tracer_t *tracer, FILE *f); /* * Close/delete the tracer * - close the current file if it's not stderr * - close and delete the pp object if any */ extern void delete_trace(tracer_t *tracer); /* * Output functions: * - if tracer is NULL, they do nothing * - otherwise, they print stuff to tracer->file provided * tracer->vlevel >= level * - both tprintf and tputs call fflush * * - if the output fails then tracer->print_failed is set to true * and tracer->err_code is set to errno */ /* * Formatted output (as in fprintf) * - level = verbosity * - fmt = a format string as in printf * - rest = stuff to print (as in prinf too) */ extern void tprintf(tracer_t *tracer, uint32_t level, const char *format, ...) __attribute__ ((format (printf, 3, 4))); /* * Print string s if tracer->vlevel >= level * (same as fputs) */ extern void tputs(tracer_t *tracer, uint32_t level, const char *s); /* * Newline */ extern void tnewline(tracer_t *trace, uint32_t level); /* * Pretty printing: * - the tracer->pp object is created and initialized on the * first call to one of these functions (provided tracer->vlevel >= level) */ /* * Pretty printing of term t + newline * - tbl = corresponding term table * - use the default printing area */ extern void tpp_term(tracer_t *trace, uint32_t level, term_table_t *tbl, term_t t); /* * Pretty printing of type tau + newline * - tbl = corresponding type table * - use the default printing area */ extern void tpp_type(tracer_t *traced, uint32_t level, type_table_t *tbl, type_t tau); #endif /* __TRACER_H */
23.577922
86
0.69485
[ "object" ]
43cfee4436547c203d79efae0e811a3fc9799b15
11,052
h
C
aws-cpp-sdk-iot/include/aws/iot/model/StreamInfo.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-iot/include/aws/iot/model/StreamInfo.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-iot/include/aws/iot/model/StreamInfo.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "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/iot/IoT_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/DateTime.h> #include <aws/iot/model/StreamFile.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace IoT { namespace Model { /** * <p>Information about a stream.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/iot-2015-05-28/StreamInfo">AWS API * Reference</a></p> */ class AWS_IOT_API StreamInfo { public: StreamInfo(); StreamInfo(Aws::Utils::Json::JsonView jsonValue); StreamInfo& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The stream ID.</p> */ inline const Aws::String& GetStreamId() const{ return m_streamId; } /** * <p>The stream ID.</p> */ inline bool StreamIdHasBeenSet() const { return m_streamIdHasBeenSet; } /** * <p>The stream ID.</p> */ inline void SetStreamId(const Aws::String& value) { m_streamIdHasBeenSet = true; m_streamId = value; } /** * <p>The stream ID.</p> */ inline void SetStreamId(Aws::String&& value) { m_streamIdHasBeenSet = true; m_streamId = std::move(value); } /** * <p>The stream ID.</p> */ inline void SetStreamId(const char* value) { m_streamIdHasBeenSet = true; m_streamId.assign(value); } /** * <p>The stream ID.</p> */ inline StreamInfo& WithStreamId(const Aws::String& value) { SetStreamId(value); return *this;} /** * <p>The stream ID.</p> */ inline StreamInfo& WithStreamId(Aws::String&& value) { SetStreamId(std::move(value)); return *this;} /** * <p>The stream ID.</p> */ inline StreamInfo& WithStreamId(const char* value) { SetStreamId(value); return *this;} /** * <p>The stream ARN.</p> */ inline const Aws::String& GetStreamArn() const{ return m_streamArn; } /** * <p>The stream ARN.</p> */ inline bool StreamArnHasBeenSet() const { return m_streamArnHasBeenSet; } /** * <p>The stream ARN.</p> */ inline void SetStreamArn(const Aws::String& value) { m_streamArnHasBeenSet = true; m_streamArn = value; } /** * <p>The stream ARN.</p> */ inline void SetStreamArn(Aws::String&& value) { m_streamArnHasBeenSet = true; m_streamArn = std::move(value); } /** * <p>The stream ARN.</p> */ inline void SetStreamArn(const char* value) { m_streamArnHasBeenSet = true; m_streamArn.assign(value); } /** * <p>The stream ARN.</p> */ inline StreamInfo& WithStreamArn(const Aws::String& value) { SetStreamArn(value); return *this;} /** * <p>The stream ARN.</p> */ inline StreamInfo& WithStreamArn(Aws::String&& value) { SetStreamArn(std::move(value)); return *this;} /** * <p>The stream ARN.</p> */ inline StreamInfo& WithStreamArn(const char* value) { SetStreamArn(value); return *this;} /** * <p>The stream version.</p> */ inline int GetStreamVersion() const{ return m_streamVersion; } /** * <p>The stream version.</p> */ inline bool StreamVersionHasBeenSet() const { return m_streamVersionHasBeenSet; } /** * <p>The stream version.</p> */ inline void SetStreamVersion(int value) { m_streamVersionHasBeenSet = true; m_streamVersion = value; } /** * <p>The stream version.</p> */ inline StreamInfo& WithStreamVersion(int value) { SetStreamVersion(value); return *this;} /** * <p>The description of the stream.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The description of the stream.</p> */ inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } /** * <p>The description of the stream.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>The description of the stream.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>The description of the stream.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>The description of the stream.</p> */ inline StreamInfo& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The description of the stream.</p> */ inline StreamInfo& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The description of the stream.</p> */ inline StreamInfo& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>The files to stream.</p> */ inline const Aws::Vector<StreamFile>& GetFiles() const{ return m_files; } /** * <p>The files to stream.</p> */ inline bool FilesHasBeenSet() const { return m_filesHasBeenSet; } /** * <p>The files to stream.</p> */ inline void SetFiles(const Aws::Vector<StreamFile>& value) { m_filesHasBeenSet = true; m_files = value; } /** * <p>The files to stream.</p> */ inline void SetFiles(Aws::Vector<StreamFile>&& value) { m_filesHasBeenSet = true; m_files = std::move(value); } /** * <p>The files to stream.</p> */ inline StreamInfo& WithFiles(const Aws::Vector<StreamFile>& value) { SetFiles(value); return *this;} /** * <p>The files to stream.</p> */ inline StreamInfo& WithFiles(Aws::Vector<StreamFile>&& value) { SetFiles(std::move(value)); return *this;} /** * <p>The files to stream.</p> */ inline StreamInfo& AddFiles(const StreamFile& value) { m_filesHasBeenSet = true; m_files.push_back(value); return *this; } /** * <p>The files to stream.</p> */ inline StreamInfo& AddFiles(StreamFile&& value) { m_filesHasBeenSet = true; m_files.push_back(std::move(value)); return *this; } /** * <p>The date when the stream was created.</p> */ inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; } /** * <p>The date when the stream was created.</p> */ inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; } /** * <p>The date when the stream was created.</p> */ inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; } /** * <p>The date when the stream was created.</p> */ inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); } /** * <p>The date when the stream was created.</p> */ inline StreamInfo& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;} /** * <p>The date when the stream was created.</p> */ inline StreamInfo& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;} /** * <p>The date when the stream was last updated.</p> */ inline const Aws::Utils::DateTime& GetLastUpdatedAt() const{ return m_lastUpdatedAt; } /** * <p>The date when the stream was last updated.</p> */ inline bool LastUpdatedAtHasBeenSet() const { return m_lastUpdatedAtHasBeenSet; } /** * <p>The date when the stream was last updated.</p> */ inline void SetLastUpdatedAt(const Aws::Utils::DateTime& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = value; } /** * <p>The date when the stream was last updated.</p> */ inline void SetLastUpdatedAt(Aws::Utils::DateTime&& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = std::move(value); } /** * <p>The date when the stream was last updated.</p> */ inline StreamInfo& WithLastUpdatedAt(const Aws::Utils::DateTime& value) { SetLastUpdatedAt(value); return *this;} /** * <p>The date when the stream was last updated.</p> */ inline StreamInfo& WithLastUpdatedAt(Aws::Utils::DateTime&& value) { SetLastUpdatedAt(std::move(value)); return *this;} /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline const Aws::String& GetRoleArn() const{ return m_roleArn; } /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline bool RoleArnHasBeenSet() const { return m_roleArnHasBeenSet; } /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline void SetRoleArn(const Aws::String& value) { m_roleArnHasBeenSet = true; m_roleArn = value; } /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline void SetRoleArn(Aws::String&& value) { m_roleArnHasBeenSet = true; m_roleArn = std::move(value); } /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline void SetRoleArn(const char* value) { m_roleArnHasBeenSet = true; m_roleArn.assign(value); } /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline StreamInfo& WithRoleArn(const Aws::String& value) { SetRoleArn(value); return *this;} /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline StreamInfo& WithRoleArn(Aws::String&& value) { SetRoleArn(std::move(value)); return *this;} /** * <p>An IAM role AWS IoT assumes to access your S3 files.</p> */ inline StreamInfo& WithRoleArn(const char* value) { SetRoleArn(value); return *this;} private: Aws::String m_streamId; bool m_streamIdHasBeenSet; Aws::String m_streamArn; bool m_streamArnHasBeenSet; int m_streamVersion; bool m_streamVersionHasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; Aws::Vector<StreamFile> m_files; bool m_filesHasBeenSet; Aws::Utils::DateTime m_createdAt; bool m_createdAtHasBeenSet; Aws::Utils::DateTime m_lastUpdatedAt; bool m_lastUpdatedAtHasBeenSet; Aws::String m_roleArn; bool m_roleArnHasBeenSet; }; } // namespace Model } // namespace IoT } // namespace Aws
29.87027
136
0.63726
[ "vector", "model" ]
43d5fdba3351d4ca069b4b69a52ef7b4e21bd4ef
5,013
h
C
src/Memory/IPKCacheBase.h
ucam-comparch-loki/lokisim
3641e01d6173d448a8bd9d62c3cc9664d05e442d
[ "MIT" ]
null
null
null
src/Memory/IPKCacheBase.h
ucam-comparch-loki/lokisim
3641e01d6173d448a8bd9d62c3cc9664d05e442d
[ "MIT" ]
2
2020-04-06T14:22:31.000Z
2020-06-01T09:33:37.000Z
src/Memory/IPKCacheBase.h
ucam-comparch-loki/lokisim
3641e01d6173d448a8bd9d62c3cc9664d05e442d
[ "MIT" ]
null
null
null
/* * IPKCacheBase.h * * Created on: 11 Jul 2012 * Author: db434 */ #ifndef IPKCACHEBASE_H_ #define IPKCACHEBASE_H_ #include "../Datatype/Instruction.h" #include "../Types.h" #include "../Utility/ISA.h" #include "../Utility/LoopCounter.h" #include "MemoryTypes.h" using sc_core::sc_event; class IPKCacheBase { //============================================================================// // Constructors and destructors //============================================================================// public: IPKCacheBase(const std::string& name, size_t size, size_t numTags, size_t maxIPKLength); virtual ~IPKCacheBase(); //============================================================================// // Methods //============================================================================// public: // Returns whether the given address matches any of the tags. virtual CacheIndex lookup(const MemoryAddr tag); // Returns the next item in the cache. virtual const Instruction read(); // Writes new data to the cache. The position to write to, and the tag for // the data, are already known. Returns the position written to. virtual CacheIndex write(const Instruction inst); // Set the tag of the most recently written instruction to the given value. virtual void setTag(MemoryAddr tag); // Jump to a new instruction at a given offset. virtual void jump(const JumpOffset offset); // Returns the remaining number of entries in the cache. virtual size_t remainingSpace() const; // Returns whether the cache is empty. Note that even if a cache is empty, // it is still possible to access its contents if an appropriate tag is // looked up. virtual bool empty() const; // Returns whether the cache is full. virtual bool full() const; // Event triggered whenever an instruction is read for the first time. This // is the signal that a credit should be sent (if necessary). const sc_event& dataConsumedEvent() const; // Return whether this core is allowed to send out a new fetch request. // It is not allowed to send the request if there is not room for a maximum- // size packet. virtual bool canFetch() const; // Abort execution of this instruction packet, and resume when the next packet // arrives. virtual void cancelPacket(); // Store some initial instructions in the cache. Returns the cache location // to which the first instruction was written. virtual CacheIndex storeCode(const std::vector<Instruction>& code); size_t size() const; // Low-level access methods - use with caution! CacheIndex getReadPointer() const; CacheIndex getWritePointer() const; void setReadPointer(CacheIndex pos); void setWritePointer(CacheIndex pos); const Instruction& debugRead(uint pos) const; protected: // Returns the position of the instruction from the given memory location, or // NOT_IN_CACHE if it is not available. virtual CacheIndex cacheIndex(const MemoryAddr address) const = 0; virtual void setTag(const CacheIndex position, const MemoryAddr tag) = 0; // Determine which position to read from next. Executed immediately before // performing the read. virtual void updateReadPointer() = 0; // Determine which position to write to next. Executed immediately before // performing the write. virtual void updateWritePointer() = 0; // Returns the position that data with the given address tag should be stored. // virtual CacheIndex getPosition(const MemoryAddr& address) = 0; virtual void incrementWritePos(); virtual void incrementReadPos(); virtual size_t getFillCount() const; private: // Instrumentation helper methods. void tagActivity(); void dataActivity(); //============================================================================// // Local state //============================================================================// protected: static const CacheIndex NOT_IN_CACHE = -1; static const MemoryAddr DEFAULT_TAG = 0xFFFFFFFF; const std::string name; // The maximum number of instructions in a single packet. Allows us to be // sure that any packet will fit in the cache when requested. const size_t maxIPKLength; // All accesses to tags must be through getTag and setTag, as different cache // configurations use tags differently. std::vector<MemoryAddr> tags; std::vector<Instruction> data; std::vector<bool> fresh; // Current instruction pointer and refill pointer. LoopCounter readPointer, writePointer; JumpOffset jumpAmount; bool finishedPacketRead, finishedPacketWrite; // When the read and write pointers are in the same place, we use this to // tell whether the cache is full or empty. bool lastOpWasARead; private: sc_event dataConsumed; // Keep track of which cycles the tag and data arrays were active so we can // estimate potential savings of clock gating. cycle_count_t lastTagActivity, lastDataActivity; }; #endif /* IPKCACHEBASE_H_ */
30.754601
80
0.664871
[ "vector" ]
43daba513287e41a1a7cf1ea50eb5e507e49f1d0
5,282
h
C
cpp/FeedRequest_generated.h
morriph/platform-api
b53cc146a3653ab6c358d6c7ecdfd8b245755f1c
[ "Apache-2.0" ]
null
null
null
cpp/FeedRequest_generated.h
morriph/platform-api
b53cc146a3653ab6c358d6c7ecdfd8b245755f1c
[ "Apache-2.0" ]
null
null
null
cpp/FeedRequest_generated.h
morriph/platform-api
b53cc146a3653ab6c358d6c7ecdfd8b245755f1c
[ "Apache-2.0" ]
null
null
null
// automatically generated by the FlatBuffers compiler, do not modify #ifndef FLATBUFFERS_GENERATED_FEEDREQUEST_REACTIVE_PAPI_H_ #define FLATBUFFERS_GENERATED_FEEDREQUEST_REACTIVE_PAPI_H_ #include "flatbuffers/flatbuffers.h" #include "Enum_generated.h" namespace reactive { namespace papi { struct FeedRequest; struct FeedRequestBuilder; struct FeedRequest FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { typedef FeedRequestBuilder Builder; enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_REQ_ID = 4, VT_SUB_REQ_TYPE = 6, VT_FEED_TYPE = 8, VT_GROUPING = 10, VT_DEPTH = 12, VT_FREQUENCY = 14, VT_MARKETS = 16 }; const flatbuffers::String *req_id() const { return GetPointer<const flatbuffers::String *>(VT_REQ_ID); } reactive::papi::SubReqType sub_req_type() const { return static_cast<reactive::papi::SubReqType>(GetField<int8_t>(VT_SUB_REQ_TYPE, 1)); } reactive::papi::FeedType feed_type() const { return static_cast<reactive::papi::FeedType>(GetField<int16_t>(VT_FEED_TYPE, 0)); } uint16_t grouping() const { return GetField<uint16_t>(VT_GROUPING, 0); } int16_t depth() const { return GetField<int16_t>(VT_DEPTH, 0); } int16_t frequency() const { return GetField<int16_t>(VT_FREQUENCY, 0); } const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *markets() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>> *>(VT_MARKETS); } bool Verify(flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_REQ_ID) && verifier.VerifyString(req_id()) && VerifyField<int8_t>(verifier, VT_SUB_REQ_TYPE) && VerifyField<int16_t>(verifier, VT_FEED_TYPE) && VerifyField<uint16_t>(verifier, VT_GROUPING) && VerifyField<int16_t>(verifier, VT_DEPTH) && VerifyField<int16_t>(verifier, VT_FREQUENCY) && VerifyOffset(verifier, VT_MARKETS) && verifier.VerifyVector(markets()) && verifier.VerifyVectorOfStrings(markets()) && verifier.EndTable(); } }; struct FeedRequestBuilder { typedef FeedRequest Table; flatbuffers::FlatBufferBuilder &fbb_; flatbuffers::uoffset_t start_; void add_req_id(flatbuffers::Offset<flatbuffers::String> req_id) { fbb_.AddOffset(FeedRequest::VT_REQ_ID, req_id); } void add_sub_req_type(reactive::papi::SubReqType sub_req_type) { fbb_.AddElement<int8_t>(FeedRequest::VT_SUB_REQ_TYPE, static_cast<int8_t>(sub_req_type), 1); } void add_feed_type(reactive::papi::FeedType feed_type) { fbb_.AddElement<int16_t>(FeedRequest::VT_FEED_TYPE, static_cast<int16_t>(feed_type), 0); } void add_grouping(uint16_t grouping) { fbb_.AddElement<uint16_t>(FeedRequest::VT_GROUPING, grouping, 0); } void add_depth(int16_t depth) { fbb_.AddElement<int16_t>(FeedRequest::VT_DEPTH, depth, 0); } void add_frequency(int16_t frequency) { fbb_.AddElement<int16_t>(FeedRequest::VT_FREQUENCY, frequency, 0); } void add_markets(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> markets) { fbb_.AddOffset(FeedRequest::VT_MARKETS, markets); } explicit FeedRequestBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } flatbuffers::Offset<FeedRequest> Finish() { const auto end = fbb_.EndTable(start_); auto o = flatbuffers::Offset<FeedRequest>(end); return o; } }; inline flatbuffers::Offset<FeedRequest> CreateFeedRequest( flatbuffers::FlatBufferBuilder &_fbb, flatbuffers::Offset<flatbuffers::String> req_id = 0, reactive::papi::SubReqType sub_req_type = reactive::papi::SubReqType::Subscribe, reactive::papi::FeedType feed_type = reactive::papi::FeedType::Default, uint16_t grouping = 0, int16_t depth = 0, int16_t frequency = 0, flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> markets = 0) { FeedRequestBuilder builder_(_fbb); builder_.add_markets(markets); builder_.add_req_id(req_id); builder_.add_frequency(frequency); builder_.add_depth(depth); builder_.add_grouping(grouping); builder_.add_feed_type(feed_type); builder_.add_sub_req_type(sub_req_type); return builder_.Finish(); } inline flatbuffers::Offset<FeedRequest> CreateFeedRequestDirect( flatbuffers::FlatBufferBuilder &_fbb, const char *req_id = nullptr, reactive::papi::SubReqType sub_req_type = reactive::papi::SubReqType::Subscribe, reactive::papi::FeedType feed_type = reactive::papi::FeedType::Default, uint16_t grouping = 0, int16_t depth = 0, int16_t frequency = 0, const std::vector<flatbuffers::Offset<flatbuffers::String>> *markets = nullptr) { auto req_id__ = req_id ? _fbb.CreateString(req_id) : 0; auto markets__ = markets ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*markets) : 0; return reactive::papi::CreateFeedRequest( _fbb, req_id__, sub_req_type, feed_type, grouping, depth, frequency, markets__); } } // namespace papi } // namespace reactive #endif // FLATBUFFERS_GENERATED_FEEDREQUEST_REACTIVE_PAPI_H_
35.931973
112
0.724158
[ "vector" ]
43e318ac4e9feb60111ec488ce9da7d895e05bb6
2,170
h
C
llvm-3.5/tools/llvm-diff/DiffLog.h
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
llvm-3.5/tools/llvm-diff/DiffLog.h
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
llvm-3.5/tools/llvm-diff/DiffLog.h
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
//===-- DiffLog.h - Difference Log Builder and accessories ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header defines the interface to the LLVM difference log builder. // //===----------------------------------------------------------------------===// #ifndef _LLVM_DIFFLOG_H_ #define _LLVM_DIFFLOG_H_ #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" namespace llvm { class Instruction; class Value; class Consumer; /// Trichotomy assumption enum DiffChange { DC_match, DC_left, DC_right }; /// A temporary-object class for building up log messages. class LogBuilder { Consumer &consumer; /// The use of a stored StringRef here is okay because /// LogBuilder should be used only as a temporary, and as a /// temporary it will be destructed before whatever temporary /// might be initializing this format. StringRef Format; SmallVector<Value*, 4> Arguments; public: LogBuilder(Consumer &c, StringRef Format) : consumer(c), Format(Format) {} LogBuilder &operator<<(Value *V) { Arguments.push_back(V); return *this; } ~LogBuilder(); StringRef getFormat() const; unsigned getNumArguments() const; Value *getArgument(unsigned I) const; }; /// A temporary-object class for building up diff messages. class DiffLogBuilder { typedef std::pair<Instruction*,Instruction*> DiffRecord; SmallVector<DiffRecord, 20> Diff; Consumer &consumer; public: DiffLogBuilder(Consumer &c) : consumer(c) {} ~DiffLogBuilder(); void addMatch(Instruction *L, Instruction *R); // HACK: VS 2010 has a bug in the stdlib that requires this. void addLeft(Instruction *L); void addRight(Instruction *R); unsigned getNumLines() const; DiffChange getLineKind(unsigned I) const; Instruction *getLeft(unsigned I) const; Instruction *getRight(unsigned I) const; }; } #endif
26.790123
80
0.631336
[ "object" ]
43ea47f400eebdf12c8f120c1697826e47cb937d
2,741
h
C
ProcessLib/BoundaryCondition/Python/PythonBoundaryConditionPythonSideInterface.h
hosseinsotudeh/ogs
214afcb00af23e4393168a846c7ee8ce4f13e489
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/BoundaryCondition/Python/PythonBoundaryConditionPythonSideInterface.h
hosseinsotudeh/ogs
214afcb00af23e4393168a846c7ee8ce4f13e489
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/BoundaryCondition/Python/PythonBoundaryConditionPythonSideInterface.h
hosseinsotudeh/ogs
214afcb00af23e4393168a846c7ee8ce4f13e489
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once namespace ProcessLib { //! Base class for boundary conditions. //! This class will get Python bindings and is intended to be to be derived in //! Python. class PythonBoundaryConditionPythonSideInterface { public: /*! * Computes Dirichlet boundary condition values for the provided arguments * (time, position of the node, node id, primary variables at the node). * * \return a pair (is_dirichlet, value) indicating if a Dirichlet BC shall * be set at that node and (if so) the value of the Dirichlet BC at that * node. */ virtual std::pair<bool, double> getDirichletBCValue( double /*t*/, std::array<double, 3> /*x*/, std::size_t /*node_id*/, std::vector<double> const& /*primary_variables*/) const { _overridden_essential = false; return {false, std::numeric_limits<double>::quiet_NaN()}; } /*! * Computes the flux for the provided arguments (time, position, primary * variables at that position). * * \return a pair (is_natural, flux, flux_jacobian) indicating if a natural * BC shall be set at that position and (if so) the flux at that node and * the derivative of the flux w.r.t. all primary variables. */ virtual std::tuple<bool, double, std::vector<double>> getFlux( double /*t*/, std::array<double, 3> /*x*/, std::vector<double> const& /*primary_variables*/) const { _overridden_natural = false; return std::tuple<bool, double, std::vector<double>>{ false, std::numeric_limits<double>::quiet_NaN(), {}}; } //! Tells if getDirichletBCValue() has been overridden in the derived class //! in Python. //! //! \pre getDirichletBCValue() must already have been called //! once. bool isOverriddenEssential() const { return _overridden_essential; } //! Tells if getFlux() has been overridden in the derived class in Python. //! //! \pre getFlux() must already have been called once. bool isOverriddenNatural() const { return _overridden_natural; } virtual ~PythonBoundaryConditionPythonSideInterface() = default; private: //! Tells if getDirichletBCValue() has been overridden in the derived class //! in Python. mutable bool _overridden_essential = true; //! Tells if getFlux() has been overridden in the derived class in Python. mutable bool _overridden_natural = true; }; } // namespace ProcessLib
36.065789
79
0.661073
[ "vector" ]
43eb84ccf45e613657d1969c735f054d73c1d3d0
372
h
C
include/ontologenius_query/ressource.h
sarthou/ontologenius_query
cc7246a774b5ba43b99fa9361f83d2f53d016507
[ "BSD-2-Clause" ]
null
null
null
include/ontologenius_query/ressource.h
sarthou/ontologenius_query
cc7246a774b5ba43b99fa9361f83d2f53d016507
[ "BSD-2-Clause" ]
null
null
null
include/ontologenius_query/ressource.h
sarthou/ontologenius_query
cc7246a774b5ba43b99fa9361f83d2f53d016507
[ "BSD-2-Clause" ]
null
null
null
#ifndef ONTOLOGENIUSQUERY_RESSOURCE_H #define ONTOLOGENIUSQUERY_RESSOURCE_H namespace ontologenius_query { struct resource_t { std::string name; bool variable; bool regex; }; struct triplet_t { resource_t subject; resource_t predicat; resource_t object; }; } // namespace ontologenius_query #endif // ONTOLOGENIUSQUERY_RESSOURCE_H
15.5
39
0.736559
[ "object" ]
43eefdd4c9872206ed7f7e1cb1ab4c5a5537599a
28,277
h
C
src/Type.h
asilha/zeek
122640a713735257f784f38739232ae20f020a3b
[ "Apache-2.0" ]
1
2021-04-23T16:57:53.000Z
2021-04-23T16:57:53.000Z
src/Type.h
NathanPBarnes/zeek
672504e2652e32c1d5e06c0c5f66dad9a1b21fd9
[ "Apache-2.0" ]
null
null
null
src/Type.h
NathanPBarnes/zeek
672504e2652e32c1d5e06c0c5f66dad9a1b21fd9
[ "Apache-2.0" ]
null
null
null
// See the file "COPYING" in the main distribution directory for copyright. #pragma once #include <string> #include <set> #include <unordered_map> #include <map> #include <list> #include <optional> #include "zeek/Obj.h" #include "zeek/ID.h" #include "zeek/Attr.h" #include "zeek/ZeekList.h" #include "zeek/IntrusivePtr.h" namespace zeek { class Val; class EnumVal; class TableVal; using ValPtr = IntrusivePtr<Val>; using EnumValPtr = IntrusivePtr<EnumVal>; using TableValPtr = IntrusivePtr<TableVal>; namespace detail { class Expr; class ListExpr; class Attributes; using ListExprPtr = IntrusivePtr<ListExpr>; } // namespace detail // BRO types. enum TypeTag { TYPE_VOID, // 0 TYPE_BOOL, // 1 TYPE_INT, // 2 TYPE_COUNT, // 3 TYPE_DOUBLE, // 4 TYPE_TIME, // 5 TYPE_INTERVAL, // 6 TYPE_STRING, // 7 TYPE_PATTERN, // 8 TYPE_ENUM, // 9 TYPE_TIMER, // 10 TYPE_PORT, // 11 TYPE_ADDR, // 12 TYPE_SUBNET, // 13 TYPE_ANY, // 14 TYPE_TABLE, // 15 TYPE_UNION, // 16 TYPE_RECORD, // 17 TYPE_LIST, // 18 TYPE_FUNC, // 19 TYPE_FILE, // 20 TYPE_VECTOR, // 21 TYPE_OPAQUE, // 22 TYPE_TYPE, // 23 TYPE_ERROR // 24 #define NUM_TYPES (int(TYPE_ERROR) + 1) }; // Returns the name of the type. extern const char* type_name(TypeTag t); constexpr bool is_network_order(TypeTag tag) noexcept { return tag == TYPE_PORT; } enum FunctionFlavor { FUNC_FLAVOR_FUNCTION, FUNC_FLAVOR_EVENT, FUNC_FLAVOR_HOOK }; enum InternalTypeTag : uint16_t { TYPE_INTERNAL_VOID, TYPE_INTERNAL_INT, TYPE_INTERNAL_UNSIGNED, TYPE_INTERNAL_DOUBLE, TYPE_INTERNAL_STRING, TYPE_INTERNAL_ADDR, TYPE_INTERNAL_SUBNET, TYPE_INTERNAL_OTHER, TYPE_INTERNAL_ERROR }; constexpr InternalTypeTag to_internal_type_tag(TypeTag tag) noexcept { switch ( tag ) { case TYPE_VOID: return TYPE_INTERNAL_VOID; case TYPE_BOOL: case TYPE_INT: case TYPE_ENUM: return TYPE_INTERNAL_INT; case TYPE_COUNT: case TYPE_PORT: return TYPE_INTERNAL_UNSIGNED; case TYPE_DOUBLE: case TYPE_TIME: case TYPE_INTERVAL: return TYPE_INTERNAL_DOUBLE; case TYPE_STRING: return TYPE_INTERNAL_STRING; case TYPE_ADDR: return TYPE_INTERNAL_ADDR; case TYPE_SUBNET: return TYPE_INTERNAL_SUBNET; case TYPE_PATTERN: case TYPE_TIMER: case TYPE_ANY: case TYPE_TABLE: case TYPE_UNION: case TYPE_RECORD: case TYPE_LIST: case TYPE_FUNC: case TYPE_FILE: case TYPE_OPAQUE: case TYPE_VECTOR: case TYPE_TYPE: return TYPE_INTERNAL_OTHER; case TYPE_ERROR: return TYPE_INTERNAL_ERROR; } /* this should be unreachable */ return TYPE_INTERNAL_VOID; } class Type; class TypeList; class TableType; class SetType; class RecordType; class SubNetType; class FuncType; class EnumType; class VectorType; class TypeType; class OpaqueType; class FileType; using TypePtr = IntrusivePtr<Type>; using TypeListPtr = IntrusivePtr<TypeList>; using TableTypePtr = IntrusivePtr<TableType>; using SetTypePtr = IntrusivePtr<SetType>; using RecordTypePtr = IntrusivePtr<RecordType>; using SubNetTypePtr = IntrusivePtr<SubNetType>; using FuncTypePtr = IntrusivePtr<FuncType>; using EnumTypePtr = IntrusivePtr<EnumType>; using VectorTypePtr = IntrusivePtr<VectorType>; using TypeTypePtr = IntrusivePtr<TypeType>; using OpaqueTypePtr = IntrusivePtr<OpaqueType>; using FileTypePtr = IntrusivePtr<FileType>; constexpr int DOES_NOT_MATCH_INDEX = 0; constexpr int MATCHES_INDEX_SCALAR = 1; constexpr int MATCHES_INDEX_VECTOR = 2; class Type : public Obj { public: static inline const TypePtr nil; explicit Type(TypeTag tag, bool base_type = false); // Performs a shallow clone operation of the Bro type. // This especially means that especially for tables the types // are not recursively cloned; altering one type will in this case // alter one of them. // The main use for this is alias tracking. // Clone operations will mostly be implemented in the derived classes; // in addition cloning will be limited to classes that can be reached by // the script-level. virtual TypePtr ShallowClone(); TypeTag Tag() const { return tag; } InternalTypeTag InternalType() const { return internal_tag; } // Whether it's stored in network order. bool IsNetworkOrder() const { return is_network_order; } // Type-checks the given expression list, returning // MATCHES_INDEX_SCALAR = 1 if it matches this type's index // and produces a scalar result (and promoting its // subexpressions as necessary); MATCHES_INDEX_VECTOR = 2 // if it matches and produces a vector result; and // DOES_NOT_MATCH_INDEX = 0 if it can't match (or the type // is not an indexable type). virtual int MatchesIndex(detail::ListExpr* index) const; // Returns the type yielded by this type. For example, if // this type is a table[string] of port, then returns the "port" // type. Returns nil if this is not an index type. virtual const TypePtr& Yield() const; const TypeList* AsTypeList() const; TypeList* AsTypeList(); const TableType* AsTableType() const; TableType* AsTableType(); const SetType* AsSetType() const; SetType* AsSetType(); const RecordType* AsRecordType() const; RecordType* AsRecordType(); const SubNetType* AsSubNetType() const; SubNetType* AsSubNetType(); const FuncType* AsFuncType() const; FuncType* AsFuncType(); const FileType* AsFileType() const; FileType* AsFileType(); const EnumType* AsEnumType() const; EnumType* AsEnumType(); const VectorType* AsVectorType() const; VectorType* AsVectorType(); const OpaqueType* AsOpaqueType() const; OpaqueType* AsOpaqueType(); const TypeType* AsTypeType() const; TypeType* AsTypeType(); bool IsSet() const { return tag == TYPE_TABLE && ! Yield(); } bool IsTable() const { return tag == TYPE_TABLE && Yield(); } Type* Ref() { ::zeek::Ref(this); return this; } void Describe(ODesc* d) const override; virtual void DescribeReST(ODesc* d, bool roles_only = false) const; virtual unsigned MemoryAllocation() const; void SetName(const std::string& arg_name) { name = arg_name; } const std::string& GetName() const { return name; } struct TypePtrComparer { bool operator()(const TypePtr& a, const TypePtr& b) const { return a.get() < b.get(); } }; using TypePtrSet = std::set<TypePtr, TypePtrComparer>; using TypeAliasMap = std::map<std::string, TypePtrSet, std::less<>>; /** * Returns a mapping of type-name to all other type names declared as * an alias to it. */ static const TypeAliasMap& GetAliasMap() { return type_aliases; } /** * Returns true if the given type name has any declared aliases */ static bool HasAliases(std::string_view type_name) { return Type::type_aliases.find(type_name) != Type::type_aliases.end(); } /** * Returns the set of all type names declared as an aliases to the given * type name. A static empty set is returned if there are no aliases. */ static const TypePtrSet& Aliases(std::string_view type_name) { static TypePtrSet empty; auto it = Type::type_aliases.find(type_name); return it == Type::type_aliases.end() ? empty : it->second; } /** * Registers a new type alias. * @param type_name the name of the type to register a new alias for. * @param type the associated alias type of *type_name*. * @return true if the alias is now registered or false if the alias was * already previously registered. */ static bool RegisterAlias(std::string_view type_name, TypePtr type) { auto it = Type::type_aliases.find(type_name); if ( it == Type::type_aliases.end() ) it = Type::type_aliases.emplace(std::string{type_name}, TypePtrSet{}).first; return it->second.emplace(std::move(type)).second; } protected: Type() = default; void SetError(); private: TypeTag tag; InternalTypeTag internal_tag; bool is_network_order; bool base_type; std::string name; static TypeAliasMap type_aliases; }; class TypeList final : public Type { public: explicit TypeList(TypePtr arg_pure_type = nullptr) : Type(TYPE_LIST), pure_type(std::move(arg_pure_type)) { } ~TypeList() override = default; const std::vector<TypePtr>& GetTypes() const { return types; } bool IsPure() const { return pure_type != nullptr; } // Returns the underlying pure type, or nil if the list // is not pure or is empty. const TypePtr& GetPureType() const { return pure_type; } // True if all of the types match t, false otherwise. If // is_init is true, then the matching is done in the context // of an initialization. bool AllMatch(const Type* t, bool is_init) const; bool AllMatch(const TypePtr& t, bool is_init) const { return AllMatch(t.get(), is_init); } void Append(TypePtr t); void AppendEvenIfNotPure(TypePtr t); void Describe(ODesc* d) const override; unsigned int MemoryAllocation() const override; protected: TypePtr pure_type; std::vector<TypePtr> types; }; class IndexType : public Type { public: int MatchesIndex(detail::ListExpr* index) const override; const TypeListPtr& GetIndices() const { return indices; } const std::vector<TypePtr>& GetIndexTypes() const { return indices->GetTypes(); } const TypePtr& Yield() const override { return yield_type; } void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool roles_only = false) const override; // Returns true if this table is solely indexed by subnet. bool IsSubNetIndex() const; protected: IndexType(TypeTag t, TypeListPtr arg_indices, TypePtr arg_yield_type) : Type(t), indices(std::move(arg_indices)), yield_type(std::move(arg_yield_type)) { } ~IndexType() override = default; TypeListPtr indices; TypePtr yield_type; }; class TableType : public IndexType { public: TableType(TypeListPtr ind, TypePtr yield); /** * Assesses whether an &expire_func attribute's function type is compatible * with this table type. * @param attr the &expire_func attribute to check (this method must not be * called with other type of attributes). * @return true if compatible, false if not */ bool CheckExpireFuncCompatibility(const detail::AttrPtr& attr); TypePtr ShallowClone() override; // Returns true if this table type is "unspecified", which is // what one gets using an empty "set()" or "table()" constructor. bool IsUnspecifiedTable() const; }; class SetType final : public TableType { public: SetType(TypeListPtr ind, detail::ListExprPtr arg_elements); ~SetType() override; TypePtr ShallowClone() override; const detail::ListExprPtr& Elements() const { return elements; } protected: detail::ListExprPtr elements; }; class FuncType final : public Type { public: static inline const FuncTypePtr nil; /** * Prototype is only currently used for events and hooks which declare * multiple signature prototypes that allow users to have handlers * with various argument permutations. */ struct Prototype { bool deprecated; std::string deprecation_msg; RecordTypePtr args; // Maps from parameter index in canonical prototype to // parameter index in this alternate prorotype. std::map<int, int> offsets; }; FuncType(RecordTypePtr args, TypePtr yield, FunctionFlavor f); TypePtr ShallowClone() override; const RecordTypePtr& Params() const { return args; } const TypePtr& Yield() const override { return yield; } void SetYieldType(TypePtr arg_yield) { yield = std::move(arg_yield); } FunctionFlavor Flavor() const { return flavor; } std::string FlavorString() const; // Used to convert a function type to an event or hook type. void ClearYieldType(FunctionFlavor arg_flav) { yield = nullptr; flavor = arg_flav; } int MatchesIndex(detail::ListExpr* index) const override; bool CheckArgs(const TypePList* args, bool is_init = false, bool do_warn = true) const; bool CheckArgs(const std::vector<TypePtr>& args, bool is_init = false, bool do_warn = true) const; const TypeListPtr& ParamList() const { return arg_types; } void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool roles_only = false) const override; /** * Adds a new event/hook signature allowed for use in handlers. */ void AddPrototype(Prototype s); /** * Returns a prototype signature that matches the desired argument types. */ std::optional<Prototype> FindPrototype(const RecordType& args) const; /** * Returns all allowed function prototypes. */ const std::vector<Prototype>& Prototypes() const { return prototypes; } /** * A single lambda "capture" (outer variable used in a lambda's body). */ struct Capture { detail::IDPtr id; bool deep_copy; }; using CaptureList = std::vector<Capture>; /** * Sets this function's set of captures. Only valid for lambdas. * * @param captures if non-nil, a list of the lambda's captures */ void SetCaptures(std::optional<CaptureList> captures); /** * Returns the captures declared for this function, or nil if none. * * @return a vector giving the captures */ const std::optional<CaptureList>& GetCaptures() const { return captures; } protected: friend FuncTypePtr make_intrusive<FuncType>(); FuncType() : Type(TYPE_FUNC) { flavor = FUNC_FLAVOR_FUNCTION; } RecordTypePtr args; TypeListPtr arg_types; TypePtr yield; FunctionFlavor flavor; std::vector<Prototype> prototypes; std::optional<CaptureList> captures; // if nil then no captures specified }; class TypeType final : public Type { public: explicit TypeType(TypePtr t) : zeek::Type(TYPE_TYPE), type(std::move(t)) {} TypePtr ShallowClone() override { return make_intrusive<TypeType>(type); } const TypePtr& GetType() const { return type; } template <class T> IntrusivePtr<T> GetType() const { return cast_intrusive<T>(type); } protected: TypePtr type; }; class TypeDecl final { public: TypeDecl() = default; TypeDecl(const char* i, TypePtr t, detail::AttributesPtr attrs = nullptr); TypeDecl(const TypeDecl& other); ~TypeDecl(); const detail::AttrPtr& GetAttr(detail::AttrTag a) const { return attrs ? attrs->Find(a) : detail::Attr::nil; } void DescribeReST(ODesc* d, bool roles_only = false) const; TypePtr type; detail::AttributesPtr attrs; const char* id = nullptr; }; using type_decl_list = PList<TypeDecl>; class RecordType final : public Type { public: explicit RecordType(type_decl_list* types); TypePtr ShallowClone() override; ~RecordType() override; bool HasField(const char* field) const; /** * Looks up a field by name and returns its type. No check for invalid * field name is performed. */ const TypePtr& GetFieldType(const char* field_name) const { return GetFieldType(FieldOffset(field_name)); } /** * Looks up a field by name and returns its type as cast to @c T. * No check for invalid field name is performed. */ template <class T> IntrusivePtr<T> GetFieldType(const char* field_name) const { return cast_intrusive<T>(GetFieldType(field_name)); } /** * Looks up a field by its index and returns its type. No check for * invalid field offset is performed. */ const TypePtr& GetFieldType(int field_index) const { return (*types)[field_index]->type; } /** * Looks up a field by its index and returns its type as cast to @c T. * No check for invalid field offset is performed. */ template <class T> IntrusivePtr<T> GetFieldType(int field_index) const { return cast_intrusive<T>((*types)[field_index]->type); } ValPtr FieldDefault(int field) const; // A field's offset is its position in the type_decl_list, // starting at 0. Returns negative if the field doesn't exist. int FieldOffset(const char* field) const; // Given an offset, returns the field's name. const char* FieldName(int field) const; const type_decl_list* Types() const { return types; } type_decl_list* Types() { return types; } // Given an offset, returns the field's TypeDecl. const TypeDecl* FieldDecl(int field) const; TypeDecl* FieldDecl(int field); // Returns flags corresponding to which fields in the record // have types requiring memory management (reference counting). const std::vector<bool>& ManagedFields() const { return managed_fields; } int NumFields() const { return num_fields; } int NumOrigFields() const { return num_orig_fields; } /** * Returns a "record_field_table" value for introspection purposes. * @param rv an optional record value, if given the values of * all fields will be provided in the returned table. */ TableValPtr GetRecordFieldsVal(const RecordVal* rv = nullptr) const; // Returns null if all is ok, otherwise a pointer to an error message. const char* AddFields(const type_decl_list& types, bool add_log_attr = false); void AddFieldsDirectly(const type_decl_list& types, bool add_log_attr = false); void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool roles_only = false) const override; void DescribeFields(ODesc* d) const; void DescribeFieldsReST(ODesc* d, bool func_args) const; bool IsFieldDeprecated(int field) const { const TypeDecl* decl = FieldDecl(field); return decl && decl->GetAttr(detail::ATTR_DEPRECATED) != nullptr; } bool FieldHasAttr(int field, detail::AttrTag at) const { const TypeDecl* decl = FieldDecl(field); return decl && decl->GetAttr(at) != nullptr; } std::string GetFieldDeprecationWarning(int field, bool has_check) const; protected: RecordType() { types = nullptr; } void AddField(unsigned int field, const TypeDecl* td); // If we were willing to bound the size of records, then we could // use std::bitset here instead. std::vector<bool> managed_fields; // Number of fields in the type. int num_fields; // Number of fields in the type when originally declared. int num_orig_fields; type_decl_list* types; }; class SubNetType final : public Type { public: SubNetType(); void Describe(ODesc* d) const override; }; class FileType final : public Type { public: explicit FileType(TypePtr yield_type); TypePtr ShallowClone() override { return make_intrusive<FileType>(yield); } ~FileType() override; const TypePtr& Yield() const override { return yield; } void Describe(ODesc* d) const override; protected: TypePtr yield; }; class OpaqueType final : public Type { public: explicit OpaqueType(const std::string& name); TypePtr ShallowClone() override { return make_intrusive<OpaqueType>(name); } ~OpaqueType() override { }; const std::string& Name() const { return name; } void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool roles_only = false) const override; protected: OpaqueType() { } std::string name; }; class EnumType final : public Type { public: typedef std::list<std::pair<std::string, bro_int_t> > enum_name_list; explicit EnumType(const EnumType* e); explicit EnumType(const std::string& arg_name); TypePtr ShallowClone() override; ~EnumType() override; // The value of this name is next internal counter value, starting // with zero. The internal counter is incremented. void AddName(const std::string& module_name, const char* name, bool is_export, detail::Expr* deprecation = nullptr, bool from_redef = false); // The value of this name is set to val. Once a value has been // explicitly assigned using this method, no further names can be // added that aren't likewise explicitly initalized. void AddName(const std::string& module_name, const char* name, bro_int_t val, bool is_export, detail::Expr* deprecation = nullptr, bool from_redef = false); // -1 indicates not found. Second version is for full names // that already incorporate the module. bro_int_t Lookup(const std::string& module_name, const char* name) const; bro_int_t Lookup(const std::string& full_name) const; const char* Lookup(bro_int_t value) const; // Returns 0 if not found // Returns the list of defined names with their values. The names // will be fully qualified with their module name. enum_name_list Names() const; bool HasRedefs() const { return has_redefs; } void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool roles_only = false) const override; const EnumValPtr& GetEnumVal(bro_int_t i); protected: void AddNameInternal(const std::string& module_name, const char* name, bro_int_t val, bool is_export); void AddNameInternal(const std::string& full_name, bro_int_t val); void CheckAndAddName(const std::string& module_name, const char* name, bro_int_t val, bool is_export, detail::Expr* deprecation = nullptr, bool from_redef = false); typedef std::map<std::string, bro_int_t> NameMap; NameMap names; // Whether any of the elements of the enum were added via redef's. bool has_redefs = false; using ValMap = std::unordered_map<bro_int_t, EnumValPtr>; ValMap vals; // The counter is initialized to 0 and incremented on every implicit // auto-increment name that gets added (thus its > 0 if // auto-increment is used). Once an explicit value has been // specified, the counter is set to -1. This way counter can be used // as a flag to prevent mixing of auto-increment and explicit // enumerator specifications. bro_int_t counter; }; class VectorType final : public Type { public: explicit VectorType(TypePtr t); TypePtr ShallowClone() override; ~VectorType() override; const TypePtr& Yield() const override; int MatchesIndex(detail::ListExpr* index) const override; // Returns true if this table type is "unspecified", which is what one // gets using an empty "vector()" constructor. bool IsUnspecifiedVector() const; void Describe(ODesc* d) const override; void DescribeReST(ODesc* d, bool roles_only = false) const override; protected: TypePtr yield_type; }; // True if the two types are equivalent. If is_init is true then the test is // done in the context of an initialization. If match_record_field_names is // true then for record types the field names have to match, too. extern bool same_type(const Type& t1, const Type& t2, bool is_init=false, bool match_record_field_names=true); inline bool same_type(const TypePtr& t1, const TypePtr& t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } inline bool same_type(const Type* t1, const Type* t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } inline bool same_type(const TypePtr& t1, const Type* t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } inline bool same_type(const Type* t1, const TypePtr& t2, bool is_init=false, bool match_record_field_names=true) { return same_type(*t1, *t2, is_init, match_record_field_names); } // True if the two attribute lists are equivalent. extern bool same_attrs(const detail::Attributes* a1, const detail::Attributes* a2); // Returns true if the record sub_rec can be promoted to the record // super_rec. extern bool record_promotion_compatible(const RecordType* super_rec, const RecordType* sub_rec); // If the given Type is a TypeList with just one element, returns // that element, otherwise returns the type. extern const Type* flatten_type(const Type* t); extern Type* flatten_type(Type* t); // Returns the "maximum" of two type tags, in a type-promotion sense. extern TypeTag max_type(TypeTag t1, TypeTag t2); // Given two types, returns the "merge", in which promotable types // are promoted to the maximum of the two. Returns nil (and generates // an error message) if the types are incompatible. TypePtr merge_types(const TypePtr& t1, const TypePtr& t2); // Given a list of expressions, returns a (ref'd) type reflecting // a merged type consistent across all of them, or nil if this // cannot be done. TypePtr merge_type_list(detail::ListExpr* elements); // Given an expression, infer its type when used for an initialization. TypePtr init_type(detail::Expr* init); // Returns true if argument is an atomic type. bool is_atomic_type(const Type& t); inline bool is_atomic_type(const Type* t) { return is_atomic_type(*t); } inline bool is_atomic_type(const TypePtr& t) { return is_atomic_type(*t); } // True if the given type tag corresponds to type that can be assigned to. extern bool is_assignable(TypeTag t); inline bool is_assignable(Type* t) { return is_assignable(t->Tag()); } // True if the given type tag corresponds to an integral type. inline bool IsIntegral(TypeTag t) { return (t == TYPE_INT || t == TYPE_COUNT ); } // True if the given type tag corresponds to an arithmetic type. inline bool IsArithmetic(TypeTag t) { return (IsIntegral(t) || t == TYPE_DOUBLE); } // True if the given type tag corresponds to a boolean type. inline bool IsBool(TypeTag t) { return (t == TYPE_BOOL); } // True if the given type tag corresponds to an interval type. inline bool IsInterval(TypeTag t) { return (t == TYPE_INTERVAL); } // True if the given type tag corresponds to a record type. inline bool IsRecord(TypeTag t) { return (t == TYPE_RECORD || t == TYPE_UNION); } // True if the given type tag corresponds to a function type. inline bool IsFunc(TypeTag t) { return (t == TYPE_FUNC); } // True if the given type type is a vector. inline bool IsVector(TypeTag t) { return (t == TYPE_VECTOR); } // True if the given type type is a string. inline bool IsString(TypeTag t) { return (t == TYPE_STRING); } // True if the given type is a container aggregate. inline bool IsAggr(TypeTag tag) { return tag == TYPE_VECTOR || tag == TYPE_TABLE || tag == TYPE_RECORD; } inline bool IsAggr(const Type* t) { return IsAggr(t->Tag()); } inline bool IsAggr(const TypePtr& t) { return IsAggr(t->Tag()); } // True if the given type tag corresponds to the error type. inline bool IsErrorType(TypeTag t) { return (t == TYPE_ERROR); } // True if both tags are integral types. inline bool BothIntegral(TypeTag t1, TypeTag t2) { return (IsIntegral(t1) && IsIntegral(t2)); } // True if both tags are arithmetic types. inline bool BothArithmetic(TypeTag t1, TypeTag t2) { return (IsArithmetic(t1) && IsArithmetic(t2)); } // True if either tags is an arithmetic type. inline bool EitherArithmetic(TypeTag t1, TypeTag t2) { return (IsArithmetic(t1) || IsArithmetic(t2)); } // True if both tags are boolean types. inline bool BothBool(TypeTag t1, TypeTag t2) { return (IsBool(t1) && IsBool(t2)); } // True if both tags are interval types. inline bool BothInterval(TypeTag t1, TypeTag t2) { return (IsInterval(t1) && IsInterval(t2)); } // True if both tags are string types. inline bool BothString(TypeTag t1, TypeTag t2) { return (IsString(t1) && IsString(t2)); } // True if either tag is the error type. inline bool EitherError(TypeTag t1, TypeTag t2) { return (IsErrorType(t1) || IsErrorType(t2)); } // Returns the basic (non-parameterized) type with the given type. const TypePtr& base_type(TypeTag tag); // Returns the basic error type. inline const TypePtr& error_type() { return base_type(TYPE_ERROR); } } // namespace zeek extern zeek::OpaqueTypePtr md5_type; extern zeek::OpaqueTypePtr sha1_type; extern zeek::OpaqueTypePtr sha256_type; extern zeek::OpaqueTypePtr entropy_type; extern zeek::OpaqueTypePtr cardinality_type; extern zeek::OpaqueTypePtr topk_type; extern zeek::OpaqueTypePtr bloomfilter_type; extern zeek::OpaqueTypePtr x509_opaque_type; extern zeek::OpaqueTypePtr ocsp_resp_opaque_type; extern zeek::OpaqueTypePtr paraglob_type; extern zeek::OpaqueTypePtr int_counter_metric_type; extern zeek::OpaqueTypePtr int_counter_metric_family_type; extern zeek::OpaqueTypePtr dbl_counter_metric_type; extern zeek::OpaqueTypePtr dbl_counter_metric_family_type; extern zeek::OpaqueTypePtr int_gauge_metric_type; extern zeek::OpaqueTypePtr int_gauge_metric_family_type; extern zeek::OpaqueTypePtr dbl_gauge_metric_type; extern zeek::OpaqueTypePtr dbl_gauge_metric_family_type; extern zeek::OpaqueTypePtr int_histogram_metric_type; extern zeek::OpaqueTypePtr int_histogram_metric_family_type; extern zeek::OpaqueTypePtr dbl_histogram_metric_type; extern zeek::OpaqueTypePtr dbl_histogram_metric_family_type;
29.733964
157
0.731725
[ "vector" ]
43f0a6084b42580a98b9ab7e4d236436f367b41c
56,699
h
C
src/pbrt/util/vecmath.h
anderslanglands/pbrt-v4
70fc776fd84718eb5bb98b2963b7ab5caab4b1f6
[ "Apache-2.0" ]
4
2020-08-24T19:35:00.000Z
2020-10-28T02:16:21.000Z
src/pbrt/util/vecmath.h
anderslanglands/pbrt-v4
70fc776fd84718eb5bb98b2963b7ab5caab4b1f6
[ "Apache-2.0" ]
null
null
null
src/pbrt/util/vecmath.h
anderslanglands/pbrt-v4
70fc776fd84718eb5bb98b2963b7ab5caab4b1f6
[ "Apache-2.0" ]
1
2020-08-30T14:23:07.000Z
2020-08-30T14:23:07.000Z
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. // The pbrt source code is licensed under the Apache License, Version 2.0. // SPDX: Apache-2.0 #ifndef PBRT_UTIL_VECMATH_H #define PBRT_UTIL_VECMATH_H #include <pbrt/pbrt.h> #include <pbrt/util/check.h> #include <pbrt/util/float.h> #include <pbrt/util/math.h> #include <pbrt/util/print.h> #include <pbrt/util/pstd.h> #include <algorithm> #include <cmath> #include <iterator> #include <string> namespace pbrt { namespace internal { template <typename T> std::string ToString2(T x, T y); template <typename T> std::string ToString3(T x, T y, T z); } // namespace internal extern template std::string internal::ToString2(float, float); extern template std::string internal::ToString2(double, double); extern template std::string internal::ToString2(int, int); extern template std::string internal::ToString3(float, float, float); extern template std::string internal::ToString3(double, double, double); extern template std::string internal::ToString3(int, int, int); namespace { template <typename T> PBRT_CPU_GPU inline bool IsNaN(Interval<T> fi) { return pbrt::IsNaN(T(fi)); } // TupleLength Definition template <typename T> struct TupleLength { using type = Float; }; template <> struct TupleLength<double> { using type = double; }; template <> struct TupleLength<long double> { using type = long double; }; template <typename T> struct TupleLength<Interval<T>> { using type = Interval<typename TupleLength<T>::type>; }; } // anonymous namespace // Tuple2 Definition template <template <typename> class Child, typename T> class Tuple2 { public: // Tuple2 Public Methods static const int nDimensions = 2; Tuple2() = default; PBRT_CPU_GPU Tuple2(T x, T y) : x(x), y(y) { DCHECK(!HasNaN()); } PBRT_CPU_GPU bool HasNaN() const { return IsNaN(x) || IsNaN(y); } #ifndef NDEBUG // The default versions of these are fine for release builds; for debug // we define them so that we can add the Assert checks. PBRT_CPU_GPU Tuple2(const Child<T> &c) { DCHECK(!c.HasNaN()); x = c.x; y = c.y; } PBRT_CPU_GPU Child<T> &operator=(const Child<T> &c) { DCHECK(!c.HasNaN()); x = c.x; y = c.y; return static_cast<Child<T> &>(*this); } #endif // !NDEBUG template <typename U> PBRT_CPU_GPU auto operator+(const Child<U> &c) const -> Child<decltype(T{} + U{})> { DCHECK(!c.HasNaN()); return {x + c.x, y + c.y}; } template <typename U> PBRT_CPU_GPU Child<T> &operator+=(const Child<U> &c) { DCHECK(!c.HasNaN()); x += c.x; y += c.y; return static_cast<Child<T> &>(*this); } template <typename U> PBRT_CPU_GPU auto operator-(const Child<U> &c) const -> Child<decltype(T{} - U{})> { DCHECK(!c.HasNaN()); return {x - c.x, y - c.y}; } template <typename U> PBRT_CPU_GPU Child<T> &operator-=(const Child<U> &c) { DCHECK(!c.HasNaN()); x -= c.x; y -= c.y; return static_cast<Child<T> &>(*this); } PBRT_CPU_GPU bool operator==(const Child<T> &c) const { return x == c.x && y == c.y; } PBRT_CPU_GPU bool operator!=(const Child<T> &c) const { return x != c.x || y != c.y; } template <typename U> PBRT_CPU_GPU auto operator*(U s) const -> Child<decltype(T{} * U{})> { return {s * x, s * y}; } template <typename U> PBRT_CPU_GPU Child<T> &operator*=(U s) { DCHECK(!IsNaN(s)); x *= s; y *= s; return static_cast<Child<T> &>(*this); } template <typename U> PBRT_CPU_GPU auto operator/(U d) const -> Child<decltype(T{} / U{})> { DCHECK(d != 0 && !IsNaN(d)); return {x / d, y / d}; } template <typename U> PBRT_CPU_GPU Child<T> &operator/=(U d) { DCHECK_NE(d, 0); DCHECK(!IsNaN(d)); x /= d; y /= d; return static_cast<Child<T> &>(*this); } PBRT_CPU_GPU Child<T> operator-() const { return {-x, -y}; } PBRT_CPU_GPU T operator[](int i) const { DCHECK(i >= 0 && i <= 1); return (i == 0) ? x : y; } PBRT_CPU_GPU T &operator[](int i) { DCHECK(i >= 0 && i <= 1); return (i == 0) ? x : y; } std::string ToString() const { return internal::ToString2(x, y); } // Tuple2 Public Members T x{}, y{}; }; // Tuple2 Inline Functions template <template <class> class C, typename T, typename U> PBRT_CPU_GPU inline auto operator*(U s, const Tuple2<C, T> &t) -> C<decltype(T{} * U{})> { DCHECK(!t.HasNaN()); return t * s; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Abs(const Tuple2<C, T> &t) { // "argument-dependent lookup..." (here and elsewhere) using std::abs; return {abs(t.x), abs(t.y)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Ceil(const Tuple2<C, T> &t) { using std::ceil; return {ceil(t.x), ceil(t.y)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Floor(const Tuple2<C, T> &t) { using std::floor; return {floor(t.x), floor(t.y)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline auto Lerp(Float t, const Tuple2<C, T> &t0, const Tuple2<C, T> &t1) { return (1 - t) * t0 + t * t1; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> FMA(Float a, const Tuple2<C, T> &b, const Tuple2<C, T> &c) { return {FMA(a, b.x, c.x), FMA(a, b.y, c.y)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> FMA(const Tuple2<C, T> &a, Float b, const Tuple2<C, T> &c) { return FMA(b, a, c); } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Min(const Tuple2<C, T> &t0, const Tuple2<C, T> &t1) { using std::min; return {min(t0.x, t1.x), min(t0.y, t1.y)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline T MinComponentValue(const Tuple2<C, T> &t) { using std::min; return min({t.x, t.y}); } template <template <class> class C, typename T> PBRT_CPU_GPU inline int MinComponentIndex(const Tuple2<C, T> &t) { return (t.x < t.y) ? 0 : 1; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Max(const Tuple2<C, T> &t0, const Tuple2<C, T> &t1) { using std::max; return {max(t0.x, t1.x), max(t0.y, t1.y)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline T MaxComponentValue(const Tuple2<C, T> &t) { using std::max; return max({t.x, t.y}); } template <template <class> class C, typename T> PBRT_CPU_GPU inline int MaxComponentIndex(const Tuple2<C, T> &t) { return (t.x > t.y) ? 0 : 1; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Permute(const Tuple2<C, T> &t, pstd::array<int, 2> p) { return {t[p[0]], t[p[1]]}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline T HProd(const Tuple2<C, T> &t) { return t.x * t.y; } // Tuple3 Definition template <template <typename> class Child, typename T> class Tuple3 { public: // Tuple3 Public Methods Tuple3() = default; PBRT_CPU_GPU Tuple3(T x, T y, T z) : x(x), y(y), z(z) { DCHECK(!HasNaN()); } PBRT_CPU_GPU bool HasNaN() const { return IsNaN(x) || IsNaN(y) || IsNaN(z); } PBRT_CPU_GPU T operator[](int i) const { DCHECK(i >= 0 && i <= 2); if (i == 0) return x; if (i == 1) return y; return z; } PBRT_CPU_GPU T &operator[](int i) { DCHECK(i >= 0 && i <= 2); if (i == 0) return x; if (i == 1) return y; return z; } template <typename U> PBRT_CPU_GPU auto operator+(const Child<U> &c) const -> Child<decltype(T{} + U{})> { DCHECK(!c.HasNaN()); return {x + c.x, y + c.y, z + c.z}; } static const int nDimensions = 3; #ifndef NDEBUG // The default versions of these are fine for release builds; for debug // we define them so that we can add the Assert checks. PBRT_CPU_GPU Tuple3(const Child<T> &c) { DCHECK(!c.HasNaN()); x = c.x; y = c.y; z = c.z; } PBRT_CPU_GPU Child<T> &operator=(const Child<T> &c) { DCHECK(!c.HasNaN()); x = c.x; y = c.y; z = c.z; return static_cast<Child<T> &>(*this); } #endif // !NDEBUG template <typename U> PBRT_CPU_GPU Child<T> &operator+=(const Child<U> &c) { DCHECK(!c.HasNaN()); x += c.x; y += c.y; z += c.z; return static_cast<Child<T> &>(*this); } template <typename U> PBRT_CPU_GPU auto operator-(const Child<U> &c) const -> Child<decltype(T{} - U{})> { DCHECK(!c.HasNaN()); return {x - c.x, y - c.y, z - c.z}; } template <typename U> PBRT_CPU_GPU Child<T> &operator-=(const Child<U> &c) { DCHECK(!c.HasNaN()); x -= c.x; y -= c.y; z -= c.z; return static_cast<Child<T> &>(*this); } PBRT_CPU_GPU bool operator==(const Child<T> &c) const { return x == c.x && y == c.y && z == c.z; } PBRT_CPU_GPU bool operator!=(const Child<T> &c) const { return x != c.x || y != c.y || z != c.z; } template <typename U> PBRT_CPU_GPU auto operator*(U s) const -> Child<decltype(T{} * U{})> { return {s * x, s * y, s * z}; } template <typename U> PBRT_CPU_GPU Child<T> &operator*=(U s) { DCHECK(!IsNaN(s)); x *= s; y *= s; z *= s; return static_cast<Child<T> &>(*this); } template <typename U> PBRT_CPU_GPU auto operator/(U d) const -> Child<decltype(T{} / U{})> { DCHECK_NE(d, 0); return {x / d, y / d, z / d}; } template <typename U> PBRT_CPU_GPU Child<T> &operator/=(U d) { DCHECK_NE(d, 0); x /= d; y /= d; z /= d; return static_cast<Child<T> &>(*this); } PBRT_CPU_GPU Child<T> operator-() const { return {-x, -y, -z}; } std::string ToString() const { return internal::ToString3(x, y, z); } // Tuple3 Public Members T x{}, y{}, z{}; }; // Tuple3 Inline Functions template <template <class> class C, typename T, typename U> PBRT_CPU_GPU inline auto operator*(U s, const Tuple3<C, T> &t) -> C<decltype(T{} * U{})> { return t * s; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Abs(const Tuple3<C, T> &t) { using std::abs; return {abs(t.x), abs(t.y), abs(t.z)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Ceil(const Tuple3<C, T> &t) { using std::ceil; return {ceil(t.x), ceil(t.y), ceil(t.z)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Floor(const Tuple3<C, T> &t) { using std::floor; return {floor(t.x), floor(t.y), floor(t.z)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline auto Lerp(Float t, const Tuple3<C, T> &t0, const Tuple3<C, T> &t1) { return (1 - t) * t0 + t * t1; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> FMA(Float a, const Tuple3<C, T> &b, const Tuple3<C, T> &c) { return {FMA(a, b.x, c.x), FMA(a, b.y, c.y), FMA(a, b.z, c.z)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> FMA(const Tuple3<C, T> &a, Float b, const Tuple3<C, T> &c) { return FMA(b, a, c); } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Min(const Tuple3<C, T> &t1, const Tuple3<C, T> &t2) { using std::min; return {min(t1.x, t2.x), min(t1.y, t2.y), min(t1.z, t2.z)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline T MinComponentValue(const Tuple3<C, T> &t) { using std::min; return min({t.x, t.y, t.z}); } template <template <class> class C, typename T> PBRT_CPU_GPU inline int MinComponentIndex(const Tuple3<C, T> &t) { return (t.x < t.y) ? ((t.x < t.z) ? 0 : 2) : ((t.y < t.z) ? 1 : 2); } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Max(const Tuple3<C, T> &t1, const Tuple3<C, T> &t2) { using std::max; return {max(t1.x, t2.x), max(t1.y, t2.y), max(t1.z, t2.z)}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline T MaxComponentValue(const Tuple3<C, T> &t) { using std::max; return max({t.x, t.y, t.z}); } template <template <class> class C, typename T> PBRT_CPU_GPU inline int MaxComponentIndex(const Tuple3<C, T> &t) { return (t.x > t.y) ? ((t.x > t.z) ? 0 : 2) : ((t.y > t.z) ? 1 : 2); } template <template <class> class C, typename T> PBRT_CPU_GPU inline C<T> Permute(const Tuple3<C, T> &t, pstd::array<int, 3> p) { return {t[p[0]], t[p[1]], t[p[2]]}; } template <template <class> class C, typename T> PBRT_CPU_GPU inline T HProd(const Tuple3<C, T> &t) { return t.x * t.y * t.z; } // Vector2 Definition template <typename T> class Vector2 : public Tuple2<Vector2, T> { public: // Vector2 Public Methods using Tuple2<Vector2, T>::x; using Tuple2<Vector2, T>::y; Vector2() = default; PBRT_CPU_GPU Vector2(T x, T y) : Tuple2<pbrt::Vector2, T>(x, y) {} template <typename U> PBRT_CPU_GPU explicit Vector2(const Point2<U> &p); template <typename U> PBRT_CPU_GPU explicit Vector2(const Vector2<U> &v) : Tuple2<pbrt::Vector2, T>(T(v.x), T(v.y)) {} }; // Vector3 Definition template <typename T> class Vector3 : public Tuple3<Vector3, T> { public: // Vector3 Public Methods using Tuple3<Vector3, T>::x; using Tuple3<Vector3, T>::y; using Tuple3<Vector3, T>::z; Vector3() = default; PBRT_CPU_GPU Vector3(T x, T y, T z) : Tuple3<pbrt::Vector3, T>(x, y, z) {} template <typename U> PBRT_CPU_GPU explicit Vector3(const Vector3<U> &v) : Tuple3<pbrt::Vector3, T>(T(v.x), T(v.y), T(v.z)) {} template <typename U> PBRT_CPU_GPU explicit Vector3(const Point3<U> &p); template <typename U> PBRT_CPU_GPU explicit Vector3(const Normal3<U> &n); }; // Vector2* definitions using Vector2f = Vector2<Float>; using Vector2i = Vector2<int>; // Vector3* definitions using Vector3f = Vector3<Float>; using Vector3i = Vector3<int>; // Vector3fi Definition class Vector3fi : public Vector3<Interval<Float>> { public: // Vector3fi Public Methods using Vector3<Interval<Float>>::x; using Vector3<Interval<Float>>::y; using Vector3<Interval<Float>>::z; using Vector3<Interval<Float>>::HasNaN; using Vector3<Interval<Float>>::operator+; using Vector3<Interval<Float>>::operator+=; using Vector3<Interval<Float>>::operator*; using Vector3<Interval<Float>>::operator*=; Vector3fi() = default; PBRT_CPU_GPU Vector3fi(Float x, Float y, Float z) : Vector3<Interval<Float>>(Interval<Float>(x), Interval<Float>(y), Interval<Float>(z)) {} PBRT_CPU_GPU Vector3fi(FloatInterval x, FloatInterval y, FloatInterval z) : Vector3<Interval<Float>>(x, y, z) {} PBRT_CPU_GPU Vector3fi(const Vector3f &p) : Vector3<Interval<Float>>(Interval<Float>(p.x), Interval<Float>(p.y), Interval<Float>(p.z)) {} template <typename F> PBRT_CPU_GPU Vector3fi(const Vector3<Interval<F>> &pfi) : Vector3<Interval<Float>>(pfi) {} PBRT_CPU_GPU Vector3fi(const Vector3f &p, const Vector3f &e) : Vector3<Interval<Float>>(Interval<Float>::FromValueAndError(p.x, e.x), Interval<Float>::FromValueAndError(p.y, e.y), Interval<Float>::FromValueAndError(p.z, e.z)) {} PBRT_CPU_GPU Vector3f Error() const { return {x.Width() / 2, y.Width() / 2, z.Width() / 2}; } PBRT_CPU_GPU bool IsExact() const { return x.Width() == 0 && y.Width() == 0 && z.Width() == 0; } }; // Point2 Definition template <typename T> class Point2 : public Tuple2<Point2, T> { public: // Point2 Public Methods using Tuple2<Point2, T>::x; using Tuple2<Point2, T>::y; using Tuple2<Point2, T>::HasNaN; using Tuple2<Point2, T>::operator+; using Tuple2<Point2, T>::operator+=; using Tuple2<Point2, T>::operator*; using Tuple2<Point2, T>::operator*=; PBRT_CPU_GPU Point2() { x = y = 0; } PBRT_CPU_GPU Point2(T x, T y) : Tuple2<pbrt::Point2, T>(x, y) {} template <typename U> PBRT_CPU_GPU explicit Point2(const Point2<U> &v) : Tuple2<pbrt::Point2, T>(T(v.x), T(v.y)) {} template <typename U> PBRT_CPU_GPU explicit Point2(const Vector2<U> &v) : Tuple2<pbrt::Point2, T>(T(v.x), T(v.y)) {} template <typename U> PBRT_CPU_GPU auto operator+(const Vector2<U> &v) const -> Point2<decltype(T{} + U{})> { DCHECK(!v.HasNaN()); return {x + v.x, y + v.y}; } template <typename U> PBRT_CPU_GPU Point2<T> &operator+=(const Vector2<U> &v) { DCHECK(!v.HasNaN()); x += v.x; y += v.y; return *this; } // We can't do using operator- above, since we don't want to pull in // the Point-Point -> Point one so that we can return a vector // instead... PBRT_CPU_GPU Point2<T> operator-() const { return {-x, -y}; } template <typename U> PBRT_CPU_GPU auto operator-(const Point2<U> &p) const -> Vector2<decltype(T{} - U{})> { DCHECK(!p.HasNaN()); return {x - p.x, y - p.y}; } template <typename U> PBRT_CPU_GPU auto operator-(const Vector2<U> &v) const -> Point2<decltype(T{} - U{})> { DCHECK(!v.HasNaN()); return {x - v.x, y - v.y}; } template <typename U> PBRT_CPU_GPU Point2<T> &operator-=(const Vector2<U> &v) { DCHECK(!v.HasNaN()); x -= v.x; y -= v.y; return *this; } }; // Point3 Definition template <typename T> class Point3 : public Tuple3<Point3, T> { public: // Point3 Public Methods using Tuple3<Point3, T>::x; using Tuple3<Point3, T>::y; using Tuple3<Point3, T>::z; using Tuple3<Point3, T>::HasNaN; using Tuple3<Point3, T>::operator+; using Tuple3<Point3, T>::operator+=; using Tuple3<Point3, T>::operator*; using Tuple3<Point3, T>::operator*=; Point3() = default; PBRT_CPU_GPU Point3(T x, T y, T z) : Tuple3<pbrt::Point3, T>(x, y, z) {} // We can't do using operator- above, since we don't want to pull in // the Point-Point -> Point one so that we can return a vector // instead... PBRT_CPU_GPU Point3<T> operator-() const { return {-x, -y, -z}; } template <typename U> PBRT_CPU_GPU explicit Point3(const Point3<U> &p) : Tuple3<pbrt::Point3, T>(T(p.x), T(p.y), T(p.z)) {} template <typename U> PBRT_CPU_GPU explicit Point3(const Vector3<U> &v) : Tuple3<pbrt::Point3, T>(T(v.x), T(v.y), T(v.z)) {} template <typename U> PBRT_CPU_GPU auto operator+(const Vector3<U> &v) const -> Point3<decltype(T{} + U{})> { DCHECK(!v.HasNaN()); return {x + v.x, y + v.y, z + v.z}; } template <typename U> PBRT_CPU_GPU Point3<T> &operator+=(const Vector3<U> &v) { DCHECK(!v.HasNaN()); x += v.x; y += v.y; z += v.z; return *this; } template <typename U> PBRT_CPU_GPU auto operator-(const Vector3<U> &v) const -> Point3<decltype(T{} - U{})> { DCHECK(!v.HasNaN()); return {x - v.x, y - v.y, z - v.z}; } template <typename U> PBRT_CPU_GPU Point3<T> &operator-=(const Vector3<U> &v) { DCHECK(!v.HasNaN()); x -= v.x; y -= v.y; z -= v.z; return *this; } template <typename U> PBRT_CPU_GPU auto operator-(const Point3<U> &p) const -> Vector3<decltype(T{} - U{})> { DCHECK(!p.HasNaN()); return {x - p.x, y - p.y, z - p.z}; } }; // Point2* Definitions using Point2f = Point2<Float>; using Point2i = Point2<int>; // Point3* Definitions using Point3f = Point3<Float>; using Point3i = Point3<int>; // Point3fi Definition class Point3fi : public Point3<FloatInterval> { public: using Point3<FloatInterval>::x; using Point3<FloatInterval>::y; using Point3<FloatInterval>::z; using Point3<FloatInterval>::HasNaN; using Point3<FloatInterval>::operator+; using Point3<FloatInterval>::operator*; using Point3<FloatInterval>::operator*=; Point3fi() = default; PBRT_CPU_GPU Point3fi(FloatInterval x, FloatInterval y, FloatInterval z) : Point3<FloatInterval>(x, y, z) {} PBRT_CPU_GPU Point3fi(Float x, Float y, Float z) : Point3<FloatInterval>(FloatInterval(x), FloatInterval(y), FloatInterval(z)) {} PBRT_CPU_GPU Point3fi(const Point3f &p) : Point3<FloatInterval>(FloatInterval(p.x), FloatInterval(p.y), FloatInterval(p.z)) {} template <typename F> PBRT_CPU_GPU Point3fi(const Point3<Interval<F>> &pfi) : Point3<FloatInterval>(pfi) {} PBRT_CPU_GPU Point3fi(const Point3f &p, const Vector3f &e) : Point3<FloatInterval>(FloatInterval::FromValueAndError(p.x, e.x), FloatInterval::FromValueAndError(p.y, e.y), FloatInterval::FromValueAndError(p.z, e.z)) {} PBRT_CPU_GPU Vector3f Error() const { return {x.Width() / 2, y.Width() / 2, z.Width() / 2}; } PBRT_CPU_GPU bool IsExact() const { return x.Width() == 0 && y.Width() == 0 && z.Width() == 0; } // Meh--can't seem to get these from Point3 via using declarations... template <typename U> PBRT_CPU_GPU Point3fi operator+(const Vector3<U> &v) const { DCHECK(!v.HasNaN()); return {x + v.x, y + v.y, z + v.z}; } template <typename U> PBRT_CPU_GPU Point3fi &operator+=(const Vector3<U> &v) { DCHECK(!v.HasNaN()); x += v.x; y += v.y; z += v.z; return *this; } PBRT_CPU_GPU Point3fi operator-() const { return {-x, -y, -z}; } template <typename U> PBRT_CPU_GPU Point3fi operator-(const Point3<U> &p) const { DCHECK(!p.HasNaN()); return {x - p.x, y - p.y, z - p.z}; } template <typename U> PBRT_CPU_GPU Point3fi operator-(const Vector3<U> &v) const { DCHECK(!v.HasNaN()); return {x - v.x, y - v.y, z - v.z}; } template <typename U> PBRT_CPU_GPU Point3fi &operator-=(const Vector3<U> &v) { DCHECK(!v.HasNaN()); x -= v.x; y -= v.y; z -= v.z; return *this; } }; // Normal3 Definition template <typename T> class Normal3 : public Tuple3<Normal3, T> { public: // Normal3 Public Methods using Tuple3<Normal3, T>::x; using Tuple3<Normal3, T>::y; using Tuple3<Normal3, T>::z; using Tuple3<Normal3, T>::HasNaN; using Tuple3<Normal3, T>::operator+; using Tuple3<Normal3, T>::operator*; using Tuple3<Normal3, T>::operator*=; Normal3() = default; PBRT_CPU_GPU Normal3(T x, T y, T z) : Tuple3<pbrt::Normal3, T>(x, y, z) {} template <typename U> PBRT_CPU_GPU explicit Normal3<T>(const Normal3<U> &v) : Tuple3<pbrt::Normal3, T>(T(v.x), T(v.y), T(v.z)) {} template <typename U> PBRT_CPU_GPU explicit Normal3<T>(const Vector3<U> &v) : Tuple3<pbrt::Normal3, T>(T(v.x), T(v.y), T(v.z)) {} }; using Normal3f = Normal3<Float>; // Quaternion Definition class Quaternion { public: // Quaternion Public Methods Quaternion() = default; PBRT_CPU_GPU Quaternion &operator+=(const Quaternion &q) { v += q.v; w += q.w; return *this; } PBRT_CPU_GPU Quaternion operator+(const Quaternion &q) const { return {v + q.v, w + q.w}; } PBRT_CPU_GPU Quaternion &operator-=(const Quaternion &q) { v -= q.v; w -= q.w; return *this; } PBRT_CPU_GPU Quaternion operator-() const { return {-v, -w}; } PBRT_CPU_GPU Quaternion operator-(const Quaternion &q) const { return {v - q.v, w - q.w}; } PBRT_CPU_GPU Quaternion &operator*=(Float f) { v *= f; w *= f; return *this; } PBRT_CPU_GPU Quaternion operator*(Float f) const { return {v * f, w * f}; } PBRT_CPU_GPU Quaternion &operator/=(Float f) { DCHECK_NE(0, f); v /= f; w /= f; return *this; } PBRT_CPU_GPU Quaternion operator/(Float f) const { DCHECK_NE(0, f); return {v / f, w / f}; } std::string ToString() const; // Quaternion Public Members Vector3f v; Float w = 1; }; // Vector2 Inline Functions template <typename T> template <typename U> Vector2<T>::Vector2(const Point2<U> &p) : Tuple2<pbrt::Vector2, T>(T(p.x), T(p.y)) {} // TODO: book discuss why Dot() and not e.g. a.Dot(b) template <typename T> PBRT_CPU_GPU inline auto Dot(const Vector2<T> &v1, const Vector2<T> &v2) -> typename TupleLength<T>::type { DCHECK(!v1.HasNaN() && !v2.HasNaN()); return SumOfProducts(v1.x, v2.x, v1.y, v2.y); } template <typename T> PBRT_CPU_GPU inline auto AbsDot(const Vector2<T> &v1, const Vector2<T> &v2) -> typename TupleLength<T>::type { DCHECK(!v1.HasNaN() && !v2.HasNaN()); return std::abs(Dot(v1, v2)); } template <typename T> PBRT_CPU_GPU inline auto LengthSquared(const Vector2<T> &v) -> typename TupleLength<T>::type { return Sqr(v.x) + Sqr(v.y); } template <typename T> PBRT_CPU_GPU inline auto Length(const Vector2<T> &v) -> typename TupleLength<T>::type { using std::sqrt; return sqrt(LengthSquared(v)); } template <typename T> PBRT_CPU_GPU inline auto Normalize(const Vector2<T> &v) -> Vector2<typename TupleLength<T>::type> { return v / Length(v); } template <typename T> PBRT_CPU_GPU inline auto Distance(const Point2<T> &p1, const Point2<T> &p2) -> typename TupleLength<T>::type { return Length(p1 - p2); } template <typename T> PBRT_CPU_GPU inline auto DistanceSquared(const Point2<T> &p1, const Point2<T> &p2) -> typename TupleLength<T>::type { return LengthSquared(p1 - p2); } // Vector3 Inline Functions template <typename T> template <typename U> Vector3<T>::Vector3(const Point3<U> &p) : Tuple3<pbrt::Vector3, T>(T(p.x), T(p.y), T(p.z)) {} template <typename T> PBRT_CPU_GPU inline Vector3<T> Cross(const Vector3<T> &v1, const Normal3<T> &v2) { DCHECK(!v1.HasNaN() && !v2.HasNaN()); return {DifferenceOfProducts(v1.y, v2.z, v1.z, v2.y), DifferenceOfProducts(v1.z, v2.x, v1.x, v2.z), DifferenceOfProducts(v1.x, v2.y, v1.y, v2.x)}; } template <typename T> PBRT_CPU_GPU inline Vector3<T> Cross(const Normal3<T> &v1, const Vector3<T> &v2) { DCHECK(!v1.HasNaN() && !v2.HasNaN()); return {DifferenceOfProducts(v1.y, v2.z, v1.z, v2.y), DifferenceOfProducts(v1.z, v2.x, v1.x, v2.z), DifferenceOfProducts(v1.x, v2.y, v1.y, v2.x)}; } template <typename T> PBRT_CPU_GPU inline T LengthSquared(const Vector3<T> &v) { return v.x * v.x + v.y * v.y + v.z * v.z; } template <typename T> PBRT_CPU_GPU inline auto Length(const Vector3<T> &v) -> typename TupleLength<T>::type { using std::sqrt; return sqrt(LengthSquared(v)); } template <typename T> PBRT_CPU_GPU inline Vector3<T> Normalize(const Vector3<T> &v) { return v / Length(v); } template <typename T> PBRT_CPU_GPU inline T Dot(const Vector3<T> &v, const Vector3<T> &w) { DCHECK(!v.HasNaN() && !w.HasNaN()); return v.x * w.x + v.y * w.y + v.z * w.z; } // Equivalent to std::acos(Dot(a, b)), but more numerically stable. // via http://www.plunk.org/~hatch/rightway.php template <typename T> PBRT_CPU_GPU inline Float AngleBetween(const Vector3<T> &v1, const Vector3<T> &v2) { if (Dot(v1, v2) < 0) return Pi - 2 * SafeASin(Length(v1 + v2) / 2); else return 2 * SafeASin(Length(v2 - v1) / 2); } template <typename T> PBRT_CPU_GPU inline T AbsDot(const Vector3<T> &v1, const Vector3<T> &v2) { DCHECK(!v1.HasNaN() && !v2.HasNaN()); return std::abs(Dot(v1, v2)); } template <typename T> PBRT_CPU_GPU inline Float AngleBetween(const Normal3<T> &a, const Normal3<T> &b) { if (Dot(a, b) < 0) return Pi - 2 * SafeASin(Length(a + b) / 2); else return 2 * SafeASin(Length(b - a) / 2); } template <typename T> PBRT_CPU_GPU inline Vector3<T> GramSchmidt(const Vector3<T> &a, const Vector3<T> &b) { return a - Dot(a, b) * b; } template <typename T> PBRT_CPU_GPU inline Vector3<T> Cross(const Vector3<T> &v, const Vector3<T> &w) { DCHECK(!v.HasNaN() && !w.HasNaN()); return {DifferenceOfProducts(v.y, w.z, v.z, w.y), DifferenceOfProducts(v.z, w.x, v.x, w.z), DifferenceOfProducts(v.x, w.y, v.y, w.x)}; } template <typename T> PBRT_CPU_GPU inline void CoordinateSystem(const Vector3<T> &v1, Vector3<T> *v2, Vector3<T> *v3) { Float sign = std::copysign(Float(1), v1.z); Float a = -1 / (sign + v1.z); Float b = v1.x * v1.y * a; *v2 = Vector3<T>(1 + sign * v1.x * v1.x * a, sign * b, -sign * v1.x); *v3 = Vector3<T>(b, sign + v1.y * v1.y * a, -v1.y); } template <typename T> PBRT_CPU_GPU inline void CoordinateSystem(const Normal3<T> &v1, Vector3<T> *v2, Vector3<T> *v3) { Float sign = std::copysign(Float(1), v1.z); Float a = -1 / (sign + v1.z); Float b = v1.x * v1.y * a; *v2 = Vector3<T>(1 + sign * v1.x * v1.x * a, sign * b, -sign * v1.x); *v3 = Vector3<T>(b, sign + v1.y * v1.y * a, -v1.y); } template <typename T> template <typename U> Vector3<T>::Vector3(const Normal3<U> &n) : Tuple3<pbrt::Vector3, T>(T(n.x), T(n.y), T(n.z)) {} // Point3 Inline Functions template <typename T> PBRT_CPU_GPU inline auto Distance(const Point3<T> &p1, const Point3<T> &p2) { return Length(p1 - p2); } template <typename T> PBRT_CPU_GPU inline auto DistanceSquared(const Point3<T> &p1, const Point3<T> &p2) { return LengthSquared(p1 - p2); } // Normal3 Inline Functions template <typename T> PBRT_CPU_GPU inline auto LengthSquared(const Normal3<T> &n) -> typename TupleLength<T>::type { return Sqr(n.x) + Sqr(n.y) + Sqr(n.z); } template <typename T> PBRT_CPU_GPU inline auto Length(const Normal3<T> &n) -> typename TupleLength<T>::type { using std::sqrt; return sqrt(LengthSquared(n)); } template <typename T> PBRT_CPU_GPU inline auto Normalize(const Normal3<T> &n) -> Normal3<typename TupleLength<T>::type> { return n / Length(n); } template <typename T> PBRT_CPU_GPU inline auto Dot(const Normal3<T> &n, const Vector3<T> &v) -> typename TupleLength<T>::type { DCHECK(!n.HasNaN() && !v.HasNaN()); return FMA(n.x, v.x, SumOfProducts(n.y, v.y, n.z, v.z)); } template <typename T> PBRT_CPU_GPU inline auto Dot(const Vector3<T> &v, const Normal3<T> &n) -> typename TupleLength<T>::type { DCHECK(!v.HasNaN() && !n.HasNaN()); return FMA(n.x, v.x, SumOfProducts(n.y, v.y, n.z, v.z)); } template <typename T> PBRT_CPU_GPU inline auto Dot(const Normal3<T> &n1, const Normal3<T> &n2) -> typename TupleLength<T>::type { DCHECK(!n1.HasNaN() && !n2.HasNaN()); return FMA(n1.x, n2.x, SumOfProducts(n1.y, n2.y, n1.z, n2.z)); } template <typename T> PBRT_CPU_GPU inline auto AbsDot(const Normal3<T> &n, const Vector3<T> &v) -> typename TupleLength<T>::type { DCHECK(!n.HasNaN() && !v.HasNaN()); return std::abs(Dot(n, v)); } template <typename T> PBRT_CPU_GPU inline auto AbsDot(const Vector3<T> &v, const Normal3<T> &n) -> typename TupleLength<T>::type { using std::abs; DCHECK(!v.HasNaN() && !n.HasNaN()); return abs(Dot(v, n)); } template <typename T> PBRT_CPU_GPU inline auto AbsDot(const Normal3<T> &n1, const Normal3<T> &n2) -> typename TupleLength<T>::type { using std::abs; DCHECK(!n1.HasNaN() && !n2.HasNaN()); return abs(Dot(n1, n2)); } template <typename T> PBRT_CPU_GPU inline Normal3<T> FaceForward(const Normal3<T> &n, const Vector3<T> &v) { return (Dot(n, v) < 0.f) ? -n : n; } template <typename T> PBRT_CPU_GPU inline Normal3<T> FaceForward(const Normal3<T> &n, const Normal3<T> &n2) { return (Dot(n, n2) < 0.f) ? -n : n; } template <typename T> PBRT_CPU_GPU inline Vector3<T> FaceForward(const Vector3<T> &v, const Vector3<T> &v2) { return (Dot(v, v2) < 0.f) ? -v : v; } template <typename T> PBRT_CPU_GPU inline Vector3<T> FaceForward(const Vector3<T> &v, const Normal3<T> &n2) { return (Dot(v, n2) < 0.f) ? -v : v; } // Quaternion Inline Functions PBRT_CPU_GPU inline Quaternion operator*(Float f, const Quaternion &q) { return q * f; } PBRT_CPU_GPU inline Float Dot(const Quaternion &q1, const Quaternion &q2) { return Dot(q1.v, q2.v) + q1.w * q2.w; } PBRT_CPU_GPU inline Float Length(const Quaternion &q) { return std::sqrt(Dot(q, q)); } PBRT_CPU_GPU inline Quaternion Normalize(const Quaternion &q) { DCHECK_GT(Length(q), 0); return q / Length(q); } PBRT_CPU_GPU inline Float AngleBetween(const Quaternion &q1, const Quaternion &q2) { if (Dot(q1, q2) < 0) return Pi - 2 * SafeASin(Length(q1 + q2) / 2); else return 2 * SafeASin(Length(q2 - q1) / 2); } // http://www.plunk.org/~hatch/rightway.php PBRT_CPU_GPU inline Quaternion Slerp(Float t, const Quaternion &q1, const Quaternion &q2) { Float theta = AngleBetween(q1, q2); Float sinThetaOverTheta = SinXOverX(theta); return q1 * (1 - t) * SinXOverX((1 - t) * theta) / sinThetaOverTheta + q2 * t * SinXOverX(t * theta) / sinThetaOverTheta; } // Bounds2 Definition template <typename T> class Bounds2 { public: // Bounds2 Public Methods PBRT_CPU_GPU Bounds2() { T minNum = std::numeric_limits<T>::lowest(); T maxNum = std::numeric_limits<T>::max(); pMin = Point2<T>(maxNum, maxNum); pMax = Point2<T>(minNum, minNum); } PBRT_CPU_GPU explicit Bounds2(const Point2<T> &p) : pMin(p), pMax(p) {} PBRT_CPU_GPU Bounds2(const Point2<T> &p1, const Point2<T> &p2) : pMin(Min(p1, p2)), pMax(Max(p1, p2)) {} template <typename U> PBRT_CPU_GPU explicit Bounds2(const Bounds2<U> &b) { if (b.IsEmpty()) // Be careful about overflowing float->int conversions and the // like. *this = Bounds2<T>(); else { pMin = Point2<T>(b.pMin); pMax = Point2<T>(b.pMax); } } PBRT_CPU_GPU Vector2<T> Diagonal() const { return pMax - pMin; } PBRT_CPU_GPU T Area() const { Vector2<T> d = pMax - pMin; return d.x * d.y; } PBRT_CPU_GPU bool IsEmpty() const { return pMin.x >= pMax.x || pMin.y >= pMax.y; } PBRT_CPU_GPU bool IsDegenerate() const { return pMin.x > pMax.x || pMin.y > pMax.y; } PBRT_CPU_GPU int MaxDimension() const { Vector2<T> diag = Diagonal(); if (diag.x > diag.y) return 0; else return 1; } PBRT_CPU_GPU const Point2<T> &operator[](int i) const { DCHECK(i == 0 || i == 1); return (i == 0) ? pMin : pMax; } PBRT_CPU_GPU Point2<T> &operator[](int i) { DCHECK(i == 0 || i == 1); return (i == 0) ? pMin : pMax; } PBRT_CPU_GPU bool operator==(const Bounds2<T> &b) const { return b.pMin == pMin && b.pMax == pMax; } PBRT_CPU_GPU bool operator!=(const Bounds2<T> &b) const { return b.pMin != pMin || b.pMax != pMax; } PBRT_CPU_GPU Point2<T> Corner(int corner) const { DCHECK(corner >= 0 && corner < 4); return Point2<T>((*this)[(corner & 1)].x, (*this)[(corner & 2) ? 1 : 0].y); } PBRT_CPU_GPU Point2<T> Lerp(const Point2f &t) const { return Point2<T>(pbrt::Lerp(t.x, pMin.x, pMax.x), pbrt::Lerp(t.y, pMin.y, pMax.y)); } PBRT_CPU_GPU Vector2<T> Offset(const Point2<T> &p) const { Vector2<T> o = p - pMin; if (pMax.x > pMin.x) o.x /= pMax.x - pMin.x; if (pMax.y > pMin.y) o.y /= pMax.y - pMin.y; return o; } PBRT_CPU_GPU void BoundingSphere(Point2<T> *c, Float *rad) const { *c = (pMin + pMax) / 2; *rad = Inside(*c, *this) ? Distance(*c, pMax) : 0; } std::string ToString() const { return StringPrintf("[ %s - %s ]", pMin, pMax); } // Bounds2 Public Members Point2<T> pMin, pMax; }; // Bounds3 Definition template <typename T> class Bounds3 { public: // Bounds3 Public Methods PBRT_CPU_GPU Bounds3() { T minNum = std::numeric_limits<T>::lowest(); T maxNum = std::numeric_limits<T>::max(); pMin = Point3<T>(maxNum, maxNum, maxNum); pMax = Point3<T>(minNum, minNum, minNum); } PBRT_CPU_GPU explicit Bounds3(const Point3<T> &p) : pMin(p), pMax(p) {} PBRT_CPU_GPU Bounds3(const Point3<T> &p1, const Point3<T> &p2) : pMin(Min(p1, p2)), pMax(Max(p1, p2)) {} PBRT_CPU_GPU const Point3<T> &operator[](int i) const { DCHECK(i == 0 || i == 1); return (i == 0) ? pMin : pMax; } PBRT_CPU_GPU Point3<T> &operator[](int i) { DCHECK(i == 0 || i == 1); return (i == 0) ? pMin : pMax; } PBRT_CPU_GPU Point3<T> Corner(int corner) const { DCHECK(corner >= 0 && corner < 8); return Point3<T>((*this)[(corner & 1)].x, (*this)[(corner & 2) ? 1 : 0].y, (*this)[(corner & 4) ? 1 : 0].z); } PBRT_CPU_GPU Vector3<T> Diagonal() const { return pMax - pMin; } PBRT_CPU_GPU T SurfaceArea() const { Vector3<T> d = Diagonal(); return 2 * (d.x * d.y + d.x * d.z + d.y * d.z); } PBRT_CPU_GPU T Volume() const { Vector3<T> d = Diagonal(); return d.x * d.y * d.z; } PBRT_CPU_GPU int MaxDimension() const { Vector3<T> d = Diagonal(); if (d.x > d.y && d.x > d.z) return 0; else if (d.y > d.z) return 1; else return 2; } PBRT_CPU_GPU Point3<T> Lerp(const Point3f &t) const { return Point3<T>(pbrt::Lerp(t.x, pMin.x, pMax.x), pbrt::Lerp(t.y, pMin.y, pMax.y), pbrt::Lerp(t.z, pMin.z, pMax.z)); } PBRT_CPU_GPU Vector3<T> Offset(const Point3<T> &p) const { Vector3<T> o = p - pMin; if (pMax.x > pMin.x) o.x /= pMax.x - pMin.x; if (pMax.y > pMin.y) o.y /= pMax.y - pMin.y; if (pMax.z > pMin.z) o.z /= pMax.z - pMin.z; return o; } PBRT_CPU_GPU void BoundingSphere(Point3<T> *center, Float *radius) const { *center = (pMin + pMax) / 2; *radius = Inside(*center, *this) ? Distance(*center, pMax) : 0; } PBRT_CPU_GPU bool IsEmpty() const { return pMin.x >= pMax.x || pMin.y >= pMax.y || pMin.z >= pMax.z; } PBRT_CPU_GPU bool IsDegenerate() const { return pMin.x > pMax.x || pMin.y > pMax.y || pMin.z > pMax.z; } template <typename U> PBRT_CPU_GPU explicit Bounds3(const Bounds3<U> &b) { if (b.IsEmpty()) // Be careful about overflowing float->int conversions and the // like. *this = Bounds3<T>(); else { pMin = Point3<T>(b.pMin); pMax = Point3<T>(b.pMax); } } PBRT_CPU_GPU bool operator==(const Bounds3<T> &b) const { return b.pMin == pMin && b.pMax == pMax; } PBRT_CPU_GPU bool operator!=(const Bounds3<T> &b) const { return b.pMin != pMin || b.pMax != pMax; } PBRT_CPU_GPU bool IntersectP(const Point3f &o, const Vector3f &d, Float tMax = Infinity, Float *hitt0 = nullptr, Float *hitt1 = nullptr) const; PBRT_CPU_GPU bool IntersectP(const Point3f &o, const Vector3f &d, Float tMax, const Vector3f &invDir, const int dirIsNeg[3]) const; std::string ToString() const { return StringPrintf("[ %s - %s ]", pMin, pMax); } // Bounds3 Public Members Point3<T> pMin, pMax; }; // Bounds[23][fi] Definitions using Bounds2f = Bounds2<Float>; using Bounds2i = Bounds2<int>; using Bounds3f = Bounds3<Float>; using Bounds3i = Bounds3<int>; class Bounds2iIterator : public std::forward_iterator_tag { public: PBRT_CPU_GPU Bounds2iIterator(const Bounds2i &b, const Point2i &pt) : p(pt), bounds(&b) {} PBRT_CPU_GPU Bounds2iIterator operator++() { advance(); return *this; } PBRT_CPU_GPU Bounds2iIterator operator++(int) { Bounds2iIterator old = *this; advance(); return old; } PBRT_CPU_GPU bool operator==(const Bounds2iIterator &bi) const { return p == bi.p && bounds == bi.bounds; } PBRT_CPU_GPU bool operator!=(const Bounds2iIterator &bi) const { return p != bi.p || bounds != bi.bounds; } PBRT_CPU_GPU Point2i operator*() const { return p; } private: PBRT_CPU_GPU void advance() { ++p.x; if (p.x == bounds->pMax.x) { p.x = bounds->pMin.x; ++p.y; } } Point2i p; const Bounds2i *bounds; }; // Bounds2 Inline Functions template <typename T> PBRT_CPU_GPU inline Bounds2<T> Union(const Bounds2<T> &b1, const Bounds2<T> &b2) { // Be careful to not run the two-point Bounds constructor. Bounds2<T> ret; ret.pMin = Min(b1.pMin, b2.pMin); ret.pMax = Max(b1.pMax, b2.pMax); return ret; } template <typename T> PBRT_CPU_GPU inline Bounds2<T> Intersect(const Bounds2<T> &b1, const Bounds2<T> &b2) { // Be careful to not run the two-point Bounds constructor. Bounds2<T> b; b.pMin = Max(b1.pMin, b2.pMin); b.pMax = Min(b1.pMax, b2.pMax); return b; } template <typename T> PBRT_CPU_GPU inline bool Overlaps(const Bounds2<T> &ba, const Bounds2<T> &bb) { bool x = (ba.pMax.x >= bb.pMin.x) && (ba.pMin.x <= bb.pMax.x); bool y = (ba.pMax.y >= bb.pMin.y) && (ba.pMin.y <= bb.pMax.y); return (x && y); } template <typename T> PBRT_CPU_GPU inline bool Inside(const Point2<T> &pt, const Bounds2<T> &b) { return (pt.x >= b.pMin.x && pt.x <= b.pMax.x && pt.y >= b.pMin.y && pt.y <= b.pMax.y); } template <typename T> PBRT_CPU_GPU inline bool Inside(const Bounds2<T> &ba, const Bounds2<T> &bb) { return (ba.pMin.x >= bb.pMin.x && ba.pMax.x <= bb.pMax.x && ba.pMin.y >= bb.pMin.y && ba.pMax.y <= bb.pMax.y); } template <typename T> PBRT_CPU_GPU inline bool InsideExclusive(const Point2<T> &pt, const Bounds2<T> &b) { return (pt.x >= b.pMin.x && pt.x < b.pMax.x && pt.y >= b.pMin.y && pt.y < b.pMax.y); } template <typename T, typename U> PBRT_CPU_GPU inline Bounds2<T> Expand(const Bounds2<T> &b, U delta) { Bounds2<T> ret; ret.pMin = b.pMin - Vector2<T>(delta, delta); ret.pMax = b.pMax + Vector2<T>(delta, delta); return ret; } // Bounds3 Inline Functions template <typename T> PBRT_CPU_GPU inline Bounds3<T> Union(const Bounds3<T> &b, const Point3<T> &p) { Bounds3<T> ret; ret.pMin = Min(b.pMin, p); ret.pMax = Max(b.pMax, p); return ret; } template <typename T> PBRT_CPU_GPU inline Bounds3<T> Union(const Bounds3<T> &b1, const Bounds3<T> &b2) { Bounds3<T> ret; ret.pMin = Min(b1.pMin, b2.pMin); ret.pMax = Max(b1.pMax, b2.pMax); return ret; } template <typename T> PBRT_CPU_GPU inline Bounds3<T> Intersect(const Bounds3<T> &b1, const Bounds3<T> &b2) { Bounds3<T> b; b.pMin = Max(b1.pMin, b2.pMin); b.pMax = Min(b1.pMax, b2.pMax); return b; } template <typename T> PBRT_CPU_GPU inline bool Overlaps(const Bounds3<T> &b1, const Bounds3<T> &b2) { bool x = (b1.pMax.x >= b2.pMin.x) && (b1.pMin.x <= b2.pMax.x); bool y = (b1.pMax.y >= b2.pMin.y) && (b1.pMin.y <= b2.pMax.y); bool z = (b1.pMax.z >= b2.pMin.z) && (b1.pMin.z <= b2.pMax.z); return (x && y && z); } template <typename T> PBRT_CPU_GPU inline bool Inside(const Point3<T> &p, const Bounds3<T> &b) { return (p.x >= b.pMin.x && p.x <= b.pMax.x && p.y >= b.pMin.y && p.y <= b.pMax.y && p.z >= b.pMin.z && p.z <= b.pMax.z); } template <typename T> PBRT_CPU_GPU inline bool InsideExclusive(const Point3<T> &p, const Bounds3<T> &b) { return (p.x >= b.pMin.x && p.x < b.pMax.x && p.y >= b.pMin.y && p.y < b.pMax.y && p.z >= b.pMin.z && p.z < b.pMax.z); } template <typename T, typename U> PBRT_CPU_GPU inline auto DistanceSquared(const Point3<T> &p, const Bounds3<U> &b) { using TDist = decltype(T{} - U{}); TDist dx = std::max<TDist>({0, b.pMin.x - p.x, p.x - b.pMax.x}); TDist dy = std::max<TDist>({0, b.pMin.y - p.y, p.y - b.pMax.y}); TDist dz = std::max<TDist>({0, b.pMin.z - p.z, p.z - b.pMax.z}); return dx * dx + dy * dy + dz * dz; } template <typename T, typename U> PBRT_CPU_GPU inline auto Distance(const Point3<T> &p, const Bounds3<U> &b) { auto dist2 = DistanceSquared(p, b); using TDist = typename TupleLength<decltype(dist2)>::type; return std::sqrt(TDist(dist2)); } template <typename T, typename U> PBRT_CPU_GPU inline Bounds3<T> Expand(const Bounds3<T> &b, U delta) { Bounds3<T> ret; ret.pMin = b.pMin - Vector3<T>(delta, delta, delta); ret.pMax = b.pMax + Vector3<T>(delta, delta, delta); return ret; } template <typename T> PBRT_CPU_GPU inline bool Bounds3<T>::IntersectP(const Point3f &o, const Vector3f &d, Float tMax, Float *hitt0, Float *hitt1) const { Float t0 = 0, t1 = tMax; for (int i = 0; i < 3; ++i) { // Update interval for _i_th bounding box slab Float invRayDir = 1 / d[i]; Float tNear = (pMin[i] - o[i]) * invRayDir; Float tFar = (pMax[i] - o[i]) * invRayDir; // Update parametric interval from slab intersection $t$ values if (tNear > tFar) pstd::swap(tNear, tFar); // Update _tFar_ to ensure robust ray--bounds intersection tFar *= 1 + 2 * gamma(3); t0 = tNear > t0 ? tNear : t0; t1 = tFar < t1 ? tFar : t1; if (t0 > t1) return false; } if (hitt0) *hitt0 = t0; if (hitt1) *hitt1 = t1; return true; } template <typename T> PBRT_CPU_GPU inline bool Bounds3<T>::IntersectP(const Point3f &o, const Vector3f &d, Float raytMax, const Vector3f &invDir, const int dirIsNeg[3]) const { const Bounds3f &bounds = *this; // Check for ray intersection against $x$ and $y$ slabs Float tMin = (bounds[dirIsNeg[0]].x - o.x) * invDir.x; Float tMax = (bounds[1 - dirIsNeg[0]].x - o.x) * invDir.x; Float tyMin = (bounds[dirIsNeg[1]].y - o.y) * invDir.y; Float tyMax = (bounds[1 - dirIsNeg[1]].y - o.y) * invDir.y; // Update _tMax_ and _tyMax_ to ensure robust bounds intersection tMax *= 1 + 2 * gamma(3); tyMax *= 1 + 2 * gamma(3); if (tMin > tyMax || tyMin > tMax) return false; if (tyMin > tMin) tMin = tyMin; if (tyMax < tMax) tMax = tyMax; // Check for ray intersection against $z$ slab Float tzMin = (bounds[dirIsNeg[2]].z - o.z) * invDir.z; Float tzMax = (bounds[1 - dirIsNeg[2]].z - o.z) * invDir.z; // Update _tzMax_ to ensure robust bounds intersection tzMax *= 1 + 2 * gamma(3); if (tMin > tzMax || tzMin > tMax) return false; if (tzMin > tMin) tMin = tzMin; if (tzMax < tMax) tMax = tzMax; return (tMin < raytMax) && (tMax > 0); } PBRT_CPU_GPU inline Bounds2iIterator begin(const Bounds2i &b) { return Bounds2iIterator(b, b.pMin); } PBRT_CPU_GPU inline Bounds2iIterator end(const Bounds2i &b) { // Normally, the ending point is at the minimum x value and one past // the last valid y value. Point2i pEnd(b.pMin.x, b.pMax.y); // However, if the bounds are degenerate, override the end point to // equal the start point so that any attempt to iterate over the bounds // exits out immediately. if (b.pMin.x >= b.pMax.x || b.pMin.y >= b.pMax.y) pEnd = b.pMin; return Bounds2iIterator(b, pEnd); } template <typename T> PBRT_CPU_GPU inline Bounds2<T> Union(const Bounds2<T> &b, const Point2<T> &p) { // Be careful to not run the two-point Bounds constructor. Bounds2<T> ret; ret.pMin = Min(b.pMin, p); ret.pMax = Max(b.pMax, p); return ret; } // Spherical Geometry Inline Functions PBRT_CPU_GPU inline Vector3f SphericalDirection(Float sinTheta, Float cosTheta, Float phi) { DCHECK(sinTheta >= -1.0001 && sinTheta <= 1.0001); DCHECK(cosTheta >= -1.0001 && cosTheta <= 1.0001); return Vector3f(Clamp(sinTheta, -1, 1) * std::cos(phi), Clamp(sinTheta, -1, 1) * std::sin(phi), Clamp(cosTheta, -1, 1)); } PBRT_CPU_GPU inline Float SphericalTheta(const Vector3f &v) { return SafeACos(v.z); } PBRT_CPU_GPU inline Float SphericalPhi(const Vector3f &v) { Float p = std::atan2(v.y, v.x); return (p < 0) ? (p + 2 * Pi) : p; } PBRT_CPU_GPU inline Float SphericalTriangleArea(const Vector3f &a, const Vector3f &b, const Vector3f &c) { // Compute normalized cross products of all direction pairs Vector3f n_ab = Cross(a, b), n_bc = Cross(b, c), n_ca = Cross(c, a); if (LengthSquared(n_ab) == 0 || LengthSquared(n_bc) == 0 || LengthSquared(n_ca) == 0) return {}; n_ab = Normalize(n_ab); n_bc = Normalize(n_bc); n_ca = Normalize(n_ca); // Compute angles $\alpha$, $\beta$, and $\gamma$ at spherical triangle vertices Float alpha = AngleBetween(n_ab, -n_ca); Float beta = AngleBetween(n_bc, -n_ab); Float gamma = AngleBetween(n_ca, -n_bc); return std::abs(alpha + beta + gamma - Pi); } PBRT_CPU_GPU inline Float SphericalQuadArea(const Vector3f &a, const Vector3f &b, const Vector3f &c, const Vector3f &d); PBRT_CPU_GPU inline Float SphericalQuadArea(const Vector3f &a, const Vector3f &b, const Vector3f &c, const Vector3f &d) { Vector3f axb = Cross(a, b), bxc = Cross(b, c); Vector3f cxd = Cross(c, d), dxa = Cross(d, a); if (LengthSquared(axb) == 0 || LengthSquared(bxc) == 0 || LengthSquared(cxd) == 0 || LengthSquared(dxa) == 0) return 0; axb = Normalize(axb); bxc = Normalize(bxc); cxd = Normalize(cxd); dxa = Normalize(dxa); Float alpha = AngleBetween(dxa, -axb); Float beta = AngleBetween(axb, -bxc); Float gamma = AngleBetween(bxc, -cxd); Float delta = AngleBetween(cxd, -dxa); return std::abs(alpha + beta + gamma + delta - 2 * Pi); } PBRT_CPU_GPU inline Float CosTheta(const Vector3f &w) { return w.z; } PBRT_CPU_GPU inline Float Cos2Theta(const Vector3f &w) { return w.z * w.z; } PBRT_CPU_GPU inline Float AbsCosTheta(const Vector3f &w) { return std::abs(w.z); } PBRT_CPU_GPU inline Float Sin2Theta(const Vector3f &w) { return std::max<Float>(0, 1 - Cos2Theta(w)); } PBRT_CPU_GPU inline Float SinTheta(const Vector3f &w) { return std::sqrt(Sin2Theta(w)); } PBRT_CPU_GPU inline Float TanTheta(const Vector3f &w) { return SinTheta(w) / CosTheta(w); } PBRT_CPU_GPU inline Float Tan2Theta(const Vector3f &w) { return Sin2Theta(w) / Cos2Theta(w); } PBRT_CPU_GPU inline Float CosPhi(const Vector3f &w) { Float sinTheta = SinTheta(w); return (sinTheta == 0) ? 1 : Clamp(w.x / sinTheta, -1, 1); } PBRT_CPU_GPU inline Float SinPhi(const Vector3f &w) { Float sinTheta = SinTheta(w); return (sinTheta == 0) ? 0 : Clamp(w.y / sinTheta, -1, 1); } PBRT_CPU_GPU inline Float Cos2Phi(const Vector3f &w) { return CosPhi(w) * CosPhi(w); } PBRT_CPU_GPU inline Float Sin2Phi(const Vector3f &w) { return SinPhi(w) * SinPhi(w); } PBRT_CPU_GPU inline Float CosDPhi(const Vector3f &wa, const Vector3f &wb) { Float waxy = wa.x * wa.x + wa.y * wa.y; Float wbxy = wb.x * wb.x + wb.y * wb.y; if (waxy == 0 || wbxy == 0) return 1; return Clamp((wa.x * wb.x + wa.y * wb.y) / std::sqrt(waxy * wbxy), -1, 1); } PBRT_CPU_GPU inline bool SameHemisphere(const Vector3f &w, const Vector3f &wp) { return w.z * wp.z > 0; } PBRT_CPU_GPU inline bool SameHemisphere(const Vector3f &w, const Normal3f &wp) { return w.z * wp.z > 0; } // DirectionCone Definition class DirectionCone { public: // DirectionCone Public Methods DirectionCone() = default; PBRT_CPU_GPU DirectionCone(const Vector3f &w, Float cosTheta) : w(Normalize(w)), cosTheta(cosTheta), empty(false) {} PBRT_CPU_GPU explicit DirectionCone(const Vector3f &w) : DirectionCone(w, 1) {} PBRT_CPU_GPU static DirectionCone EntireSphere() { return DirectionCone(Vector3f(0, 0, 1), -1); } std::string ToString() const; PBRT_CPU_GPU Vector3f ClosestVectorInCone(Vector3f wp) const; // DirectionCone Public Members Vector3f w; Float cosTheta; bool empty = true; }; // DirectionCone Inline Functions PBRT_CPU_GPU inline bool Inside(const DirectionCone &d, const Vector3f &w) { return !d.empty && Dot(d.w, Normalize(w)) >= d.cosTheta; } PBRT_CPU_GPU inline DirectionCone BoundSubtendedDirections(const Bounds3f &b, const Point3f &p) { // Compute bounding sphere for _b_ and check if _p_ is inside Float radius; Point3f pCenter; b.BoundingSphere(&pCenter, &radius); if (DistanceSquared(p, pCenter) < radius * radius) return DirectionCone::EntireSphere(); // Compute and return _DirectionCone_ for bounding sphere Vector3f w = Normalize(pCenter - p); Float sinThetaMax2 = radius * radius / DistanceSquared(pCenter, p); Float cosThetaMax = SafeSqrt(1 - sinThetaMax2); return DirectionCone(w, cosThetaMax); } PBRT_CPU_GPU inline Vector3f DirectionCone::ClosestVectorInCone(Vector3f wp) const { DCHECK(!empty); wp = Normalize(wp); // Return provided vector if it is inside the cone if (Dot(wp, w) > cosTheta) return wp; // Find closest vector by rotating _wp_ until it touches the cone Float sinTheta = -SafeSqrt(1 - cosTheta * cosTheta); Vector3f a = Cross(wp, w); return cosTheta * w + (sinTheta / Length(a)) * Vector3f(w.x * (wp.y * w.y + wp.z * w.z) - wp.x * (Sqr(w.y) + Sqr(w.z)), w.y * (wp.x * w.x + wp.z * w.z) - wp.y * (Sqr(w.x) + Sqr(w.z)), w.z * (wp.x * w.x + wp.y * w.y) - wp.z * (Sqr(w.x) + Sqr(w.y))); } // DirectionCone Function Declarations PBRT_CPU_GPU DirectionCone Union(const DirectionCone &a, const DirectionCone &b); // Frame Definition class Frame { public: // Frame Public Methods PBRT_CPU_GPU Frame() : x(1, 0, 0), y(0, 1, 0), z(0, 0, 1) {} PBRT_CPU_GPU Frame(const Vector3f &x, const Vector3f &y, const Vector3f &z) : x(x), y(y), z(z) { DCHECK_LT(std::abs(LengthSquared(x) - 1), 1e-4); DCHECK_LT(std::abs(LengthSquared(y) - 1), 1e-4); DCHECK_LT(std::abs(LengthSquared(z) - 1), 1e-4); DCHECK_LT(std::abs(Dot(x, y)), 1e-4); DCHECK_LT(std::abs(Dot(y, z)), 1e-4); DCHECK_LT(std::abs(Dot(z, x)), 1e-4); } PBRT_CPU_GPU static Frame FromXZ(const Vector3f &x, const Vector3f &z) { return Frame(x, Cross(z, x), z); } PBRT_CPU_GPU static Frame FromXY(const Vector3f &x, const Vector3f &y) { return Frame(x, y, Cross(x, y)); } PBRT_CPU_GPU static Frame FromZ(const Vector3f &z) { Vector3f x, y; CoordinateSystem(z, &x, &y); return Frame(x, y, z); } PBRT_CPU_GPU static Frame FromZ(const Normal3f &z) { return FromZ(Vector3f(z)); } PBRT_CPU_GPU Vector3f ToLocal(const Vector3f &v) const { return Vector3f(Dot(v, x), Dot(v, y), Dot(v, z)); } PBRT_CPU_GPU Normal3f ToLocal(const Normal3f &n) const { return Normal3f(Dot(n, x), Dot(n, y), Dot(n, z)); } PBRT_CPU_GPU Vector3f FromLocal(const Vector3f &v) const { return v.x * x + v.y * y + v.z * z; } PBRT_CPU_GPU Normal3f FromLocal(const Normal3f &n) const { return Normal3f(n.x * x + n.y * y + n.z * z); } std::string ToString() const { return StringPrintf("[ Frame x: %s y: %s z: %s ]", x, y, z); } // Frame Public Members Vector3f x, y, z; }; } // namespace pbrt #endif // PBRT_UTIL_VECMATH_H
29.936114
90
0.59352
[ "geometry", "vector" ]
43f36c045fcaf5ce899d5391db864461ca17432e
2,489
h
C
common/WhirlyGlobeLib/include/MapboxVectorFilter.h
akovalov/WhirlyGlobe
09f3e7447ce8c049dedfb92550ff649ad1895bb7
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/include/MapboxVectorFilter.h
akovalov/WhirlyGlobe
09f3e7447ce8c049dedfb92550ff649ad1895bb7
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/include/MapboxVectorFilter.h
akovalov/WhirlyGlobe
09f3e7447ce8c049dedfb92550ff649ad1895bb7
[ "Apache-2.0" ]
null
null
null
/* * MapboxVectorFilter.h * WhirlyGlobeLib * * Created by Steve Gifford on 4/8/20. * Copyright 2011-2022 mousebird consulting * * 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. * */ #import "Dictionary.h" #import "QuadTreeNew.h" #import <string> namespace WhirlyKit { /// @brief Mapbox filter operator types typedef enum {MBFilterEqual,MBFilterNotEqual,MBFilterGreaterThan,MBFilterGreaterThanEqual,MBFilterLessThan,MBFilterLessThanEqual,MBFilterIn,MBFilterNotIn,MBFilterHas,MBFilterNotHas,MBFilterAll,MBFilterAny,MBFilterNone} MapboxVectorFilterType; /// @brief Mapbox geometry types typedef enum {MBGeomPoint,MBGeomLineString,MBGeomPolygon,MBGeomNone} MapboxVectorGeometryType; class MapboxVectorStyleSetImpl; typedef std::shared_ptr<MapboxVectorStyleSetImpl> MapboxVectorStyleSetImplRef; class MapboxVectorFilter; typedef std::shared_ptr<MapboxVectorFilter> MapboxVectorFilterRef; /// @brief Filter is used to match data in a layer to styles class MapboxVectorFilter { public: MapboxVectorFilter(); /// @brief Parse the filter info out of the style entry bool parse(const std::vector<DictionaryEntryRef> &styleEntry,MapboxVectorStyleSetImpl *styleSet); /// @brief Test a feature's attributes against the filter bool testFeature(Dictionary const& attrs,const QuadTreeIdentifier &tileID); /// @brief The comparison type for this filter MapboxVectorFilterType filterType; /// @brief Attribute name for all the types that take two arguments std::string attrName; /// @brief Set if we're comparing geometry type instead of an attribute MapboxVectorGeometryType geomType; /// @brief Attribute value to compare for all the type that take two arguments DictionaryEntryRef attrVal; /// @brief Attribute values for the in and !in operators std::vector<DictionaryEntryRef> attrVals; /// @brief For All and Any these are the MapboxVectorFilters to evaluate std::vector<MapboxVectorFilterRef> subFilters; }; }
34.569444
242
0.774608
[ "geometry", "vector" ]
43f50c7f13b253eb4a65440abe81f9986210c1bd
35,510
c
C
vnfs/sonata-vtc-vnf-docker/pfring_web_api/vtc/PF_RING/userland/libpcap/pcap-dos.c
demonCoder95/son-examples
d9b88ec83607c4bcac6c18b80ef2bd62a549981d
[ "Apache-2.0" ]
10
2019-01-09T06:32:58.000Z
2021-11-16T11:36:22.000Z
vnfs/sonata-vtc-vnf-docker/pfring_web_api/vtc/PF_RING/userland/libpcap/pcap-dos.c
demonCoder95/son-examples
d9b88ec83607c4bcac6c18b80ef2bd62a549981d
[ "Apache-2.0" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
vnfs/sonata-vtc-vnf-docker/pfring_web_api/vtc/PF_RING/userland/libpcap/pcap-dos.c
demonCoder95/son-examples
d9b88ec83607c4bcac6c18b80ef2bd62a549981d
[ "Apache-2.0" ]
18
2016-08-23T08:24:28.000Z
2021-06-02T11:10:14.000Z
/* * This file is part of DOS-libpcap * Ported to DOS/DOSX by G. Vanem <gvanem@broadpark.no> * * pcap-dos.c: Interface to PKTDRVR, NDIS2 and 32-bit pmode * network drivers. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <float.h> #include <fcntl.h> #include <io.h> #if defined(USE_32BIT_DRIVERS) #include "msdos/pm_drvr/pmdrvr.h" #include "msdos/pm_drvr/pci.h" #include "msdos/pm_drvr/bios32.h" #include "msdos/pm_drvr/module.h" #include "msdos/pm_drvr/3c501.h" #include "msdos/pm_drvr/3c503.h" #include "msdos/pm_drvr/3c509.h" #include "msdos/pm_drvr/3c59x.h" #include "msdos/pm_drvr/3c515.h" #include "msdos/pm_drvr/3c90x.h" #include "msdos/pm_drvr/3c575_cb.h" #include "msdos/pm_drvr/ne.h" #include "msdos/pm_drvr/wd.h" #include "msdos/pm_drvr/accton.h" #include "msdos/pm_drvr/cs89x0.h" #include "msdos/pm_drvr/rtl8139.h" #include "msdos/pm_drvr/ne2k-pci.h" #endif #include "pcap.h" #include "pcap-dos.h" #include "pcap-int.h" #include "msdos/pktdrvr.h" #ifdef USE_NDIS2 #include "msdos/ndis2.h" #endif #include <arpa/inet.h> #include <net/if.h> #include <net/if_arp.h> #include <net/if_ether.h> #include <net/if_packe.h> #include <tcp.h> #if defined(USE_32BIT_DRIVERS) #define FLUSHK() do { _printk_safe = 1; _printk_flush(); } while (0) #define NDIS_NEXT_DEV &rtl8139_dev static char *rx_pool = NULL; static void init_32bit (void); static int pktq_init (struct rx_ringbuf *q, int size, int num, char *pool); static int pktq_check (struct rx_ringbuf *q); static int pktq_inc_out (struct rx_ringbuf *q); static int pktq_in_index (struct rx_ringbuf *q) LOCKED_FUNC; static void pktq_clear (struct rx_ringbuf *q) LOCKED_FUNC; static struct rx_elem *pktq_in_elem (struct rx_ringbuf *q) LOCKED_FUNC; static struct rx_elem *pktq_out_elem (struct rx_ringbuf *q); #else #define FLUSHK() ((void)0) #define NDIS_NEXT_DEV NULL #endif /* * Internal variables/functions in Watt-32 */ extern WORD _pktdevclass; extern BOOL _eth_is_init; extern int _w32_dynamic_host; extern int _watt_do_exit; extern int _watt_is_init; extern int _w32__bootp_on, _w32__dhcp_on, _w32__rarp_on, _w32__do_mask_req; extern void (*_w32_usr_post_init) (void); extern void (*_w32_print_hook)(); extern void dbug_write (const char *); /* Watt-32 lib, pcdbug.c */ extern int pkt_get_mtu (void); static int ref_count = 0; static u_long mac_count = 0; static u_long filter_count = 0; static volatile BOOL exc_occured = 0; static struct device *handle_to_device [20]; static int pcap_activate_dos (pcap_t *p); static int pcap_read_dos (pcap_t *p, int cnt, pcap_handler callback, u_char *data); static void pcap_cleanup_dos (pcap_t *p); static int pcap_stats_dos (pcap_t *p, struct pcap_stat *ps); static int pcap_sendpacket_dos (pcap_t *p, const void *buf, size_t len); static int pcap_setfilter_dos (pcap_t *p, struct bpf_program *fp); static int ndis_probe (struct device *dev); static int pkt_probe (struct device *dev); static void close_driver (void); static int init_watt32 (struct pcap *pcap, const char *dev_name, char *err_buf); static int first_init (const char *name, char *ebuf, int promisc); static void watt32_recv_hook (u_char *dummy, const struct pcap_pkthdr *pcap, const u_char *buf); /* * These are the device we always support */ static struct device ndis_dev = { "ndis", "NDIS2 LanManager", 0, 0,0,0,0,0,0, NDIS_NEXT_DEV, /* NULL or a 32-bit device */ ndis_probe }; static struct device pkt_dev = { "pkt", "Packet-Driver", 0, 0,0,0,0,0,0, &ndis_dev, pkt_probe }; static struct device *get_device (int fd) { if (fd <= 0 || fd >= sizeof(handle_to_device)/sizeof(handle_to_device[0])) return (NULL); return handle_to_device [fd-1]; } /* * Private data for capturing on MS-DOS. */ struct pcap_dos { void (*wait_proc)(void); /* call proc while waiting */ struct pcap_stat stat; }; pcap_t *pcap_create_interface (const char *device, char *ebuf) { pcap_t *p; p = pcap_create_common(device, ebuf, sizeof (struct pcap_dos)); if (p == NULL) return (NULL); p->activate_op = pcap_activate_dos; return (p); } /* * Open MAC-driver with name 'device_name' for live capture of * network packets. */ static int pcap_activate_dos (pcap_t *pcap) { struct pcap_dos *pcapd = pcap->priv; if (pcap->opt.rfmon) { /* * No monitor mode on DOS. */ return (PCAP_ERROR_RFMON_NOTSUP); } if (pcap->snapshot < ETH_MIN+8) pcap->snapshot = ETH_MIN+8; if (pcap->snapshot > ETH_MAX) /* silently accept and truncate large MTUs */ pcap->snapshot = ETH_MAX; pcap->linktype = DLT_EN10MB; /* !! */ pcap->cleanup_op = pcap_cleanup_dos; pcap->read_op = pcap_read_dos; pcap->stats_op = pcap_stats_dos; pcap->inject_op = pcap_sendpacket_dos; pcap->setfilter_op = pcap_setfilter_dos; pcap->setdirection_op = NULL; /* Not implemented.*/ pcap->fd = ++ref_count; if (pcap->fd == 1) /* first time we're called */ { if (!init_watt32(pcap, pcap->opt.source, pcap->errbuf) || !first_init(pcap->opt.source, pcap->errbuf, pcap->opt.promisc)) { return (PCAP_ERROR); } atexit (close_driver); } else if (stricmp(active_dev->name,pcap->opt.source)) { snprintf (pcap->errbuf, PCAP_ERRBUF_SIZE, "Cannot use different devices simultaneously " "(`%s' vs. `%s')", active_dev->name, pcap->opt.source); return (PCAP_ERROR); } handle_to_device [pcap->fd-1] = active_dev; return (0); } /* * Poll the receiver queue and call the pcap callback-handler * with the packet. */ static int pcap_read_one (pcap_t *p, pcap_handler callback, u_char *data) { struct pcap_dos *pd = p->priv; struct pcap_pkthdr pcap; struct timeval now, expiry = { 0,0 }; BYTE *rx_buf; int rx_len = 0; if (p->opt.timeout > 0) { gettimeofday2 (&now, NULL); expiry.tv_usec = now.tv_usec + 1000UL * p->opt.timeout; expiry.tv_sec = now.tv_sec; while (expiry.tv_usec >= 1000000L) { expiry.tv_usec -= 1000000L; expiry.tv_sec++; } } while (!exc_occured) { volatile struct device *dev; /* might be reset by sig_handler */ dev = get_device (p->fd); if (!dev) break; PCAP_ASSERT (dev->copy_rx_buf || dev->peek_rx_buf); FLUSHK(); /* If driver has a zero-copy receive facility, peek at the queue, * filter it, do the callback and release the buffer. */ if (dev->peek_rx_buf) { PCAP_ASSERT (dev->release_rx_buf); rx_len = (*dev->peek_rx_buf) (&rx_buf); } else { BYTE buf [ETH_MAX+100]; /* add some margin */ rx_len = (*dev->copy_rx_buf) (buf, p->snapshot); rx_buf = buf; } if (rx_len > 0) /* got a packet */ { mac_count++; FLUSHK(); pcap.caplen = min (rx_len, p->snapshot); pcap.len = rx_len; if (callback && (!p->fcode.bf_insns || bpf_filter(p->fcode.bf_insns, rx_buf, pcap.len, pcap.caplen))) { filter_count++; /* Fix-me!! Should be time of arrival. Not time of * capture. */ gettimeofday2 (&pcap.ts, NULL); (*callback) (data, &pcap, rx_buf); } if (dev->release_rx_buf) (*dev->release_rx_buf) (rx_buf); if (pcap_pkt_debug > 0) { if (callback == watt32_recv_hook) dbug_write ("pcap_recv_hook\n"); else dbug_write ("pcap_read_op\n"); } FLUSHK(); return (1); } /* If not to wait for a packet or pcap_cleanup_dos() called from * e.g. SIGINT handler, exit loop now. */ if (p->opt.timeout <= 0 || (volatile int)p->fd <= 0) break; gettimeofday2 (&now, NULL); if (timercmp(&now, &expiry, >)) break; #ifndef DJGPP kbhit(); /* a real CPU hog */ #endif if (p->wait_proc) (*p->wait_proc)(); /* call yield func */ } if (rx_len < 0) /* receive error */ { pd->stat.ps_drop++; #ifdef USE_32BIT_DRIVERS if (pcap_pkt_debug > 1) printk ("pkt-err %s\n", pktInfo.error); #endif return (-1); } return (0); } static int pcap_read_dos (pcap_t *p, int cnt, pcap_handler callback, u_char *data) { struct pcap_dos *pd = p->priv; int rc, num = 0; while (num <= cnt || PACKET_COUNT_IS_UNLIMITED(cnt)) { if (p->fd <= 0) return (-1); rc = pcap_read_one (p, callback, data); if (rc > 0) num++; if (rc < 0) break; _w32_os_yield(); /* allow SIGINT generation, yield to Win95/NT */ } return (num); } /* * Return network statistics */ static int pcap_stats_dos (pcap_t *p, struct pcap_stat *ps) { struct net_device_stats *stats; struct pcap_dos *pd; struct device *dev = p ? get_device(p->fd) : NULL; if (!dev) { strcpy (p->errbuf, "illegal pcap handle"); return (-1); } if (!dev->get_stats || (stats = (*dev->get_stats)(dev)) == NULL) { strcpy (p->errbuf, "device statistics not available"); return (-1); } FLUSHK(); pd = p->priv; pd->stat.ps_recv = stats->rx_packets; pd->stat.ps_drop += stats->rx_missed_errors; pd->stat.ps_ifdrop = stats->rx_dropped + /* queue full */ stats->rx_errors; /* HW errors */ if (ps) *ps = pd->stat; return (0); } /* * Return detailed network/device statistics. * May be called after 'dev->close' is called. */ int pcap_stats_ex (pcap_t *p, struct pcap_stat_ex *se) { struct device *dev = p ? get_device (p->fd) : NULL; if (!dev || !dev->get_stats) { strlcpy (p->errbuf, "detailed device statistics not available", PCAP_ERRBUF_SIZE); return (-1); } if (!strnicmp(dev->name,"pkt",3)) { strlcpy (p->errbuf, "pktdrvr doesn't have detailed statistics", PCAP_ERRBUF_SIZE); return (-1); } memcpy (se, (*dev->get_stats)(dev), sizeof(*se)); return (0); } /* * Simply store the filter-code for the pcap_read_dos() callback * Some day the filter-code could be handed down to the active * device (pkt_rx1.s or 32-bit device interrupt handler). */ static int pcap_setfilter_dos (pcap_t *p, struct bpf_program *fp) { if (!p) return (-1); p->fcode = *fp; return (0); } /* * Return # of packets received in pcap_read_dos() */ u_long pcap_mac_packets (void) { return (mac_count); } /* * Return # of packets passed through filter in pcap_read_dos() */ u_long pcap_filter_packets (void) { return (filter_count); } /* * Close pcap device. Not called for offline captures. */ static void pcap_cleanup_dos (pcap_t *p) { struct pcap_dos *pd; if (p && !exc_occured) { pd = p->priv; if (pcap_stats(p,NULL) < 0) pd->stat.ps_drop = 0; if (!get_device(p->fd)) return; handle_to_device [p->fd-1] = NULL; p->fd = 0; if (ref_count > 0) ref_count--; if (ref_count > 0) return; } close_driver(); } /* * Return the name of the 1st network interface, * or NULL if none can be found. */ char *pcap_lookupdev (char *ebuf) { struct device *dev; #ifdef USE_32BIT_DRIVERS init_32bit(); #endif for (dev = (struct device*)dev_base; dev; dev = dev->next) { PCAP_ASSERT (dev->probe); if ((*dev->probe)(dev)) { FLUSHK(); probed_dev = (struct device*) dev; /* remember last probed device */ return (char*) dev->name; } } if (ebuf) strcpy (ebuf, "No driver found"); return (NULL); } /* * Gets localnet & netmask from Watt-32. */ int pcap_lookupnet (const char *device, bpf_u_int32 *localnet, bpf_u_int32 *netmask, char *errbuf) { if (!_watt_is_init) { strcpy (errbuf, "pcap_open_offline() or pcap_activate() must be " "called first"); return (-1); } *netmask = _w32_sin_mask; *localnet = my_ip_addr & *netmask; if (*localnet == 0) { if (IN_CLASSA(*netmask)) *localnet = IN_CLASSA_NET; else if (IN_CLASSB(*netmask)) *localnet = IN_CLASSB_NET; else if (IN_CLASSC(*netmask)) *localnet = IN_CLASSC_NET; else { sprintf (errbuf, "inet class for 0x%lx unknown", *netmask); return (-1); } } ARGSUSED (device); return (0); } /* * Get a list of all interfaces that are present and that we probe okay. * Returns -1 on error, 0 otherwise. * The list, as returned through "alldevsp", may be null if no interfaces * were up and could be opened. */ int pcap_findalldevs (pcap_if_t **alldevsp, char *errbuf) { struct device *dev; struct sockaddr_ll sa_ll_1, sa_ll_2; struct sockaddr *addr, *netmask, *broadaddr, *dstaddr; pcap_if_t *devlist = NULL; int ret = 0; size_t addr_size = sizeof(struct sockaddr_ll); for (dev = (struct device*)dev_base; dev; dev = dev->next) { PCAP_ASSERT (dev->probe); if (!(*dev->probe)(dev)) continue; PCAP_ASSERT (dev->close); /* set by probe routine */ FLUSHK(); (*dev->close) (dev); memset (&sa_ll_1, 0, sizeof(sa_ll_1)); memset (&sa_ll_2, 0, sizeof(sa_ll_2)); sa_ll_1.sll_family = AF_PACKET; sa_ll_2.sll_family = AF_PACKET; addr = (struct sockaddr*) &sa_ll_1; netmask = (struct sockaddr*) &sa_ll_1; dstaddr = (struct sockaddr*) &sa_ll_1; broadaddr = (struct sockaddr*) &sa_ll_2; memset (&sa_ll_2.sll_addr, 0xFF, sizeof(sa_ll_2.sll_addr)); if (pcap_add_if(&devlist, dev->name, dev->flags, dev->long_name, errbuf) < 0) { ret = -1; break; } if (add_addr_to_iflist(&devlist,dev->name, dev->flags, addr, addr_size, netmask, addr_size, broadaddr, addr_size, dstaddr, addr_size, errbuf) < 0) { ret = -1; break; } } if (devlist && ret < 0) { pcap_freealldevs (devlist); devlist = NULL; } else if (!devlist) strcpy (errbuf, "No drivers found"); *alldevsp = devlist; return (ret); } /* * pcap_assert() is mainly used for debugging */ void pcap_assert (const char *what, const char *file, unsigned line) { FLUSHK(); fprintf (stderr, "%s (%u): Assertion \"%s\" failed\n", file, line, what); close_driver(); _exit (-1); } /* * For pcap_offline_read(): wait and yield between printing packets * to simulate the pace packets where actually recorded. */ void pcap_set_wait (pcap_t *p, void (*yield)(void), int wait) { struct pcap_dos *pd; if (p) { pd = p->priv; pd->wait_proc = yield; p->opt.timeout = wait; } } /* * Initialise a named network device. */ static struct device * open_driver (const char *dev_name, char *ebuf, int promisc) { struct device *dev; for (dev = (struct device*)dev_base; dev; dev = dev->next) { PCAP_ASSERT (dev->name); if (strcmp (dev_name,dev->name)) continue; if (!probed_dev) /* user didn't call pcap_lookupdev() first */ { PCAP_ASSERT (dev->probe); if (!(*dev->probe)(dev)) /* call the xx_probe() function */ { sprintf (ebuf, "failed to detect device `%s'", dev_name); return (NULL); } probed_dev = dev; /* device is probed okay and may be used */ } else if (dev != probed_dev) { goto not_probed; } FLUSHK(); /* Select what traffic to receive */ if (promisc) dev->flags |= (IFF_ALLMULTI | IFF_PROMISC); else dev->flags &= ~(IFF_ALLMULTI | IFF_PROMISC); PCAP_ASSERT (dev->open); if (!(*dev->open)(dev)) { sprintf (ebuf, "failed to activate device `%s'", dev_name); if (pktInfo.error && !strncmp(dev->name,"pkt",3)) { strcat (ebuf, ": "); strcat (ebuf, pktInfo.error); } return (NULL); } /* Some devices need this to operate in promiscous mode */ if (promisc && dev->set_multicast_list) (*dev->set_multicast_list) (dev); active_dev = dev; /* remember our active device */ break; } /* 'dev_name' not matched in 'dev_base' list. */ if (!dev) { sprintf (ebuf, "device `%s' not supported", dev_name); return (NULL); } not_probed: if (!probed_dev) { sprintf (ebuf, "device `%s' not probed", dev_name); return (NULL); } return (dev); } /* * Deinitialise MAC driver. * Set receive mode back to default mode. */ static void close_driver (void) { /* !!todo: loop over all 'handle_to_device[]' ? */ struct device *dev = active_dev; if (dev && dev->close) { (*dev->close) (dev); FLUSHK(); } active_dev = NULL; #ifdef USE_32BIT_DRIVERS if (rx_pool) { k_free (rx_pool); rx_pool = NULL; } if (dev) pcibios_exit(); #endif } #ifdef __DJGPP__ static void setup_signals (void (*handler)(int)) { signal (SIGSEGV,handler); signal (SIGILL, handler); signal (SIGFPE, handler); } static void exc_handler (int sig) { #ifdef USE_32BIT_DRIVERS if (active_dev->irq > 0) /* excludes IRQ 0 */ { disable_irq (active_dev->irq); irq_eoi_cmd (active_dev->irq); _printk_safe = 1; } #endif switch (sig) { case SIGSEGV: fputs ("Catching SIGSEGV.\n", stderr); break; case SIGILL: fputs ("Catching SIGILL.\n", stderr); break; case SIGFPE: _fpreset(); fputs ("Catching SIGFPE.\n", stderr); break; default: fprintf (stderr, "Catching signal %d.\n", sig); } exc_occured = 1; pcap_cleanup_dos (NULL); } #endif /* __DJGPP__ */ /* * Open the pcap device for the first client calling pcap_activate() */ static int first_init (const char *name, char *ebuf, int promisc) { struct device *dev; #ifdef USE_32BIT_DRIVERS rx_pool = k_calloc (RECEIVE_BUF_SIZE, RECEIVE_QUEUE_SIZE); if (!rx_pool) { strcpy (ebuf, "Not enough memory (Rx pool)"); return (0); } #endif #ifdef __DJGPP__ setup_signals (exc_handler); #endif #ifdef USE_32BIT_DRIVERS init_32bit(); #endif dev = open_driver (name, ebuf, promisc); if (!dev) { #ifdef USE_32BIT_DRIVERS k_free (rx_pool); rx_pool = NULL; #endif #ifdef __DJGPP__ setup_signals (SIG_DFL); #endif return (0); } #ifdef USE_32BIT_DRIVERS /* * If driver is NOT a 16-bit "pkt/ndis" driver (having a 'copy_rx_buf' * set in it's probe handler), initialise near-memory ring-buffer for * the 32-bit device. */ if (dev->copy_rx_buf == NULL) { dev->get_rx_buf = get_rxbuf; dev->peek_rx_buf = peek_rxbuf; dev->release_rx_buf = release_rxbuf; pktq_init (&dev->queue, RECEIVE_BUF_SIZE, RECEIVE_QUEUE_SIZE, rx_pool); } #endif return (1); } #ifdef USE_32BIT_DRIVERS static void init_32bit (void) { static int init_pci = 0; if (!_printk_file) _printk_init (64*1024, NULL); /* calls atexit(printk_exit) */ if (!init_pci) (void)pci_init(); /* init BIOS32+PCI interface */ init_pci = 1; } #endif /* * Hook functions for using Watt-32 together with pcap */ static char rxbuf [ETH_MAX+100]; /* rx-buffer with some margin */ static WORD etype; static pcap_t pcap_save; static void watt32_recv_hook (u_char *dummy, const struct pcap_pkthdr *pcap, const u_char *buf) { /* Fix me: assumes Ethernet II only */ struct ether_header *ep = (struct ether_header*) buf; memcpy (rxbuf, buf, pcap->caplen); etype = ep->ether_type; ARGSUSED (dummy); } #if (WATTCP_VER >= 0x0224) /* * This function is used by Watt-32 to poll for a packet. * i.e. it's set to bypass _eth_arrived() */ static void *pcap_recv_hook (WORD *type) { int len = pcap_read_dos (&pcap_save, 1, watt32_recv_hook, NULL); if (len < 0) return (NULL); *type = etype; return (void*) &rxbuf; } /* * This function is called by Watt-32 (via _eth_xmit_hook). * If dbug_init() was called, we should trace packets sent. */ static int pcap_xmit_hook (const void *buf, unsigned len) { int rc = 0; if (pcap_pkt_debug > 0) dbug_write ("pcap_xmit_hook: "); if (active_dev && active_dev->xmit) if ((*active_dev->xmit) (active_dev, buf, len) > 0) rc = len; if (pcap_pkt_debug > 0) dbug_write (rc ? "ok\n" : "fail\n"); return (rc); } #endif static int pcap_sendpacket_dos (pcap_t *p, const void *buf, size_t len) { struct device *dev = p ? get_device(p->fd) : NULL; if (!dev || !dev->xmit) return (-1); return (*dev->xmit) (dev, buf, len); } /* * This function is called by Watt-32 in tcp_post_init(). * We should prevent Watt-32 from using BOOTP/DHCP/RARP etc. */ static void (*prev_post_hook) (void); static void pcap_init_hook (void) { _w32__bootp_on = _w32__dhcp_on = _w32__rarp_on = 0; _w32__do_mask_req = 0; _w32_dynamic_host = 0; if (prev_post_hook) (*prev_post_hook)(); } /* * Supress PRINT message from Watt-32's sock_init() */ static void null_print (void) {} /* * To use features of Watt-32 (netdb functions and socket etc.) * we must call sock_init(). But we set various hooks to prevent * using normal PKTDRVR functions in pcpkt.c. This should hopefully * make Watt-32 and pcap co-operate. */ static int init_watt32 (struct pcap *pcap, const char *dev_name, char *err_buf) { char *env; int rc, MTU, has_ip_addr; int using_pktdrv = 1; /* If user called sock_init() first, we need to reinit in * order to open debug/trace-file properly */ if (_watt_is_init) sock_exit(); env = getenv ("PCAP_DEBUG"); if (env && atoi(env) > 0 && pcap_pkt_debug < 0) /* if not already set */ { dbug_init(); pcap_pkt_debug = atoi (env); } _watt_do_exit = 0; /* prevent sock_init() calling exit() */ prev_post_hook = _w32_usr_post_init; _w32_usr_post_init = pcap_init_hook; _w32_print_hook = null_print; if (dev_name && strncmp(dev_name,"pkt",3)) using_pktdrv = FALSE; rc = sock_init(); has_ip_addr = (rc != 8); /* IP-address assignment failed */ /* if pcap is using a 32-bit driver w/o a pktdrvr loaded, we * just pretend Watt-32 is initialised okay. * * !! fix-me: The Watt-32 config isn't done if no pktdrvr * was found. In that case my_ip_addr + sin_mask * have default values. Should be taken from another * ini-file/environment in any case (ref. tcpdump.ini) */ _watt_is_init = 1; if (!using_pktdrv || !has_ip_addr) /* for now .... */ { static const char myip[] = "192.168.0.1"; static const char mask[] = "255.255.255.0"; printf ("Just guessing, using IP %s and netmask %s\n", myip, mask); my_ip_addr = aton (myip); _w32_sin_mask = aton (mask); } else if (rc && using_pktdrv) { sprintf (err_buf, "sock_init() failed, code %d", rc); return (0); } /* Set recv-hook for peeking in _eth_arrived(). */ #if (WATTCP_VER >= 0x0224) _eth_recv_hook = pcap_recv_hook; _eth_xmit_hook = pcap_xmit_hook; #endif /* Free the pkt-drvr handle allocated in pkt_init(). * The above hooks should thus use the handle reopened in open_driver() */ if (using_pktdrv) { _eth_release(); /* _eth_is_init = 1; */ /* hack to get Rx/Tx-hooks in Watt-32 working */ } memcpy (&pcap_save, pcap, sizeof(pcap_save)); MTU = pkt_get_mtu(); pcap_save.fcode.bf_insns = NULL; pcap_save.linktype = _eth_get_hwtype (NULL, NULL); pcap_save.snapshot = MTU > 0 ? MTU : ETH_MAX; /* assume 1514 */ #if 1 /* prevent use of resolve() and resolve_ip() */ last_nameserver = 0; #endif return (1); } int EISA_bus = 0; /* Where is natural place for this? */ /* * Application config hooks to set various driver parameters. */ static const struct config_table debug_tab[] = { { "PKT.DEBUG", ARG_ATOI, &pcap_pkt_debug }, { "PKT.VECTOR", ARG_ATOX_W, NULL }, { "NDIS.DEBUG", ARG_ATOI, NULL }, #ifdef USE_32BIT_DRIVERS { "3C503.DEBUG", ARG_ATOI, &ei_debug }, { "3C503.IO_BASE", ARG_ATOX_W, &el2_dev.base_addr }, { "3C503.MEMORY", ARG_ATOX_W, &el2_dev.mem_start }, { "3C503.IRQ", ARG_ATOI, &el2_dev.irq }, { "3C505.DEBUG", ARG_ATOI, NULL }, { "3C505.BASE", ARG_ATOX_W, NULL }, { "3C507.DEBUG", ARG_ATOI, NULL }, { "3C509.DEBUG", ARG_ATOI, &el3_debug }, { "3C509.ILOOP", ARG_ATOI, &el3_max_loop }, { "3C529.DEBUG", ARG_ATOI, NULL }, { "3C575.DEBUG", ARG_ATOI, &debug_3c575 }, { "3C59X.DEBUG", ARG_ATOI, &vortex_debug }, { "3C59X.IFACE0", ARG_ATOI, &vortex_options[0] }, { "3C59X.IFACE1", ARG_ATOI, &vortex_options[1] }, { "3C59X.IFACE2", ARG_ATOI, &vortex_options[2] }, { "3C59X.IFACE3", ARG_ATOI, &vortex_options[3] }, { "3C90X.DEBUG", ARG_ATOX_W, &tc90xbc_debug }, { "ACCT.DEBUG", ARG_ATOI, &ethpk_debug }, { "CS89.DEBUG", ARG_ATOI, &cs89_debug }, { "RTL8139.DEBUG", ARG_ATOI, &rtl8139_debug }, /* { "RTL8139.FDUPLEX", ARG_ATOI, &rtl8139_options }, */ { "SMC.DEBUG", ARG_ATOI, &ei_debug }, /* { "E100.DEBUG", ARG_ATOI, &e100_debug }, */ { "PCI.DEBUG", ARG_ATOI, &pci_debug }, { "BIOS32.DEBUG", ARG_ATOI, &bios32_debug }, { "IRQ.DEBUG", ARG_ATOI, &irq_debug }, { "TIMER.IRQ", ARG_ATOI, &timer_irq }, #endif { NULL } }; /* * pcap_config_hook() is an extension to application's config * handling. Uses Watt-32's config-table function. */ int pcap_config_hook (const char *name, const char *value) { return parse_config_table (debug_tab, NULL, name, value); } /* * Linked list of supported devices */ struct device *active_dev = NULL; /* the device we have opened */ struct device *probed_dev = NULL; /* the device we have probed */ const struct device *dev_base = &pkt_dev; /* list of network devices */ /* * PKTDRVR device functions */ int pcap_pkt_debug = -1; static void pkt_close (struct device *dev) { BOOL okay = PktExitDriver(); if (pcap_pkt_debug > 1) fprintf (stderr, "pkt_close(): %d\n", okay); if (dev->priv) free (dev->priv); dev->priv = NULL; } static int pkt_open (struct device *dev) { PKT_RX_MODE mode; if (dev->flags & IFF_PROMISC) mode = PDRX_ALL_PACKETS; else mode = PDRX_BROADCAST; if (!PktInitDriver(mode)) return (0); PktResetStatistics (pktInfo.handle); PktQueueBusy (FALSE); return (1); } static int pkt_xmit (struct device *dev, const void *buf, int len) { struct net_device_stats *stats = (struct net_device_stats*) dev->priv; if (pcap_pkt_debug > 0) dbug_write ("pcap_xmit\n"); if (!PktTransmit(buf,len)) { stats->tx_errors++; return (0); } return (len); } static void *pkt_stats (struct device *dev) { struct net_device_stats *stats = (struct net_device_stats*) dev->priv; if (!stats || !PktSessStatistics(pktInfo.handle)) return (NULL); stats->rx_packets = pktStat.inPackets; stats->rx_errors = pktStat.lost; stats->rx_missed_errors = PktRxDropped(); return (stats); } static int pkt_probe (struct device *dev) { if (!PktSearchDriver()) return (0); dev->open = pkt_open; dev->xmit = pkt_xmit; dev->close = pkt_close; dev->get_stats = pkt_stats; dev->copy_rx_buf = PktReceive; /* farmem peek and copy routine */ dev->get_rx_buf = NULL; dev->peek_rx_buf = NULL; dev->release_rx_buf = NULL; dev->priv = calloc (sizeof(struct net_device_stats), 1); if (!dev->priv) return (0); return (1); } /* * NDIS device functions */ static void ndis_close (struct device *dev) { #ifdef USE_NDIS2 NdisShutdown(); #endif ARGSUSED (dev); } static int ndis_open (struct device *dev) { int promis = (dev->flags & IFF_PROMISC); #ifdef USE_NDIS2 if (!NdisInit(promis)) return (0); return (1); #else ARGSUSED (promis); return (0); #endif } static void *ndis_stats (struct device *dev) { static struct net_device_stats stats; /* to-do */ ARGSUSED (dev); return (&stats); } static int ndis_probe (struct device *dev) { #ifdef USE_NDIS2 if (!NdisOpen()) return (0); #endif dev->open = ndis_open; dev->xmit = NULL; dev->close = ndis_close; dev->get_stats = ndis_stats; dev->copy_rx_buf = NULL; /* to-do */ dev->get_rx_buf = NULL; /* upcall is from rmode driver */ dev->peek_rx_buf = NULL; dev->release_rx_buf = NULL; return (0); } /* * Search & probe for supported 32-bit (pmode) pcap devices */ #if defined(USE_32BIT_DRIVERS) struct device el2_dev LOCKED_VAR = { "3c503", "EtherLink II", 0, 0,0,0,0,0,0, NULL, el2_probe }; struct device el3_dev LOCKED_VAR = { "3c509", "EtherLink III", 0, 0,0,0,0,0,0, &el2_dev, el3_probe }; struct device tc515_dev LOCKED_VAR = { "3c515", "EtherLink PCI", 0, 0,0,0,0,0,0, &el3_dev, tc515_probe }; struct device tc59_dev LOCKED_VAR = { "3c59x", "EtherLink PCI", 0, 0,0,0,0,0,0, &tc515_dev, tc59x_probe }; struct device tc90xbc_dev LOCKED_VAR = { "3c90x", "EtherLink 90X", 0, 0,0,0,0,0,0, &tc59_dev, tc90xbc_probe }; struct device wd_dev LOCKED_VAR = { "wd", "Westen Digital", 0, 0,0,0,0,0,0, &tc90xbc_dev, wd_probe }; struct device ne_dev LOCKED_VAR = { "ne", "NEx000", 0, 0,0,0,0,0,0, &wd_dev, ne_probe }; struct device acct_dev LOCKED_VAR = { "acct", "Accton EtherPocket", 0, 0,0,0,0,0,0, &ne_dev, ethpk_probe }; struct device cs89_dev LOCKED_VAR = { "cs89", "Crystal Semiconductor", 0, 0,0,0,0,0,0, &acct_dev, cs89x0_probe }; struct device rtl8139_dev LOCKED_VAR = { "rtl8139", "RealTek PCI", 0, 0,0,0,0,0,0, &cs89_dev, rtl8139_probe /* dev->probe routine */ }; /* * Dequeue routine is called by polling. * NOTE: the queue-element is not copied, only a pointer is * returned at '*buf' */ int peek_rxbuf (BYTE **buf) { struct rx_elem *tail, *head; PCAP_ASSERT (pktq_check (&active_dev->queue)); DISABLE(); tail = pktq_out_elem (&active_dev->queue); head = pktq_in_elem (&active_dev->queue); ENABLE(); if (head != tail) { PCAP_ASSERT (tail->size < active_dev->queue.elem_size-4-2); *buf = &tail->data[0]; return (tail->size); } *buf = NULL; return (0); } /* * Release buffer we peeked at above. */ int release_rxbuf (BYTE *buf) { #ifndef NDEBUG struct rx_elem *tail = pktq_out_elem (&active_dev->queue); PCAP_ASSERT (&tail->data[0] == buf); #else ARGSUSED (buf); #endif pktq_inc_out (&active_dev->queue); return (1); } /* * get_rxbuf() routine (in locked code) is called from IRQ handler * to request a buffer. Interrupts are disabled and we have a 32kB stack. */ BYTE *get_rxbuf (int len) { int idx; if (len < ETH_MIN || len > ETH_MAX) return (NULL); idx = pktq_in_index (&active_dev->queue); #ifdef DEBUG { static int fan_idx LOCKED_VAR = 0; writew ("-\\|/"[fan_idx++] | (15 << 8), /* white on black colour */ 0xB8000 + 2*79); /* upper-right corner, 80-col colour screen */ fan_idx &= 3; } /* writew (idx + '0' + 0x0F00, 0xB8000 + 2*78); */ #endif if (idx != active_dev->queue.out_index) { struct rx_elem *head = pktq_in_elem (&active_dev->queue); head->size = len; active_dev->queue.in_index = idx; return (&head->data[0]); } /* !!to-do: drop 25% of the oldest element */ pktq_clear (&active_dev->queue); return (NULL); } /* * Simple ring-buffer queue handler for reception of packets * from network driver. */ #define PKTQ_MARKER 0xDEADBEEF static int pktq_check (struct rx_ringbuf *q) { #ifndef NDEBUG int i; char *buf; #endif if (!q || !q->num_elem || !q->buf_start) return (0); #ifndef NDEBUG buf = q->buf_start; for (i = 0; i < q->num_elem; i++) { buf += q->elem_size; if (*(DWORD*)(buf - sizeof(DWORD)) != PKTQ_MARKER) return (0); } #endif return (1); } static int pktq_init (struct rx_ringbuf *q, int size, int num, char *pool) { int i; q->elem_size = size; q->num_elem = num; q->buf_start = pool; q->in_index = 0; q->out_index = 0; PCAP_ASSERT (size >= sizeof(struct rx_elem) + sizeof(DWORD)); PCAP_ASSERT (num); PCAP_ASSERT (pool); for (i = 0; i < num; i++) { #if 0 struct rx_elem *elem = (struct rx_elem*) pool; /* assert dword aligned elements */ PCAP_ASSERT (((unsigned)(&elem->data[0]) & 3) == 0); #endif pool += size; *(DWORD*) (pool - sizeof(DWORD)) = PKTQ_MARKER; } return (1); } /* * Increment the queue 'out_index' (tail). * Check for wraps. */ static int pktq_inc_out (struct rx_ringbuf *q) { q->out_index++; if (q->out_index >= q->num_elem) q->out_index = 0; return (q->out_index); } /* * Return the queue's next 'in_index' (head). * Check for wraps. */ static int pktq_in_index (struct rx_ringbuf *q) { volatile int index = q->in_index + 1; if (index >= q->num_elem) index = 0; return (index); } /* * Return the queue's head-buffer. */ static struct rx_elem *pktq_in_elem (struct rx_ringbuf *q) { return (struct rx_elem*) (q->buf_start + (q->elem_size * q->in_index)); } /* * Return the queue's tail-buffer. */ static struct rx_elem *pktq_out_elem (struct rx_ringbuf *q) { return (struct rx_elem*) (q->buf_start + (q->elem_size * q->out_index)); } /* * Clear the queue ring-buffer by setting head=tail. */ static void pktq_clear (struct rx_ringbuf *q) { q->in_index = q->out_index; } /* * Symbols that must be linkable for "gcc -O0" */ #undef __IOPORT_H #undef __DMA_H #define extern #define __inline__ #include "msdos/pm_drvr/ioport.h" #include "msdos/pm_drvr/dma.h" #endif /* USE_32BIT_DRIVERS */
23.720775
95
0.594002
[ "vector" ]
43f613a0d9b8af7ed93e6b3f20ec05ca5f2dbaba
13,571
h
C
ui/views/layout/grid_layout.h
junmin-zhu/chromium-rivertrail
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
[ "BSD-3-Clause" ]
2
2020-06-10T07:15:26.000Z
2020-12-13T19:44:12.000Z
ui/views/layout/grid_layout.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
null
null
null
ui/views/layout/grid_layout.h
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
1
2020-11-04T07:27:33.000Z
2020-11-04T07:27:33.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 UI_VIEWS_LAYOUT_GRID_LAYOUT_H_ #define UI_VIEWS_LAYOUT_GRID_LAYOUT_H_ #include <string> #include <vector> #include "base/compiler_specific.h" #include "ui/views/layout/layout_manager.h" #include "ui/views/view.h" namespace gfx { class Insets; } // GridLayout is a LayoutManager that positions child Views in a grid. You // define the structure of the Grid first, then add the Views. // The following creates a trivial grid with two columns separated by // a column with padding: // ColumnSet* columns = layout->AddColumnSet(0); // Give this column an // // identifier of 0. // columns->AddColumn(FILL, // Views are horizontally resized to fill column. // FILL, // Views starting in this column are vertically // // resized. // 1, // This column has a resize weight of 1. // USE_PREF, // Use the preferred size of the view. // 0, // Ignored for USE_PREF. // 0); // A minimum width of 0. // columns->AddPaddingColumn(0, // The padding column is not resizable. // 10); // And has a width of 10 pixels. // columns->AddColumn(FILL, FILL, 0, USE_PREF, 0, 0); // Now add the views: // // First start a row. // layout->StartRow(0, // This row isn't vertically resizable. // 0); // The column set to use for this row. // layout->AddView(v1); // Notice you need not skip over padding columns, that's done for you. // layout->AddView(v2); // // When adding a Column you give it the default alignment for all views // originating in that column. You can override this for specific views // when adding them. For example, the following forces a View to have // a horizontal and vertical alignment of leading regardless of that defined // for the column: // layout->AddView(v1, 1, 1, LEADING, LEADING); // // If the View using GridLayout is given a size bigger than the preferred, // columns and rows with a resize percent > 0 are resized. Each column/row // is given resize_percent / total_resize_percent * extra_pixels extra // pixels. Only Views with an Alignment of FILL are given extra space, others // are aligned in the provided space. // // GridLayout allows you to define multiple column sets. When you start a // new row you specify the id of the column set the row is to use. // // GridLayout allows you to force columns to have the same width. This is // done using the LinkColumnSizes method. // // AddView takes care of adding the View to the View the GridLayout was // created with. namespace views { class Column; class ColumnSet; class Row; class View; struct ViewState; class VIEWS_EXPORT GridLayout : public LayoutManager { public: // An enumeration of the possible alignments supported by GridLayout. enum Alignment { // Leading equates to left along the horizontal axis, and top along the // vertical axis. LEADING, // Centers the view along the axis. CENTER, // Trailing equals to right along the horizontal axis, and bottom along // the vertical axis. TRAILING, // The view is resized to fill the space. FILL, // The view is aligned along the baseline. This is only valid for the // vertical axis. BASELINE }; // An enumeration of the possible ways the size of a column may be obtained. enum SizeType { // The column size is fixed. FIXED, // The preferred size of the view is used to determine the column size. USE_PREF }; explicit GridLayout(View* host); virtual ~GridLayout(); // Creates a GridLayout with kPanel*Margin insets. static GridLayout* CreatePanel(View* host); // Sets the insets. All views are placed relative to these offsets. void SetInsets(int top, int left, int bottom, int right); void SetInsets(const gfx::Insets& insets); // Creates a new column set with the specified id and returns it. // The id is later used when starting a new row. // GridLayout takes ownership of the ColumnSet and will delete it when // the GridLayout is deleted. ColumnSet* AddColumnSet(int id); // Adds a padding row. Padding rows typically don't have any views, and // but are used to provide vertical white space between views. // Size specifies the height of the row. void AddPaddingRow(float vertical_resize, int size); // A convenience for AddPaddingRow followed by StartRow. void StartRowWithPadding(float vertical_resize, int column_set_id, float padding_resize, int padding); // Starts a new row with the specified column set. void StartRow(float vertical_resize, int column_set_id); // Advances past columns. Use this when the current column should not // contain any views. void SkipColumns(int col_count); // Adds a view using the default alignment from the column. The added // view has a column and row span of 1. // As a convenience this adds the view to the host. The view becomes owned // by the host, and NOT this GridLayout. void AddView(View* view); // Adds a view using the default alignment from the column. // As a convenience this adds the view to the host. The view becomes owned // by the host, and NOT this GridLayout. void AddView(View* view, int col_span, int row_span); // Adds a view with the specified alignment and spans. // As a convenience this adds the view to the host. The view becomes owned // by the host, and NOT this GridLayout. void AddView(View* view, int col_span, int row_span, Alignment h_align, Alignment v_align); // Adds a view with the specified alignment and spans. If // pref_width/pref_height is > 0 then the preferred width/height of the view // is fixed to the specified value. // As a convenience this adds the view to the host. The view becomes owned // by the host, and NOT this GridLayout. void AddView(View* view, int col_span, int row_span, Alignment h_align, Alignment v_align, int pref_width, int pref_height); // Notification we've been installed on a particular host. Checks that host // is the same as the View supplied in the constructor. virtual void Installed(View* host) OVERRIDE; // Notification we've been uninstalled on a particular host. Checks that host // is the same as the View supplied in the constructor. virtual void Uninstalled(View* host) OVERRIDE; // Notification that a view has been added. virtual void ViewAdded(View* host, View* view) OVERRIDE; // Notification that a view has been removed. virtual void ViewRemoved(View* host, View* view) OVERRIDE; // Layouts out the components. virtual void Layout(View* host) OVERRIDE; // Returns the preferred size for the GridLayout. virtual gfx::Size GetPreferredSize(View* host) OVERRIDE; virtual int GetPreferredHeightForWidth(View* host, int width) OVERRIDE; void set_minimum_size(const gfx::Size& size) { minimum_size_ = size; } private: // As both Layout and GetPreferredSize need to do nearly the same thing, // they both call into this method. This sizes the Columns/Rows as // appropriate. If layout is true, width/height give the width/height the // of the host, otherwise they are ignored. void SizeRowsAndColumns(bool layout, int width, int height, gfx::Size* pref); // Calculates the master columns of all the column sets. See Column for // a description of what a master column is. void CalculateMasterColumnsIfNecessary(); // This is called internally from AddView. It adds the ViewState to the // appropriate structures, and updates internal fields such as next_column_. void AddViewState(ViewState* view_state); // Returns the column set for the specified id, or NULL if one doesn't exist. ColumnSet* GetColumnSet(int id); // Adds the Row to rows_, as well as updating next_column_, // current_row_col_set ... void AddRow(Row* row); // As the name says, updates the remaining_height of the ViewState for // all Rows the supplied ViewState touches. void UpdateRemainingHeightFromRows(ViewState* state); // If the view state's remaining height is > 0, it is distributed among // the rows the view state touches. This is used during layout to make // sure the Rows can accommodate a view. void DistributeRemainingHeight(ViewState* state); // Advances next_column_ past any padding columns. void SkipPaddingColumns(); // Returns the column set of the last non-padding row. ColumnSet* GetLastValidColumnSet(); // The view we were created with. We don't own this. View* const host_; // Whether or not we've calculated the master/linked columns. bool calculated_master_columns_; // Used to verify a view isn't added with a row span that expands into // another column structure. int remaining_row_span_; // Current row. int current_row_; // Current column. int next_column_; // Column set for the current row. This is null for padding rows. ColumnSet* current_row_col_set_; // Insets. int top_inset_; int bottom_inset_; int left_inset_; int right_inset_; // Set to true when adding a View. bool adding_view_; // ViewStates. This is ordered by row_span in ascending order. std::vector<ViewState*> view_states_; // ColumnSets. std::vector<ColumnSet*> column_sets_; // Rows. std::vector<Row*> rows_; // Minimum preferred size. gfx::Size minimum_size_; DISALLOW_COPY_AND_ASSIGN(GridLayout); }; // ColumnSet is used to define a set of columns. GridLayout may have any // number of ColumnSets. You don't create a ColumnSet directly, instead // use the AddColumnSet method of GridLayout. class VIEWS_EXPORT ColumnSet { public: ~ColumnSet(); // Adds a column for padding. When adding views, padding columns are // automatically skipped. For example, if you create a column set with // two columns separated by a padding column, the first AddView automatically // skips past the padding column. That is, to add two views, do: // layout->AddView(v1); layout->AddView(v2);, not: // layout->AddView(v1); layout->SkipColumns(1); layout->AddView(v2); void AddPaddingColumn(float resize_percent, int width); // Adds a column. The alignment gives the default alignment for views added // with no explicit alignment. fixed_width gives a specific width for the // column, and is only used if size_type == FIXED. min_width gives the // minimum width for the column. // // If none of the columns in a columnset are resizable, the views are only // made as wide as the widest views in each column, even if extra space is // provided. In other words, GridLayout does not automatically resize views // unless the column is marked as resizable. void AddColumn(GridLayout::Alignment h_align, GridLayout::Alignment v_align, float resize_percent, GridLayout::SizeType size_type, int fixed_width, int min_width); // Forces the specified columns to have the same size. The size of // linked columns is that of the max of the specified columns. This // must end with -1. For example, the following forces the first and // second column to have the same size: // LinkColumnSizes(0, 1, -1); void LinkColumnSizes(int first, ...); // ID of this ColumnSet. int id() const { return id_; } int num_columns() const { return static_cast<int>(columns_.size()); } private: friend class GridLayout; explicit ColumnSet(int id); void AddColumn(GridLayout::Alignment h_align, GridLayout::Alignment v_align, float resize_percent, GridLayout::SizeType size_type, int fixed_width, int min_width, bool is_padding); void AddViewState(ViewState* view_state); // Set description of these. void CalculateMasterColumns(); void AccumulateMasterColumns(); // Sets the size of each linked column to be the same. void UnifySameSizedColumnSizes(); // Updates the remaining width field of the ViewState from that of the // columns the view spans. void UpdateRemainingWidth(ViewState* view_state); // Makes sure the columns touched by view state are big enough for the // view. void DistributeRemainingWidth(ViewState* view_state); // Returns the total size needed for this ColumnSet. int LayoutWidth(); // Returns the width of the specified columns. int GetColumnWidth(int start_col, int col_span); // Updates the x coordinate of each column from the previous ones. // NOTE: this doesn't include the insets. void ResetColumnXCoordinates(); // Calculate the preferred width of each view in this column set, as well // as updating the remaining_width. void CalculateSize(); // Distributes delta amoung the resizable columns. void Resize(int delta); // ID for this columnset. const int id_; // The columns. std::vector<Column*> columns_; // The ViewStates. This is sorted based on column_span in ascending // order. std::vector<ViewState*> view_states_; // The master column of those columns that are linked. See Column // for a description of what the master column is. std::vector<Column*> master_columns_; DISALLOW_COPY_AND_ASSIGN(ColumnSet); }; } // namespace views #endif // UI_VIEWS_LAYOUT_GRID_LAYOUT_H_
35.997347
79
0.707317
[ "vector" ]
43f760e0ef8d3fc7f250143ce007ecc89ef1d341
3,753
h
C
aws-cpp-sdk-elasticmapreduce/include/aws/elasticmapreduce/model/InstanceFleetProvisioningSpecifications.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-elasticmapreduce/include/aws/elasticmapreduce/model/InstanceFleetProvisioningSpecifications.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-elasticmapreduce/include/aws/elasticmapreduce/model/InstanceFleetProvisioningSpecifications.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "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/elasticmapreduce/EMR_EXPORTS.h> #include <aws/elasticmapreduce/model/SpotProvisioningSpecification.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace EMR { namespace Model { /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> <note> <p>The * instance fleet configuration is available only in Amazon EMR versions 4.8.0 and * later, excluding 5.0.x versions.</p> </note><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/InstanceFleetProvisioningSpecifications">AWS * API Reference</a></p> */ class AWS_EMR_API InstanceFleetProvisioningSpecifications { public: InstanceFleetProvisioningSpecifications(); InstanceFleetProvisioningSpecifications(Aws::Utils::Json::JsonView jsonValue); InstanceFleetProvisioningSpecifications& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> */ inline const SpotProvisioningSpecification& GetSpotSpecification() const{ return m_spotSpecification; } /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> */ inline bool SpotSpecificationHasBeenSet() const { return m_spotSpecificationHasBeenSet; } /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> */ inline void SetSpotSpecification(const SpotProvisioningSpecification& value) { m_spotSpecificationHasBeenSet = true; m_spotSpecification = value; } /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> */ inline void SetSpotSpecification(SpotProvisioningSpecification&& value) { m_spotSpecificationHasBeenSet = true; m_spotSpecification = std::move(value); } /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> */ inline InstanceFleetProvisioningSpecifications& WithSpotSpecification(const SpotProvisioningSpecification& value) { SetSpotSpecification(value); return *this;} /** * <p>The launch specification for Spot instances in the fleet, which determines * the defined duration and provisioning timeout behavior.</p> */ inline InstanceFleetProvisioningSpecifications& WithSpotSpecification(SpotProvisioningSpecification&& value) { SetSpotSpecification(std::move(value)); return *this;} private: SpotProvisioningSpecification m_spotSpecification; bool m_spotSpecificationHasBeenSet; }; } // namespace Model } // namespace EMR } // namespace Aws
38.295918
169
0.745803
[ "model" ]
43fdde61cb48fc0e05ad8a9428d1ba9e165899d1
1,338
h
C
apps/tests/007_combined_image_sampler_array/test_class.h
JumpyWizardEni/kernel_slicer
6f8eb09797b5d2a97ff059e89c9793a2687cd0ac
[ "MIT" ]
null
null
null
apps/tests/007_combined_image_sampler_array/test_class.h
JumpyWizardEni/kernel_slicer
6f8eb09797b5d2a97ff059e89c9793a2687cd0ac
[ "MIT" ]
null
null
null
apps/tests/007_combined_image_sampler_array/test_class.h
JumpyWizardEni/kernel_slicer
6f8eb09797b5d2a97ff059e89c9793a2687cd0ac
[ "MIT" ]
null
null
null
#ifndef TEST_CLASS_H #define TEST_CLASS_H #include <vector> #include <iostream> #include <fstream> #include "texture2d.h" ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class TestCombinedImage { public: TestCombinedImage(); virtual void Run(const int a_width, const int a_height, unsigned int* outData1ui __attribute__((size("a_width", "a_height"))) ); virtual void CommitDeviceData() {} // will be overriden in generated class virtual void GetExecutionTime(const char* a_funcName, float a_out[4]) {} // will be overriden in generated class protected: void kernel2D_Run(const int a_width, const int a_height, unsigned int* outData1ui); std::vector< std::shared_ptr<ITexture2DCombined> > m_textures; std::vector< const ITexture2DCombined* > m_textures2; int m_blurRadius; int m_width; int m_height; int m_widthSmall; int m_heightSmall; float m_gamma = 2.2F; static constexpr uint FRACTAL_ITERATIONS = 256; }; #endif
31.857143
130
0.508969
[ "vector" ]
b74b22979b4e64b107f9ba1ed0c7155b5d44e197
13,698
h
C
src/bootimg/include/apol/netcon-query.h
xxroot/android_universal
af2d8627182f936383d792c1f775d87da50f2f6d
[ "MIT" ]
207
2018-10-01T08:53:01.000Z
2022-03-14T12:15:54.000Z
src/bootimg/include/apol/netcon-query.h
xxroot/android_universal
af2d8627182f936383d792c1f775d87da50f2f6d
[ "MIT" ]
8
2019-06-29T14:18:51.000Z
2022-02-19T07:30:27.000Z
src/bootimg/include/apol/netcon-query.h
xxroot/android_universal
af2d8627182f936383d792c1f775d87da50f2f6d
[ "MIT" ]
53
2019-03-12T16:50:21.000Z
2022-03-15T23:16:18.000Z
/** * @file * Public Interface for querying portcons, netifcons, and nodecons of * a policy. * * @author Jeremy A. Mowery jmowery@tresys.com * @author Jason Tang jtang@tresys.com * * Copyright (C) 2006-2007 Tresys Technology, LLC * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef APOL_NETCON_QUERY_H #define APOL_NETCON_QUERY_H #ifdef __cplusplus extern "C" { #endif #include "policy.h" #include "vector.h" #include "context-query.h" #include <qpol/policy.h> typedef struct apol_portcon_query apol_portcon_query_t; typedef struct apol_netifcon_query apol_netifcon_query_t; typedef struct apol_nodecon_query apol_nodecon_query_t; /******************** portcon queries ********************/ /** * Execute a query against all portcons within the policy. The * returned portcons will be unordered. * * @param p Policy within which to look up portcons. * @param po Structure containing parameters for query. If this is * NULL then return all portcons. * @param v Reference to a vector of qpol_portcon_t. The vector will * be allocated by this function. The caller must call * apol_vector_destroy() afterwards. This will be set to NULL upon no * results or upon error. * * @return 0 on success (including none found), negative on error. */ extern int apol_portcon_get_by_query(const apol_policy_t * p, const apol_portcon_query_t * po, apol_vector_t ** v); /** * Allocate and return a new portcon query structure. All fields are * initialized, such that running this blank query results in * returning all portcons within the policy. The caller must call * apol_portcon_query_destroy() upon the return value afterwards. * * @return An initialized portcon query structure, or NULL upon error. */ extern apol_portcon_query_t *apol_portcon_query_create(void); /** * Deallocate all memory associated with the referenced portcon * query, and then set it to NULL. This function does nothing if the * query is already NULL. * * @param po Reference to a portcon query structure to destroy. */ extern void apol_portcon_query_destroy(apol_portcon_query_t ** po); /** * Set a portcon query to return only portcons that use this protocol. * * @param p Policy handler, to report errors. * @param po Portcon query to set. * @param proto Limit query to only portcons with this protocol, or * negative to unset this field. * * @return Always 0. */ extern int apol_portcon_query_set_protocol(const apol_policy_t * p, apol_portcon_query_t * po, int proto); /** * Set a portcon query to return only portcons with this as their low * port. * * @param p Policy handler, to report errors. * @param po Portcon query to set. * @param low Limit query to only portcons with this low port, or * negative to unset this field. * * @return Always 0. */ extern int apol_portcon_query_set_low(const apol_policy_t * p, apol_portcon_query_t * po, int low); /** * Set a portcon query to return only portcons with this as their high * port. * * @param p Policy handler, to report errors. * @param po Portcon query to set. * @param high Limit query to only portcons with this high port, or * negative to unset this field. * * @return Always 0. */ extern int apol_portcon_query_set_high(const apol_policy_t * p, apol_portcon_query_t * po, int high); /** * Set a portcon query to return only portcons matching a context. * This function takes ownership of the context, such that the caller * must not modify nor destroy it afterwards. * * @param p Policy handler, to report errors. * @param po Portcon query to set. * @param context Limit query to only portcons matching this context, * or NULL to unset this field. * @param range_match Specifies how to match the MLS range within the * context. This must be one of APOL_QUERY_SUB, APOL_QUERY_SUPER, or * APOL_QUERY_EXACT. This parameter is ignored if context is NULL. * * @return Always returns 0. */ extern int apol_portcon_query_set_context(const apol_policy_t * p, apol_portcon_query_t * po, apol_context_t * context, unsigned int range_match); /** * Creates a string containing the textual representation of * a portcon type. * @param p Reference to a policy. * @param portcon Reference to the portcon statement to be rendered. * * @return A newly allocated string on success, caller must free; * NULL on error. */ extern char *apol_portcon_render(const apol_policy_t * p, const qpol_portcon_t * portcon); /******************** netifcon queries ********************/ /** * Execute a query against all netifcons within the policy. The * returned netifcons will be unordered. * * @param p Policy within which to look up netifcons. * @param n Structure containing parameters for query. If this is * NULL then return all netifcons. * @param v Reference to a vector of qpol_netifcon_t. The vector will * be allocated by this function. The caller must call * apol_vector_destroy() afterwards,. This will be set to NULL upon * no results or upon error. * * @return 0 on success (including none found), negative on error. */ extern int apol_netifcon_get_by_query(const apol_policy_t * p, const apol_netifcon_query_t * n, apol_vector_t ** v); /** * Allocate and return a new netifcon query structure. All fields are * initialized, such that running this blank query results in * returning all netifcons within the policy. The caller must call * apol_netifcon_query_destroy() upon the return value afterwards. * * @return An initialized netifcon query structure, or NULL upon * error. */ extern apol_netifcon_query_t *apol_netifcon_query_create(void); /** * Deallocate all memory associated with the referenced netifcon * query, and then set it to NULL. This function does nothing if the * query is already NULL. * * @param n Reference to a netifcon query structure to destroy. */ extern void apol_netifcon_query_destroy(apol_netifcon_query_t ** n); /** * Set a netifcon query to return only netifcons that use this device. * * @param p Policy handler, to report errors. * @param n Netifcon query to set. * @param dev Limit query to only netifcons that use this device, or * NULL to unset this field. * * @return 0 on success, negative on error. */ extern int apol_netifcon_query_set_device(const apol_policy_t * p, apol_netifcon_query_t * n, const char *dev); /** * Set a netifcon query to return only netifcons matching this context * for its interface. This function takes ownership of the context, * such that the caller must not modify nor destroy it afterwards. * * @param p Policy handler, to report errors. * @param n Netifcon query to set. * @param context Limit query to only netifcon matching this context * for its interface, or NULL to unset this field. * @param range_match Specifies how to match the MLS range within the * context. This must be one of APOL_QUERY_SUB, APOL_QUERY_SUPER, or * APOL_QUERY_EXACT. This parameter is ignored if context is NULL. * * @return Always returns 0. */ extern int apol_netifcon_query_set_if_context(const apol_policy_t * p, apol_netifcon_query_t * n, apol_context_t * context, unsigned int range_match); /** * Set a netifcon query to return only netifcons matching this context * for its messages. This function takes ownership of the context, * such that the caller must not modify nor destroy it afterwards. * * @param p Policy handler, to report errors. * @param n Netifcon query to set. * @param context Limit query to only netifcon matching this context * for its messages, or NULL to unset this field. * @param range_match Specifies how to match the MLS range within the * context. This must be one of APOL_QUERY_SUB, APOL_QUERY_SUPER, or * APOL_QUERY_EXACT. This parameter is ignored if context is NULL. * * @return Always returns 0. */ extern int apol_netifcon_query_set_msg_context(const apol_policy_t * p, apol_netifcon_query_t * n, apol_context_t * context, unsigned int range_match); /** * Creates a string containing the textual representation of * a netifcon type. * @param p Reference to a policy. * @param netifcon Reference to the netifcon statement to be rendered. * * @return A newly allocated string on success, caller must free; * NULL on error. */ extern char *apol_netifcon_render(const apol_policy_t * p, const qpol_netifcon_t * netifcon); /******************** nodecon queries ********************/ /** * Execute a query against all nodecons within the policy. The * returned nodecons will be unordered. * * @param p Policy within which to look up nodecons. * @param n Structure containing parameters for query. If this is * NULL then return all nodecons. * @param v Reference to a vector of qpol_nodecon_t. The vector will * be allocated by this function. The caller must call * apol_vector_destroy() afterwards. This will be set to NULL upon no * results or upon error. * * @return 0 on success (including none found), negative on error. */ extern int apol_nodecon_get_by_query(const apol_policy_t * p, const apol_nodecon_query_t * n, apol_vector_t ** v); /** * Allocate and return a new nodecon query structure. All fields are * initialized, such that running this blank query results in * returning all nodecons within the policy. The caller must call * apol_nodecon_query_destroy() upon the return value afterwards. * * @return An initialized nodecon query structure, or NULL upon * error. */ extern apol_nodecon_query_t *apol_nodecon_query_create(void); /** * Deallocate all memory associated with the referenced nodecon * query, and then set it to NULL. This function does nothing if the * query is already NULL. * * @param n Reference to a nodecon query structure to destroy. */ extern void apol_nodecon_query_destroy(apol_nodecon_query_t ** n); /** * Set a nodecon query to return only nodecons with this protocol, * either IPv4 or IPv6. * * @param p Policy handler, to report errors. * @param n Nodecon query to set. * @param proto Limit query to only this protocol, either QPOL_IPV4 or * QPOL_IPV6, or a negative value to unset this field. * * @return 0 if protocol was valid, -1 on error. */ extern int apol_nodecon_query_set_protocol(const apol_policy_t * p, apol_nodecon_query_t * n, int proto); /** * Set a nodecon query to return only nodecons with this address. If * the protocol is QPOL_IPV4 then only the first element of the * address array is used, for QPOL_IPV6 all four are used. * * @param p Policy handler, to report errors. * @param n Nodecon query to set. * @param addr Array of no more than four elements representing the * address, or NULL to unset this field. This function will make a * copy of the array. * @param proto Format of address, either QPOL_IPV4 or QPOL_IPV6. * This parameter is ignored if addr is NULL. * * @return 0 if protocol was valid, -1 on error. */ extern int apol_nodecon_query_set_addr(const apol_policy_t * p, apol_nodecon_query_t * n, uint32_t * addr, int proto); /** * Set a nodecon query to return only nodecons with this netmask. If * the protocol is QPOL_IPV4 then only the first element of the mask * array is used, for QPOL_IPV6 all four are used. * * @param p Policy handler, to report errors. * @param n Nodecon query to set. * @param mask Array of no more than four elements representing the * netmask, or NULL to unset this field. This function will make a * copy of the array. * @param proto Format of mask, either QPOL_IPV4 or QPOL_IPV6. This * parameter is ignored if mask is NULL. * * @return 0 if protocol was valid, -1 on error. */ extern int apol_nodecon_query_set_mask(const apol_policy_t * p, apol_nodecon_query_t * n, uint32_t * mask, int proto); /** * Set a nodecon query to return only nodecons matching this context. * This function takes ownership of the context, such that the caller * must not modify nor destroy it afterwards. * * @param p Policy handler, to report errors. * @param n Nodecon query to set. * @param context Limit query to only nodecons matching this context, * or NULL to unset this field. * @param range_match Specifies how to match the MLS range within the * context. This must be one of APOL_QUERY_SUB, APOL_QUERY_SUPER, or * APOL_QUERY_EXACT. This parameter is ignored if context is NULL. * * @return Always returns 0. */ extern int apol_nodecon_query_set_context(const apol_policy_t * p, apol_nodecon_query_t * n, apol_context_t * context, unsigned int range_match); /** * Creates a string containing the textual representation of * a nodecon type. * @param p Reference to a policy. * @param nodecon Reference to the nodecon statement to be rendered. * * @return A newly allocated string on success, caller must free; * NULL on error. */ extern char *apol_nodecon_render(const apol_policy_t * p, const qpol_nodecon_t * nodecon); #ifdef __cplusplus } #endif #endif /* APOL_NETCON_QUERY_H */
37.528767
119
0.736458
[ "vector" ]
b74bbae493f161a6ae7819b89b825772215642d5
4,007
h
C
HW7_2/PQ_Heap.h
justin-harper/cs223
487a4d8e803b3cb6a34608a15432e5aabe4894c4
[ "MIT" ]
null
null
null
HW7_2/PQ_Heap.h
justin-harper/cs223
487a4d8e803b3cb6a34608a15432e5aabe4894c4
[ "MIT" ]
null
null
null
HW7_2/PQ_Heap.h
justin-harper/cs223
487a4d8e803b3cb6a34608a15432e5aabe4894c4
[ "MIT" ]
null
null
null
//Justin Harper //10696738 //HW7_Heaps #ifndef PQHEAPH #define PQHEAPH #include "PQBase.h" #include <queue> #include <vector> using namespace std; template <typename T> class PQ_Heap : public PQBase<T> { private: // Declare the private member variables you need here. // Store the heap data in an array or a std::vector. vector <T> m_heap; int m_k = 0; public: PQ_Heap(int k) { // Implement this constructor so that it stores k and uses it in // the appropriate member functions to build a k-ary heap for // the priorty queue. m_k = k; } //if vector is is empty then return 1 bool IsEmpty() const { //empty is a vector member function if (m_heap.empty() == true) { return true; } else { return false; } } void Add(const T& toCopyAndAdd) { //get heap size //size is a vector member funtion int heapSize = m_heap.size(); heapSize++; //push item to vector m_heap.push_back(toCopyAndAdd); //because heap size is 0 at first, so we need to do a -1 SiftUp(heapSize - 1); } bool RemoveMax(T& outputItem) { //cant remove if empty if (m_heap.empty() == true) { return false; } //if size is 2, then no need to do any sifting else if (m_heap.size() <= 2) { //reassign outputItem outputItem = m_heap[0]; //move last entry in heap to the front m_heap[0] = m_heap[m_heap.size() - 1]; //rezie down by 1...as that is nolonger a valid entry in the heap m_heap.resize(m_heap.size() - 1); return true; } //else take the first item and return it to outputitem //then resize it smaller by 1 //and starting shifting down at the top else { //reassign outputItem outputItem = m_heap[0]; //move last item in heap to the front m_heap[0] = m_heap[m_heap.size() - 1]; //rezie heap as last entry is nolonger valid m_heap.resize(m_heap.size() - 1); //now SiftDown to "heapify" ShiftDown(0); return true; } return false; } void SiftUp(int nodeIndex) { //see what the parent index are, and then check to see if parent is less //if parent is less than do the shifting //do shifting until all cases are met int parentIndex; T temp; if (0 != nodeIndex) { parentIndex = GetParentIndex(nodeIndex); //if data at parent is < data at node index if (m_heap[parentIndex] < m_heap[nodeIndex]) { //flip Nodes arround temp = m_heap[parentIndex]; m_heap[parentIndex] = m_heap[nodeIndex]; m_heap[nodeIndex] = temp; //contine sifting SiftUp(parentIndex); } } //value is =, do nothing } int GetParentIndex(int nodeIndex) { //parent index = n-1 / k return (nodeIndex - 1) / m_k; } void ShiftDown(int indexNode) { //FIND the child max //once find the child max value //return the index of the child int count =0; T temp; //first child is located at nk+1 int childIndex = (indexNode*m_k) + 1; //if(nk+1 > m_heap.size()) then indexNode is a leaf node and has no children //since it is a leaf node it is in the correct spot if (childIndex < m_heap.size()) { //index is not a leaf T max_child = m_heap[childIndex]; int length = m_heap.size(); int index = childIndex; for (int i = index + 1; i < index + m_k && i < length; i++) { if (m_heap[i] > max_child) { max_child = m_heap[i]; childIndex = i; } } //now do recursion until all cases are met if (m_heap[indexNode] < m_heap[childIndex]) { temp = m_heap[indexNode]; m_heap[indexNode] = m_heap[childIndex]; m_heap[childIndex] = temp; //go again ShiftDown(childIndex); } } return; } vector<int> GetChildrensIndex(int indexNode) { if (indexNode != 0) { int size = m_k; vector< int > arr; for (int i = 0; i < m_k; i++) { arr.push_back((indexNode * size) + 1); } return arr; } else { vector< int > arr; for (int i = 0; i < m_k; i++) { arr.push_back(i + 1); } return arr; } } }; #endif
18.550926
78
0.626154
[ "vector" ]
b74f14e815a03074cc2c7cad559955d85e2f61a0
2,610
h
C
MVC6SH/Examples/Learnvcn/Chap21/MyDraw10/DrawDoc.h
jdm7dv/MCSD-2000
bdba2928383ece76dca532a04f21179de460ca48
[ "Unlicense" ]
null
null
null
MVC6SH/Examples/Learnvcn/Chap21/MyDraw10/DrawDoc.h
jdm7dv/MCSD-2000
bdba2928383ece76dca532a04f21179de460ca48
[ "Unlicense" ]
null
null
null
MVC6SH/Examples/Learnvcn/Chap21/MyDraw10/DrawDoc.h
jdm7dv/MCSD-2000
bdba2928383ece76dca532a04f21179de460ca48
[ "Unlicense" ]
null
null
null
// DrawDoc.h : interface of the CMyDrawDoc class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_DRAWDOC_H__24958324_5D0A_11D2_991B_00C04FC29F5C__INCLUDED_) #define AFX_DRAWDOC_H__24958324_5D0A_11D2_991B_00C04FC29F5C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Shape.h" class CMyDrawDoc : public CDocument { protected: // create from serialization only CMyDrawDoc(); DECLARE_DYNCREATE(CMyDrawDoc) // Attributes public: void SetToOldestShape() { m_pos = m_listShapes.GetTailPosition(); }; void SetToLatestShape() { m_pos = m_listShapes.GetHeadPosition(); }; CShape* GetPrevShape() { // Sets m_pos to NULL if no shapes or if // latest shape is last in list. return (CShape*)m_listShapes.GetPrev(m_pos); }; CShape* GetNextShape() { // Sets m_pos to NULL if no shapes or if // latest shape is last in list. return (CShape*)m_listShapes.GetNext(m_pos); }; POSITION GetPos() const { // m_pos tells you where you are in a list of the shapes. // Use GetPos with either iteration direction to test for end. return m_pos; // Can be NULL }; int GetCount() const { // Return the number of stored shapes. return m_listShapes.GetCount(); }; private: CObList m_listShapes; // Linked list of all shapes drawn so far POSITION m_pos; // Latest position accessed // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMyDrawDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); virtual void DeleteContents(); //}}AFX_VIRTUAL // Implementation public: void GetDocSizes(int nMapMode, CSize& sizeTotal, CSize& sizePage, CSize& sizeLine); CShape* CreateShape(ShpType st); void DeleteAllShapes(); void DeleteLatestShape(); virtual ~CMyDrawDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMyDrawDoc) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DRAWDOC_H__24958324_5D0A_11D2_991B_00C04FC29F5C__INCLUDED_)
26.632653
97
0.671264
[ "shape" ]
b752d0b3c1b94e3f1d8de497d828c7db114a4d8f
8,849
h
C
dev/Gems/ImageProcessing/Code/Source/Converters/CubeMapGen/VectorMacros.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/ImageProcessing/Code/Source/Converters/CubeMapGen/VectorMacros.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/ImageProcessing/Code/Source/Converters/CubeMapGen/VectorMacros.h
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once //-------------------------------------------------------------------------------------- // VectorMacros.h // // Fast operations on vectors, stored as arrays of floats // //-------------------------------------------------------------------------------------- // (C) 2001-2005 ATI Research, Inc. All rights reserved. //-------------------------------------------------------------------------------------- // modifications by Crytek GmbH //disable warning about doubles being converted down to float #pragma warning (disable : 4244 ) #define VM_LARGE_FLOAT 3.7e37f #define VM_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define VM_MAX(a, b) (((a) > (b)) ? (a) : (b)) //clamping macros #define VM_CLAMP(d, s, mn, mx){(d) = ((s)<(mx))?( ((s)>(mn))?(s):(mn) ):(mx); } #define VM_CLAMP2_UNTYPED(d, s, mn, mx) {VM_CLAMP(d[0], s[0], mn, mx); VM_CLAMP(d[1], s[1], mn, mx);} #define VM_CLAMP2(d, s, mn, mx) VM_CLAMP2_UNTYPED(((float *)(d)), ((float *)(s)), (float)(mn), (float)(mx)) #define VM_CLAMP3_UNTYPED(d, s, mn, mx) {VM_CLAMP(d[0], s[0], mn, mx); VM_CLAMP(d[1], s[1], mn, mx); VM_CLAMP(d[2], s[2], mn, mx);} #define VM_CLAMP3(d, s, mn, mx) VM_CLAMP3_UNTYPED(((float *)(d)), ((float *)(s)), (float)(mn), (float)(mx)) #define VM_CLAMP4_UNTYPED(d, s, mn, mx) {VM_CLAMP(d[0], s[0], mn, mx); VM_CLAMP(d[1], s[1], mn, mx); VM_CLAMP(d[2], s[2], mn, mx); VM_CLAMP(d[3], s[3], mn, mx);} #define VM_CLAMP4(d, s, mn, mx) VM_CLAMP4_UNTYPED(((float *)(d)), ((float *)(s)), (float)(mn), (float)(mx)) //set vectors #define VM_SET2_UNTYPED(d, f) { d[0]=f; d[1]=f;} #define VM_SET2(d, f) VM_SET2_UNTYPED(((float *)(d)), ((float)(f))) #define VM_SET3_UNTYPED(d, f) { d[0]=f; d[1]=f; d[2]=f; } #define VM_SET3(d, f) VM_SET3_UNTYPED(((float *)(d)), ((float)(f))) #define VM_SET4_UNTYPED(d, f) { d[0]=f; d[1]=f; d[2]=f; d[3]=f; } #define VM_SET4(d, f) VM_SET4_UNTYPED(((float *)(d)), ((float)(f))) //copy vectors #define VM_COPY2_UNTYPED(d, s) { d[0]=s[0]; d[1]=s[1];} #define VM_COPY2(d, s) VM_COPY2_UNTYPED(((float *)(d)), ((float *)(s))) #define VM_COPY3_UNTYPED(d, s) { d[0]=s[0]; d[1]=s[1]; d[2]=s[2]; } #define VM_COPY3(d, s) VM_COPY3_UNTYPED(((float *)(d)), ((float *)(s))) #define VM_COPY4_UNTYPED(d, s) { d[0]=s[0]; d[1]=s[1]; d[2]=s[2]; d[3]=s[3]; } #define VM_COPY4(d, s) VM_COPY4_UNTYPED(((float *)(d)), ((float *)(s))) //add two vectors #define VM_ADD2_UNTYPED(d, sa, sb) { d[0]=sa[0]+sb[0]; d[1]=sa[1]+sb[1]; } #define VM_ADD2(d, sa, sb) VM_ADD3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) #define VM_ADD3_UNTYPED(d, sa, sb) { d[0]=sa[0]+sb[0]; d[1]=sa[1]+sb[1]; d[2]=sa[2]+sb[2]; } #define VM_ADD3(d, sa, sb) VM_ADD3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) #define VM_ADD4_UNTYPED(d, sa, sb) { d[0]=sa[0]+sb[0]; d[1]=sa[1]+sb[1]; d[2]=sa[2]+sb[2]; d[3]=sa[3]+sb[3]; } #define VM_ADD4(d, sa, sb) VM_ADD4_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) //subtract two vectors #define VM_SUB2_UNTYPED(d, sa, sb) { d[0]=sa[0]-sb[0]; d[1]=sa[1]-sb[1]; } #define VM_SUB2(d, sa, sb) VM_SUB2_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) #define VM_SUB3_UNTYPED(d, sa, sb) { d[0]=sa[0]-sb[0]; d[1]=sa[1]-sb[1]; d[2]=sa[2]-sb[2]; } #define VM_SUB3(d, sa, sb) VM_SUB3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) #define VM_SUB4_UNTYPED(d, sa, sb) { d[0]=sa[0]-sb[0]; d[1]=sa[1]-sb[1]; d[2]=sa[2]-sb[2]; d[3]=sa[3]-sb[3]; } #define VM_SUB4(d, sa, sb) VM_SUB4_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) //multiply all elements of a vector by a scalar #define VM_SCALE2_UNTYPED(d, s, f) {d[0]=s[0]*f; d[1]=s[1]*f; } #define VM_SCALE2(d, s, f) VM_SCALE2_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f)) ) #define VM_SCALE3_UNTYPED(d, s, f) {d[0]=s[0]*f; d[1]=s[1]*f; d[2]=s[2]*f; } #define VM_SCALE3(d, s, f) VM_SCALE3_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f)) ) #define VM_SCALE4_UNTYPED(d, s, f) {d[0]=s[0]*f; d[1]=s[1]*f; d[2]=s[2]*f; d[3]=s[3]*f; } #define VM_SCALE4(d, s, f) VM_SCALE4_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f)) ) //add a scalar to all elements of a vector #define VM_BIAS2_UNTYPED(d, s, f) { d[0]=s[0]+f; d[1]=s[1]+f; } #define VM_BIAS2(d, s, f) VM_BIAS2_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f))) #define VM_BIAS3_UNTYPED(d, s, f) { d[0]=s[0]+f; d[1]=s[1]+f; d[2]=s[2]+f; } #define VM_BIAS3(d, s, f) VM_BIAS3_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f))) #define VM_BIAS4_UNTYPED(d, s, f) { d[0]=s[0]+f; d[1]=s[1]+f; d[2]=s[2]+f; d[3]=s[3]+f; } #define VM_BIAS4(d, s, f) VM_BIAS4_UNTYPED(((float *)(d)), ((float *)(s)), ((float)(f))) //3D cross product #define VM_XPROD3_UNTYPED(d, sa, sb) { d[0]=sa[1]*sb[2]-sa[2]*sb[1]; d[1]=sa[2]*sb[0]-sa[0]*sb[2]; d[2]=sa[0]*sb[1]-sa[1]*sb[0]; } #define VM_XPROD3(d, sa, sb) VM_XPROD3_UNTYPED(((float *)(d)), ((float *)(sa)), ((float *)(sb))) //dot products #define VM_DOTPROD2_UNTYPED(sa, sb) (sa[0]*sb[0]+ sa[1]*sb[1]) #define VM_DOTPROD2(sa, sb) VM_DOTPROD2_UNTYPED(((float *)(sa)), ((float *)(sb))) #define VM_DOTPROD3_UNTYPED(sa, sb) (sa[0]*sb[0]+ sa[1]*sb[1]+ sa[2]*sb[2]) #define VM_DOTPROD3(sa, sb) VM_DOTPROD3_UNTYPED(((float *)(sa)), ((float *)(sb))) #define VM_DOTPROD4_UNTYPED(sa, sb) (sa[0]*sb[0]+ sa[1]*sb[1]+ sa[2]*sb[2] + sa[3]*sb[3]) #define VM_DOTPROD4(sa, sb) VM_DOTPROD4_UNTYPED(((float *)(sa)), ((float *)(sb))) //dp3 then and add 4th component from second arguement #define VM_DOTPROD3ADD_UNTYPED(pt, pl) (pt[0]*pl[0]+ pt[1]*pl[1]+ pt[2]*pl[2] + pl[3]) #define VM_DOTPROD3ADD(pt, pl) VM_DOTPROD3ADD_UNTYPED(((float *)(pt)), ((float *)(pl))) //normalize vectors #define VM_NORM3_UNTYPED(d, s) {double __idsq; __idsq=1.0/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } #define VM_NORM3_UNTYPED_F32(d, s) {float __idsq; __idsq=1.0/sqrt(VM_DOTPROD3_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } #define VM_NORM3(d, s) VM_NORM3_UNTYPED_F32(((float *)(d)), ((float *)(s))) #define VM_NORM4_UNTYPED(d, s) {double __idsq; __idsq=1.0/sqrt(VM_DOTPROD4_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; d[3]=s[3]*__idsq; } #define VM_NORM4_UNTYPED_F32(d, s) {float __idsq; __idsq=1.0/sqrt(VM_DOTPROD4_UNTYPED(s,s)); d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; d[3]=s[3]*__idsq; } #define VM_NORM4(d, s) VM_NORM4_UNTYPED_F32(((float *)(d)), ((float *)(s))) //safely normalize vectors, deal with 0 length case #define VM_SAFENORM3_UNTYPED(d, s) {float __idsq, __dp; __dp = VM_DOTPROD3_UNTYPED(s,s); \ __idsq=( (__dp > 0.0f)?(1.0/sqrt(__dp)):0.0f ) ; d[0]=s[0]*__idsq; d[1]=s[1]*__idsq; d[2]=s[2]*__idsq; } #define VM_SAFENORM3(d, s) VM_NORM3_UNTYPED_F32(((float *)(d)), ((float *)(s))) //absolute value #define VM_ABS2_UNTYPED(d, s) { d[0] = fabs(s[0]); d[1] = fabs(s[1]); } #define VM_ABS2(d, s) VM_ABS2_UNTYPED(((float *)(d)), ((float *)(s)) ) #define VM_ABS3_UNTYPED(d, s) { d[0] = fabs(s[0]); d[1] = fabs(s[1]); d[2] = fabs(s[2]); } #define VM_ABS3(d, s) VM_ABS3_UNTYPED(((float *)(d)), ((float *)(s)) ) #define VM_ABS4_UNTYPED(d, s) { d[0] = fabs(s[0]); d[1] = fabs(s[1]); d[2] = fabs(s[2]); d[3] = fabs(s[3]); } #define VM_ABS4(d, s) VM_ABS4_UNTYPED(((float *)(d)), ((float *)(s)) ) //projection of a vector onto another vector (assumes vector v is normalized) // computes d, which is the parallel component of s onto vector v #define VM_PROJ3_UNTYPED(d, s, v) { double __dp; __dp = VM_DOTPROD3_UNTYPED(s, v); VM_SCALE3_UNTYPED(d, s, __dp); } #define VM_PROJ3(d, s, v) VM_PROJ3_UNTYPED(((float *)(d)), ((float *)(s)), ((float *)(v)) ) #define VM_PROJ3_F64(d, s, v) VM_PROJ3_UNTYPED(((double *)(d)), ((double *)(s)), ((double *)(v)) ) //compute component of a vector perpendicular to another vector // d is perpendicular component of s onto vector v // this macro first computes the parallel projection, then subtracts off from the original vector // to obtain the perpendicular component #define VM_PERP3_UNTYPED(d, s, v) {double __proj[3]; VM_PROJ3_UNTYPED(__proj, s, v); VM_SUB3_UNTYPED(d, s, __proj); } #define VM_PERP3(d, s, v) VM_PERP3_UNTYPED(((float *)(d)), ((float *)(s)), ((float *)(v)) ) #define VM_PERP3_F64(d, s, v) VM_PERP3_UNTYPED(((double *)(d)), ((double *)(s)), ((double *)(v)) )
49.99435
166
0.592044
[ "vector", "3d" ]
b75484ac3d6dc716110cc4415725302f5968bd25
7,094
c
C
Minix3/commands/simple/udpstat.c
Angold-4/OSDI
3424282923559c9b0c4b5ecf7008370e43961bab
[ "MIT" ]
12
2020-09-01T07:07:33.000Z
2022-03-30T11:16:20.000Z
Minix3/commands/simple/udpstat.c
Angold-4/OSDI
3424282923559c9b0c4b5ecf7008370e43961bab
[ "MIT" ]
null
null
null
Minix3/commands/simple/udpstat.c
Angold-4/OSDI
3424282923559c9b0c4b5ecf7008370e43961bab
[ "MIT" ]
4
2020-09-14T08:14:37.000Z
2021-12-19T07:18:30.000Z
/* udpstat.c Created: March 2001 by Philip Homburg <philip@f-mnx.phicoh.com> */ #define _MINIX_SOURCE #define _POSIX_C_SOURCE 2 #include <inet/inet.h> #undef printf #include <assert.h> #include <fcntl.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <sys/svrctl.h> #ifndef __minix_vmd #include <sys/times.h> #endif #include <net/netlib.h> #include <net/gen/inet.h> #include <net/gen/netdb.h> #include <net/gen/socket.h> #include <minix/queryparam.h> #include <inet/generic/buf.h> #include <inet/generic/clock.h> #include <inet/generic/event.h> #include <inet/generic/type.h> #include <inet/generic/udp_int.h> char *prog_name; udp_fd_t udp_fd_table[UDP_FD_NR]; udp_port_t *udp_port_table; udp_port_t *udp_port_tablep; size_t udp_port_table_s; size_t udp_port_table_rs; int udp_port_nr; char values[6 * sizeof(void *) + 3]; char *valuesl= NULL; size_t v_size; int inclSel, numerical; void print_fd(int i, clock_t now); void usage(void); int main(int argc, char*argv[]) { char *ipstat_device; int fd, i, r; size_t psize; char *pval, *param; struct timeval uptime; clock_t now; int fl; int a_flag, n_flag; struct tms tmsbuf; (prog_name=strrchr(argv[0], '/')) ? prog_name++ : (prog_name=argv[0]); a_flag= 0; n_flag= 0; while ((fl= getopt(argc, argv, "?an")) != -1) { switch(fl) { case '?': usage(); case 'a': a_flag= 1; break; case 'n': n_flag= 1; break; default: fprintf(stderr, "%s: getopt failed: '%c'\n", prog_name, fl); exit(1); } } inclSel= !!a_flag; numerical= !!n_flag; ipstat_device= IPSTAT_DEVICE; if ((fd= open(ipstat_device, O_RDWR)) == -1) { fprintf(stderr, "%s: unable to open '%s': %s\n", prog_name, ipstat_device, strerror(errno)); exit(1); } v_size= 2*sizeof(udp_fd_table)+1; valuesl= realloc(valuesl, v_size); if (!valuesl) { fprintf(stderr, "%s: unable to malloc %u bytes for valuesl\n", prog_name, v_size); exit(1); } param= "udp_fd_table"; psize= strlen(param); r= write(fd, param, psize); if (r != psize) { fprintf(stderr, "%s: write to %s failed: %s\n", prog_name, ipstat_device, r < 0 ? strerror(errno) : "short write"); exit(1); } r= read(fd, valuesl, v_size); if (r < 0) { fprintf(stderr, "%s: read from %s failed: %s\n", prog_name, ipstat_device, strerror(errno)); exit(1); } pval= valuesl; if (paramvalue(&pval, udp_fd_table, sizeof(udp_fd_table)) != sizeof(udp_fd_table)) { fprintf(stderr, "%s: unable to decode the results from queryparam (udp_fd_table)\n", prog_name); exit(1); } /* Get address, size, and element size of the UDP port table */ param = "&udp_port_table,$udp_port_table,$udp_port_table[0]"; psize = strlen(param); r= write(fd, param, psize); if (r != psize) { fprintf(stderr, "%s: write to %s failed: %s\n", prog_name, ipstat_device, r < 0 ? strerror(errno) : "short write"); exit(1); } r= read(fd, values, sizeof(values)); if (r < 0) { fprintf(stderr, "%s: read from %s failed: %s\n", prog_name, ipstat_device, strerror(errno)); exit(1); } pval= values; if (paramvalue(&pval, &udp_port_tablep, sizeof(udp_port_tablep)) != sizeof(udp_port_tablep) || paramvalue(&pval, &udp_port_table_s, sizeof(udp_port_table_s)) != sizeof(udp_port_table_s) || paramvalue(&pval, &udp_port_table_rs, sizeof(udp_port_table_rs)) != sizeof(udp_port_table_rs)) { fprintf(stderr, "%s: unable to decode the results from queryparam (&udp_port_table, ...)\n", prog_name); exit(1); } if (udp_port_table_rs != sizeof(udp_port_table[0])) { fprintf(stderr, "%s: size mismatch in udp_port_table (different version of inet?)\n", prog_name); exit(1); } udp_port_nr= udp_port_table_s/udp_port_table_rs; assert(udp_port_table_s == udp_port_nr*udp_port_table_rs); udp_port_table= malloc(udp_port_table_s); if (!udp_port_table) { fprintf(stderr, "%s: unable to malloc %u bytes for udp_port_table\n", prog_name, udp_port_table_s); exit(1); } v_size= 2*udp_port_table_s+1; valuesl= realloc(valuesl, v_size); if (!valuesl) { fprintf(stderr, "%s: unable to malloc %u bytes for valuesl\n", prog_name, v_size); exit(1); } param = "udp_port_table"; psize = strlen(param); r= write(fd, param, psize); if (r != psize) { fprintf(stderr, "%s: write to %s failed: %s\n", prog_name, ipstat_device, r < 0 ? strerror(errno) : "short write"); exit(1); } r= read(fd, valuesl, v_size); if (r < 0) { fprintf(stderr, "%s: read from %s failed: %s\n", prog_name, ipstat_device, strerror(errno)); exit(1); } pval= valuesl; if (paramvalue(&pval, udp_port_table, udp_port_table_s) != udp_port_table_s) { fprintf(stderr, "%s: unable to decode the results from queryparam (udp_port_table)\n", prog_name); exit(1); } /* Get the uptime in clock ticks. */ #ifdef __minix_vmd if (sysutime(UTIME_UPTIME, &uptime) == -1) { fprintf(stderr, "%s: sysutime failed: %s\n", prog_name, strerror(errno)); exit(1); } now= uptime.tv_sec * HZ + (uptime.tv_usec*HZ/1000000); #else /* Minix 3 */ now= times(&tmsbuf); #endif for (i= 0; i<UDP_FD_NR; i++) print_fd(i, now); exit(0); } void print_fd(int i, clock_t now) { unsigned long nwuo_flags; int port_nr; udp_fd_t *udp_fd; udp_port_t *udp_port; char *locaddr_str, *remaddr_str; struct hostent *hostent; struct servent *servent; nwio_udpopt_t uf_udpopt; udp_fd= &udp_fd_table[i]; if (!(udp_fd->uf_flags & UFF_INUSE)) return; uf_udpopt= udp_fd->uf_udpopt; nwuo_flags= uf_udpopt.nwuo_flags; if (((nwuo_flags & NWUO_LOCPORT_MASK) != NWUO_LP_SET) && !inclSel) return; port_nr= udp_fd->uf_port-udp_port_tablep; udp_port= &udp_port_table[port_nr]; printf("%3d", i); if (nwuo_flags & NWUO_EN_LOC) { if (!numerical && (hostent= gethostbyaddr((char *)&udp_port->up_ipaddr, sizeof(ipaddr_t), AF_INET)) != NULL) { locaddr_str= hostent->h_name; } else locaddr_str= inet_ntoa(udp_port->up_ipaddr); } else if (nwuo_flags & NWUO_EN_BROAD) locaddr_str= "255.255.255.255"; else locaddr_str= "0.0.0.0"; printf(" %s:", locaddr_str); if ((nwuo_flags & NWUO_LOCPORT_MASK) != NWUO_LP_SEL && (nwuo_flags & NWUO_LOCPORT_MASK) != NWUO_LP_SET) { printf("*"); } else if ((servent= getservbyport(uf_udpopt.nwuo_locport, "udp")) != NULL) { printf("%s", servent->s_name); } else printf("%u", ntohs(uf_udpopt.nwuo_locport)); printf(" -> "); if (!(nwuo_flags & NWUO_RA_SET)) remaddr_str= "*"; else if (!numerical && (hostent= gethostbyaddr((char *)&uf_udpopt.nwuo_remaddr, sizeof(ipaddr_t), AF_INET)) != NULL) { remaddr_str= hostent->h_name; } else remaddr_str= inet_ntoa(uf_udpopt.nwuo_remaddr); printf("%s:", remaddr_str); if (!(nwuo_flags & NWUO_RP_SET)) printf("*"); else if ((servent= getservbyport(uf_udpopt.nwuo_remport, "udp")) != NULL) { printf("%s", servent->s_name); } else printf("%u", ntohs(uf_udpopt.nwuo_remport)); printf("\n"); } void usage(void) { fprintf(stderr, "Usage: %s [-a] [-n]\n", prog_name); exit(1); } /* * $PchId: udpstat.c,v 1.4 2005/01/30 01:04:57 philip Exp $ */
21.962848
76
0.667043
[ "3d" ]
b75535d74b68a4191c27fdc5f424e8565be3de1a
2,581
h
C
Engine/Plugins/Media/WmfMedia/Source/WmfMedia/Private/Player/WmfMediaPlayer.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/Media/WmfMedia/Source/WmfMedia/Private/Player/WmfMediaPlayer.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/Media/WmfMedia/Source/WmfMedia/Private/Player/WmfMediaPlayer.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "WmfMediaPrivate.h" #if WMFMEDIA_SUPPORTED_PLATFORM #include "Containers/UnrealString.h" #include "IMediaCache.h" #include "IMediaPlayer.h" #include "IMediaView.h" #include "Misc/Timespan.h" #include "AllowWindowsPlatformTypes.h" class FWmfMediaSession; class FWmfMediaTracks; class IMediaEventSink; /** * Implements a media player using the Windows Media Foundation framework. */ class FWmfMediaPlayer : public IMediaPlayer , protected IMediaCache , protected IMediaView { public: /** * Create and initialize a new instance. * * @param InEventSink The object that receives media events from this player. */ FWmfMediaPlayer(IMediaEventSink& InEventSink); /** Virtual destructor. */ virtual ~FWmfMediaPlayer(); public: //~ IMediaPlayer interface virtual void Close() override; virtual IMediaCache& GetCache() override; virtual IMediaControls& GetControls() override; virtual FString GetInfo() const override; virtual FName GetPlayerName() const override; virtual IMediaSamples& GetSamples() override; virtual FString GetStats() const override; virtual IMediaTracks& GetTracks() override; virtual FString GetUrl() const override; virtual IMediaView& GetView() override; virtual bool Open(const FString& Url, const IMediaOptions* Options) override; virtual bool Open(const TSharedRef<FArchive, ESPMode::ThreadSafe>& Archive, const FString& OriginalUrl, const IMediaOptions* Options) override; virtual void TickFetch(FTimespan DeltaTime, FTimespan Timecode) override; virtual void TickInput(FTimespan DeltaTime, FTimespan Timecode) override; protected: /** * Initialize the native AvPlayer instance. * * @param Archive The archive being used as a media source (optional). * @param Url The media URL being opened. * @param Precache Whether to precache media into RAM if InURL is a local file. * @return true on success, false otherwise. */ bool InitializePlayer(const TSharedPtr<FArchive, ESPMode::ThreadSafe>& Archive, const FString& Url, bool Precache); private: /** The duration of the currently loaded media. */ FTimespan Duration; /** The media event handler. */ IMediaEventSink& EventSink; /** The URL of the currently opened media. */ FString MediaUrl; /** Asynchronous callback object for the media session. */ TComPtr<FWmfMediaSession> Session; /** Media streams collection. */ TSharedPtr<FWmfMediaTracks, ESPMode::ThreadSafe> Tracks; }; #include "HideWindowsPlatformTypes.h" #endif //WMFMEDIA_SUPPORTED_PLATFORM
27.457447
144
0.765982
[ "object" ]
b757322016c1d053d461553af2d12bb8f9fa5487
435
h
C
WANetworkRoutingTests/EmployeeCD.h
lorenzopicoli/WANetworkRouting
8e377ccd2bb1aee734e9a99c3d1026ad29f9c078
[ "X11" ]
10
2016-02-26T23:14:00.000Z
2016-07-22T06:31:06.000Z
WANetworkRoutingTests/EmployeeCD.h
lorenzopicoli/WANetworkRouting
8e377ccd2bb1aee734e9a99c3d1026ad29f9c078
[ "X11" ]
null
null
null
WANetworkRoutingTests/EmployeeCD.h
lorenzopicoli/WANetworkRouting
8e377ccd2bb1aee734e9a99c3d1026ad29f9c078
[ "X11" ]
3
2016-10-20T17:58:15.000Z
2020-06-07T20:15:26.000Z
// // EmployeeCD.h // WAMapping // // Created by Marian Paul on 16-02-16. // Copyright © 2016 Wasappli. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class EnterpriseCD; NS_ASSUME_NONNULL_BEGIN @interface EmployeeCD : NSManagedObject // Insert code here to declare functionality of your managed object subclass @end NS_ASSUME_NONNULL_END #import "EmployeeCD+CoreDataProperties.h"
17.4
76
0.76092
[ "object" ]
b75d28bcccafb5e6324614121edaf39415a1f3f1
823
h
C
aws-cpp-sdk-fms/include/aws/fms/model/MarketplaceSubscriptionOnboardingStatus.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-fms/include/aws/fms/model/MarketplaceSubscriptionOnboardingStatus.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-fms/include/aws/fms/model/MarketplaceSubscriptionOnboardingStatus.h
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/fms/FMS_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace FMS { namespace Model { enum class MarketplaceSubscriptionOnboardingStatus { NOT_SET, NO_SUBSCRIPTION, NOT_COMPLETE, COMPLETE }; namespace MarketplaceSubscriptionOnboardingStatusMapper { AWS_FMS_API MarketplaceSubscriptionOnboardingStatus GetMarketplaceSubscriptionOnboardingStatusForName(const Aws::String& name); AWS_FMS_API Aws::String GetNameForMarketplaceSubscriptionOnboardingStatus(MarketplaceSubscriptionOnboardingStatus value); } // namespace MarketplaceSubscriptionOnboardingStatusMapper } // namespace Model } // namespace FMS } // namespace Aws
24.939394
127
0.800729
[ "model" ]
b7628385b3b8b97e2b993d8c583df7d019248834
4,350
h
C
be/src/storage/in_predicate_utils.h
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
1
2022-03-08T09:13:32.000Z
2022-03-08T09:13:32.000Z
be/src/storage/in_predicate_utils.h
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
null
null
null
be/src/storage/in_predicate_utils.h
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
null
null
null
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. #pragma once #include "column/hash_set.h" #include "runtime/decimalv3.h" #include "storage/type_traits.h" #include "storage/types.h" #include "util/string_parser.hpp" namespace starrocks::vectorized { namespace in_pred_utils_detail { template <typename T> struct PHashSetTraits { using SetType = HashSet<T>; }; template <> struct PHashSetTraits<Slice> { using SetType = SliceNormalHashSet; }; template <typename T> using PHashSet = typename PHashSetTraits<T>::SetType; } // namespace in_pred_utils_detail template <typename T> struct ItemHashSet : public in_pred_utils_detail::PHashSet<T> { bool contains(const T& v) const { return in_pred_utils_detail::PHashSet<T>::contains(v); } }; template <typename T, size_t N> struct ArraySet : public std::array<T, N> { static_assert(N <= 4 && N >= 1); bool contains(const T& v) const noexcept { const T* const ptr = this->data(); if constexpr (N == 1) { return v == ptr[0]; } if constexpr (N == 2) { return (v == ptr[0]) | (v == ptr[1]); } if constexpr (N == 3) { return (v == ptr[0]) | (v == ptr[1]) | (v == ptr[2]); } if constexpr (N == 4) { return (v == ptr[0]) | (v == ptr[1]) | (v == ptr[2]) | (v == ptr[3]); } CHECK(false) << "unreachable path"; return false; } }; namespace predicate_internal { template <typename T> class Converter { public: void push_back(const T& v) { _elements.push_back(v); } template <typename Container, typename = typename std::enable_if_t<std::is_same_v<T, typename Container::value_type>>> operator Container() const { return convert_to_container<Container>()(_elements); } private: template <typename Container> struct convert_to_container { Container operator()(const std::vector<T>& elems) { Container c; for (const T& v : elems) { c.push_back(v); } return c; } }; template <typename U> struct convert_to_container<ItemHashSet<U>> { ItemHashSet<U> operator()(const std::vector<T>& elems) { ItemHashSet<U> c; for (const T& v : elems) { c.emplace(v); } return c; } }; template <size_t N> struct convert_to_container<ArraySet<T, N>> { ArraySet<T, N> operator()(const std::vector<T>& elems) { ArraySet<T, N> c; for (size_t i = 0; i < N; i++) { c[i] = elems[i]; } return c; } }; std::vector<T> _elements; }; template <FieldType field_type> inline Converter<typename CppTypeTraits<field_type>::CppType> strings_to_set(const std::vector<std::string>& strings) { using CppType = typename CppTypeTraits<field_type>::CppType; TypeInfoPtr type_info = get_type_info(field_type); Converter<CppType> result; for (const auto& s : strings) { CppType v; auto st = type_info->from_string(&v, s); DCHECK(st.ok()); result.push_back(v); } return result; } template <FieldType field_type> inline Converter<typename CppTypeTraits<field_type>::CppType> strings_to_decimal_set( int scale, const std::vector<std::string>& strings) { using CppType = typename CppTypeTraits<field_type>::CppType; Converter<CppType> result; for (const auto& s : strings) { CppType v; auto st = DecimalV3Cast::from_string_with_overflow_allowed<CppType>(&v, scale, s.data(), s.size()); CHECK_EQ(false, st); result.push_back(v); } return result; } template <FieldType field_type> inline ItemHashSet<typename CppTypeTraits<field_type>::CppType> strings_to_hashset( const std::vector<std::string>& strings) { using CppType = typename CppTypeTraits<field_type>::CppType; static TypeInfoPtr type_info = get_type_info(field_type); ItemHashSet<CppType> result; for (const auto& s : strings) { CppType v; auto st = type_info->from_string(&v, s); result.emplace(v); } return result; } } // namespace predicate_internal } // namespace starrocks::vectorized
28.431373
119
0.613103
[ "vector" ]
b7684713c47196a18df7dcd6139ee4b7277fb336
1,766
h
C
content/browser/android/selection_popup_controller.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
content/browser/android/selection_popup_controller.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/android/selection_popup_controller.h
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.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 CONTENT_BROWSER_ANDROID_SELECTION_POPUP_CONTROLLER_H_ #define CONTENT_BROWSER_ANDROID_SELECTION_POPUP_CONTROLLER_H_ #include <jni.h> #include "base/android/jni_weak_ref.h" #include "content/browser/android/render_widget_host_connector.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/touch_selection/selection_event_type.h" namespace content { class RenderWidgetHostViewAndroid; struct ContextMenuParams; class SelectionPopupController : public RenderWidgetHostConnector { public: SelectionPopupController(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, WebContents* web_contents); // RendetWidgetHostConnector implementation. void UpdateRenderProcessConnection( RenderWidgetHostViewAndroid* old_rwhva, RenderWidgetHostViewAndroid* new_rhwva) override; // Called from native -> java void OnSelectionEvent(ui::SelectionEventType event, const gfx::RectF& selection_rect); void OnSelectionChanged(const std::string& text); bool ShowSelectionMenu(const ContextMenuParams& params, int handle_height); void OnShowUnhandledTapUIIfNeeded(int x_dip, int y_dip, float dip_scale); void OnSelectWordAroundCaretAck(bool did_select, int start_adjust, int end_adjust); private: ~SelectionPopupController() override {} JavaObjectWeakGlobalRef java_obj_; }; bool RegisterSelectionPopupController(JNIEnv* env); } // namespace content #endif // CONTENT_BROWSER_ANDROID_SELECTION_POPUP_CONTROLLER_H_
34.627451
77
0.746319
[ "geometry" ]
b768eff0f8f1baac46ca48778f9bc833356a3447
7,917
h
C
usr/include/Poco/Data/Binding.h
Roboy/roboy_controlled_node_fpga
dbba4eff19ed04469a6196ba368cea231cad539d
[ "BSD-3-Clause" ]
2
2018-12-11T16:35:20.000Z
2019-01-23T16:42:17.000Z
usr/include/Poco/Data/Binding.h
Roboy/roboy_managing_node_fpga
64ffe5aec2f2c98a051bb1a881849c195b8d052c
[ "BSD-3-Clause" ]
1
2018-12-28T21:11:50.000Z
2018-12-28T21:11:50.000Z
usr/include/Poco/Data/Binding.h
Roboy/roboy_managing_node_fpga
64ffe5aec2f2c98a051bb1a881849c195b8d052c
[ "BSD-3-Clause" ]
3
2018-01-21T17:53:17.000Z
2021-09-08T10:22:05.000Z
// // Binding.h // // $Id: //poco/1.3/Data/include/Poco/Data/Binding.h#1 $ // // Library: Data // Package: DataCore // Module: Binding // // Definition of the Binding class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Binding_INCLUDED #define Data_Binding_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractBinding.h" #include "Poco/Data/DataException.h" #include "Poco/Data/TypeHandler.h" #include <set> #include <vector> #include <map> #include <cstddef> namespace Poco { namespace Data { template <class T> class Binding: public AbstractBinding /// A Binding maps a value to a column. { public: explicit Binding(const T& val): _val(val), _bound(false) /// Creates the Binding. { } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler<T>::size(); } std::size_t numOfRowsHandled() const { return 1; } bool canBind() const { return !_bound; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); TypeHandler<T>::bind(pos, _val, getBinder()); _bound = true; } void reset () { _bound = false; } private: const T& _val; bool _bound; }; template <class T> class Binding<std::vector<T> >: public AbstractBinding /// Specialization for std::vector. { public: explicit Binding(const std::vector<T>& val): _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler<T>::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler<T>::bind(pos, *_begin, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::vector<T>& _val; typename std::vector<T>::const_iterator _begin; typename std::vector<T>::const_iterator _end; }; template <class T> class Binding<std::set<T> >: public AbstractBinding /// Specialization for std::set. { public: explicit Binding(const std::set<T>& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler<T>::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler<T>::bind(pos, *_begin, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::set<T>& _val; typename std::set<T>::const_iterator _begin; typename std::set<T>::const_iterator _end; }; template <class T> class Binding<std::multiset<T> >: public AbstractBinding /// Specialization for std::multiset. { public: explicit Binding(const std::multiset<T>& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler<T>::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler<T>::bind(pos, *_begin, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::multiset<T>& _val; typename std::multiset<T>::const_iterator _begin; typename std::multiset<T>::const_iterator _end; }; template <class K, class V> class Binding<std::map<K, V> >: public AbstractBinding /// Specialization for std::map. { public: explicit Binding(const std::map<K, V>& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler<V>::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler<V>::bind(pos, _begin->second, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::map<K, V>& _val; typename std::map<K, V>::const_iterator _begin; typename std::map<K, V>::const_iterator _end; }; template <class K, class V> class Binding<std::multimap<K, V> >: public AbstractBinding /// Specialization for std::multimap. { public: explicit Binding(const std::multimap<K, V>& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler<V>::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler<V>::bind(pos, _begin->second, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::multimap<K, V>& _val; typename std::multimap<K, V>::const_iterator _begin; typename std::multimap<K, V>::const_iterator _end; }; template <typename T> Binding<T>* use(const T& t) /// Convenience function for a more compact Binding creation. { return new Binding<T>(t); } } } // namespace Poco::Data #endif // Data_Binding_INCLUDED
20.779528
117
0.674119
[ "object", "vector" ]
b76b9fa38e716ae17c10dafd16a4dced6f43c3a7
14,271
h
C
bfvmm/include/hve/arch/intel_x64/vcpu.h
fengjixuchui/boxy
f54566eefdc772e41def4bbfbea8a4637a89f3db
[ "MIT" ]
58
2019-03-12T18:32:17.000Z
2022-01-28T15:38:25.000Z
bfvmm/include/hve/arch/intel_x64/vcpu.h
fengjixuchui/boxy
f54566eefdc772e41def4bbfbea8a4637a89f3db
[ "MIT" ]
41
2019-01-15T16:40:53.000Z
2021-07-20T18:26:15.000Z
bfvmm/include/hve/arch/intel_x64/vcpu.h
fengjixuchui/boxy
f54566eefdc772e41def4bbfbea8a4637a89f3db
[ "MIT" ]
16
2018-12-23T14:33:30.000Z
2021-09-06T09:06:33.000Z
// // Copyright (C) 2019 Assured Information Security, Inc. // // 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 VCPU_INTEL_X64_BOXY_H #define VCPU_INTEL_X64_BOXY_H #include <time.h> #include <bfvmm/vcpu/vcpu_manager.h> #include <bfvmm/hve/arch/intel_x64/vcpu.h> #include "domain.h" #include "vmexit/exception.h" #include "vmexit/external_interrupt.h" #include "vmexit/hlt.h" #include "vmexit/io_instruction.h" #include "vmexit/msr.h" #include "vmexit/nmi_window.h" #include "vmexit/preemption_timer.h" #include "vmexit/vmcall.h" #include "vmcall/debug_op.h" #include "vmcall/domain_op.h" #include "vmcall/handle_op.h" #include "vmcall/run_op.h" #include "vmcall/vcpu_op.h" #include "vmcall/vm_kv_op.h" #include "vmcall/vm_management_op.h" #include "vmcall/vm_properties_op.h" #include "vmcall/vm_state_op.h" #include "vmcall/vp_exit_op.h" #include "vmcall/vp_management_op.h" #include "vmcall/vp_properties_op.h" #include "vmcall/vp_state_op.h" #include "emulation/cpuid.h" #include "emulation/mtrr.h" #include "emulation/x2apic.h" #include "virt/vclock.h" #include "virt/virq.h" //------------------------------------------------------------------------------ // Definition //------------------------------------------------------------------------------ namespace boxy::intel_x64 { class vcpu : public bfvmm::intel_x64::vcpu { public: /// Constructor /// /// @expects /// @ensures /// /// @param id the id of this vcpu /// /// @cond /// explicit vcpu( vcpuid::type id, gsl::not_null<domain *> domain); /// @endcond /// Destructor /// /// @expects /// @ensures /// ~vcpu() override; public: //-------------------------------------------------------------------------- // Domain Info //-------------------------------------------------------------------------- /// Is Dom0 /// /// @expects /// @ensures /// /// @return returns true if this is dom0, false otherwise /// VIRTUAL bool is_dom0() const noexcept; /// Is DomU /// /// @expects /// @ensures /// /// @return returns true if this is a domU, false otherwise /// VIRTUAL bool is_domU() const noexcept; /// Domain ID /// /// @expects /// @ensures /// /// @return the vCPU's domid /// VIRTUAL domain::domainid_type domid() const noexcept; //-------------------------------------------------------------------------- // VMCall //-------------------------------------------------------------------------- /// Add VMCall Handler /// /// @expects /// @ensures /// /// @param d the delegate to call when a vmcall exit occurs /// VIRTUAL void add_vmcall_handler(const handler_delegate_t &d); //-------------------------------------------------------------------------- // Hlt //-------------------------------------------------------------------------- /// Add Hlt Handler /// /// @expects /// @ensures /// /// @param d the handler to call when an exit occurs /// VIRTUAL void add_hlt_handler(const handler_delegate_t &d); /// Add Yield Handler /// /// @expects /// @ensures /// /// @param d the handler to call when an exit occurs /// VIRTUAL void add_yield_handler(const handler_delegate_t &d); //-------------------------------------------------------------------------- // Preemption Timer //-------------------------------------------------------------------------- /// Add Preemption Timer Handler /// /// @expects /// @ensures /// /// @param d the handler to call when an exit occurs /// VIRTUAL void add_preemption_timer_handler(const handler_delegate_t &d); //-------------------------------------------------------------------------- // Parent //-------------------------------------------------------------------------- /// Set Parent vCPU /// /// Each vCPU that is executing (not created) must have a parent. The /// only exception to this is the host vCPUs. If a vCPU can no longer /// execute (e.g., from a crash, interrupt, hlt, etc...), the parent /// vCPU is the parent that will be resumed. /// /// @expects /// @ensures /// /// @param id the id of the vCPU to resume /// VIRTUAL void set_parent_vcpu(gsl::not_null<vcpu *> vcpu); /// Get Parent vCPU ID /// /// Returns the vCPU ID for this vCPU's parent. Note that this ID could /// change on every exit. Specifically when the Host OS moves the /// userspace application associated with a guest vCPU. For this reason, /// don't cache this value. It always needs to be looked up. /// /// @expects /// @ensures /// /// @return returns the vcpuid for this vCPU's parent vCPU. /// VIRTUAL vcpu *parent_vcpu() const noexcept; /// Prepare For World Switch /// /// Prepares the vCPU for a world switch. This ensures that portions of /// the vCPU's state is properly restored. /// VIRTUAL void prepare_for_world_switch(); /// Return (Fault) /// /// Return to the parent vCPU (i.e. resume the parent), and tell the parent /// to stop the guest vCPU and report a fault. /// /// @expects /// @ensures /// /// @param error the error code to return to the parent /// VIRTUAL void return_fault(uint64_t error = 0); /// Return (Continue) /// /// Return to the parent vCPU (i.e. resume the parent), and tell the parent /// to resume the guest as fast as possible. This is used to hand control /// back to the parent, even though the guest is not finished yet /// /// @expects /// @ensures /// VIRTUAL void return_continue(); /// Return (Yield) /// /// Return to the parent vCPU (i.e. resume the parent), and tell the parent /// to put the child vCPU asleep for the specified number of nanoseconds /// /// @expects /// @ensures /// /// @param nsec the number of nanoseconds to sleep /// VIRTUAL void return_yield(uint64_t nsec); /// Return (Set Wall Clock) /// /// Return to the parent vCPU (i.e. resume the parent), and tell the parent /// to set the wallclock and then resume back to the guest /// /// @expects /// @ensures /// VIRTUAL void return_set_wallclock(); //-------------------------------------------------------------------------- // Control //-------------------------------------------------------------------------- /// Kill /// /// Tells the vCPU to stop execution. /// /// @expects /// @ensures /// VIRTUAL void kill() noexcept; /// Is Alive /// /// @expects /// @ensures /// /// @return returns true if the vCPU has not been killed, false otherwise /// VIRTUAL bool is_alive() const noexcept; /// Is Killed /// /// @expects /// @ensures /// /// @return returns true if the vCPU has been killed, false otherwise /// VIRTUAL bool is_killed() const noexcept; //-------------------------------------------------------------------------- // Virtual IRQs //-------------------------------------------------------------------------- /// Queue vIRQ /// /// Queues a virtual IRQ to be delivered to a guest VM. Note that this /// will actually queue the Hypervisor Callback Vector IRQ into the /// guest, and then the guest has to VMCall to this class to get the /// vIRQ vector. Also note that all vIRQs are essentially vMSIs so once /// the vIRQ is dequeued, it is gone. /// /// @expects /// @ensures /// VIRTUAL void queue_virtual_interrupt(uint64_t vector); /// Inject vIRQ /// /// Injects a virtual IRQ to be delivered to a guest VM. Note that this /// will actually inject the Hypervisor Callback Vector IRQ into the /// guest, and then the guest has to VMCall to this class to get the /// vIRQ vector. Also note that all vIRQs are essentially vMSIs so once /// the vIRQ is dequeued, it is gone. /// /// @expects /// @ensures /// VIRTUAL void inject_virtual_interrupt(uint64_t vector); //-------------------------------------------------------------------------- // Virtual Clock //-------------------------------------------------------------------------- /// Set Host Wall Clock Real Time Clock /// /// Records the provided wall clock RTC /// /// @expects /// @ensures /// /// @param val the wall clock RTC /// VIRTUAL void set_host_wallclock_rtc(uint64_t sec, uint64_t nsec) noexcept; /// Set Host Wall Clock TSC /// /// Records the wall clock TSC /// /// @expects /// @ensures /// /// @param val the wall clock TSC /// VIRTUAL void set_host_wallclock_tsc(uint64_t val) noexcept; /// Reset Host Wall Clock /// /// Resets the host Wall Clock. Once this is executed, any attempt to /// launch a vCPU (i.e. a vCPU that has never been run, or has been /// cleared) will cause the lanuch to return back to bfexec so that the /// host wall clock can be reread. /// /// Note: /// /// This does not work the same way as the reset_host_wallclock hypercall. /// That hypercall performs the return on-behalf of the guest. This /// performs the return on-behalf of the host. /// /// @expects /// @ensures /// VIRTUAL void reset_host_wallclock(void) noexcept; /// Get the Host Wall Clock /// /// Returns the host's Wall Clock from epoch. This function will throw /// if the set_host_wallclock_rtc and set_host_wallclock_tsc functions /// have not yet been called. /// /// @expects /// @ensures /// /// @return returns the host's Wall Clock from epoch /// VIRTUAL std::pair<struct timespec, uint64_t> get_host_wallclock() const; //-------------------------------------------------------------------------- // Fault //-------------------------------------------------------------------------- /// Halt the vCPU /// /// Halts the vCPU. The default action is to freeze the physical core /// resulting in a hang, but this function can be overrided to provide /// a safer action if possible. /// /// @param str the reason for the halt /// void halt(const std::string &str = {}) override; private: void write_dom0_guest_state(domain *domain); void write_domU_guest_state(domain *domain); void setup_default_register_state(); void setup_default_controls(); void setup_default_handlers(); private: domain *m_domain{}; bool m_killed{}; vcpu *m_parent_vcpu{}; private: exception_handler m_exception_handler; external_interrupt_handler m_external_interrupt_handler; hlt_handler m_hlt_handler; io_instruction_handler m_io_instruction_handler; msr_handler m_msr_handler; nmi_window_handler m_nmi_window_handler; preemption_timer_handler m_preemption_timer_handler; vmcall_handler m_vmcall_handler; run_op_handler m_run_op_handler; debug_op_handler m_debug_op_handler; domain_op_handler m_domain_op_handler; handle_op_handler m_handle_op_handler; vcpu_op_handler m_vcpu_op_handler; vm_kv_op_handler m_vm_kv_op_handler; vm_management_op_handler m_vm_management_op_handler; vm_properties_op_handler m_vm_properties_op_handler; vm_state_op_handler m_vm_state_op_handler; vp_exit_op_handler m_vp_exit_op_handler; vp_management_op_handler m_vp_management_op_handler; vp_properties_op_handler m_vp_properties_op_handler; vp_state_op_handler m_vp_state_op_handler; cpuid_handler m_cpuid_handler; mtrr_handler m_mtrr_handler; x2apic_handler m_x2apic_handler; vclock_handler m_vclock_handler; virq_handler m_virq_handler; }; } //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ // Note: // // Undefine previously defined helper macros. Note that these are used by // each extension to provide quick access to the vcpu in the extension. If // include files are not handled properly, you could end up with the wrong // vcpu, resulting in compilation errors // #ifdef get_vcpu #undef get_vcpu #endif #ifdef vcpu_cast #undef vcpu_cast #endif /// Get Guest vCPU /// /// Gets a guest vCPU from the vCPU manager given a vcpuid /// /// @expects /// @ensures /// /// @return returns a pointer to the vCPU being queried or throws /// and exception. /// #define get_vcpu(a) \ g_vcm->get<boxy::intel_x64::vcpu *>(a, __FILE__ ": invalid boxy vcpuid") /// Boxy vCPU Cast /// /// To keeps things simple, this is a Boxy specific vCPU cast so that we can /// take any vCPU and cast it to a Boxy vCPU. Note that this is a static /// cast since we know that if we are in this code, we are sure we have the /// right vCPU so no dynamic cast is needed. /// #define _v(a) static_cast<boxy::intel_x64::vcpu *>(a) #endif
29.424742
81
0.5727
[ "vector" ]
b76c39172f2fbb0dcba775302e4860442c5fd403
1,458
c
C
Clanger_Test_main.c
larryfraz/Clanger_test_main.c
8989cb34cd2c190770d120d61c3a6874c3216e7d
[ "MIT" ]
null
null
null
Clanger_Test_main.c
larryfraz/Clanger_test_main.c
8989cb34cd2c190770d120d61c3a6874c3216e7d
[ "MIT" ]
null
null
null
Clanger_Test_main.c
larryfraz/Clanger_test_main.c
8989cb34cd2c190770d120d61c3a6874c3216e7d
[ "MIT" ]
null
null
null
#include <msp430.h> /* * main.c */ #define PERIOD (250000/4) // smclk/120 bpm /60 sec*2 ticks per beat #define PULSE_DUR 250000/(1000/20) // 20ms pulse time char cs_hat = BIT1; // closed hat out 2.1 char op_hat = BIT2;// open hat out 2.2 char cy = BIT5;//cymbal pin 1.4 int counter =0; int main(void) { WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer DCOCTL = CALDCO_16MHZ; BCSCTL1 = CALBC1_16MHZ; BCSCTL2 |= DIVS_3; // SMCLK = MCLK / 8 = 2MHZ WDTCTL = WDTPW + WDTHOLD; // Stop WDT _BIS_SR(GIE); // enable interrupts P1DIR |= BIT0 + BIT1 + BIT2 + BIT5; // output P1OUT = 0; TA1CCTL1 = OUTMOD_7; // CCR1 reset/set P2DIR |= BIT1 + BIT2 + BIT5; P2SEL=0; P2OUT = 0; //output 2.2 P2REN = 0xFF; ///ren all pins on P2---new change!!!! TA1CTL = TASSEL_2 + MC_1 + ID_3; // SMCLK, up mode, /8 = 250KHz TA1CCTL0 |= CCIE; TA1CCR0 = PERIOD; ///period should be SMCLK 500k /120bpm*2 ticks per beat return 0; } #pragma vector=TIMER1_A0_VECTOR __interrupt void Timer1_A0 (void){ int i, dummy; char output; TA1CCR0 = PERIOD; if(counter == 6|| counter == 13) output = op_hat; else if(counter ==15) output = cy; else output = cs_hat; counter++; if(counter == 16) counter = 0; P1OUT |= BIT0 + output; //P2OUT |= output; for (i = PULSE_DUR; i>0; i--) ; P1OUT &=~(BIT0 + output); //P2OUT &= ~output; }
25.137931
78
0.58299
[ "vector" ]
b773c639befdd0a9c382e635ba3570b32ccd5ea4
23,707
h
C
wpilibc/Athena/include/CANTalon.h
flamingchickens1540/wpilib-mirror
58a82be5baaf0248ce3161804c9743724f165479
[ "BSD-3-Clause" ]
null
null
null
wpilibc/Athena/include/CANTalon.h
flamingchickens1540/wpilib-mirror
58a82be5baaf0248ce3161804c9743724f165479
[ "BSD-3-Clause" ]
null
null
null
wpilibc/Athena/include/CANTalon.h
flamingchickens1540/wpilib-mirror
58a82be5baaf0248ce3161804c9743724f165479
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2014-2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #pragma once #include "SafePWM.h" #include "CANSpeedController.h" #include "PIDOutput.h" #include "PIDSource.h" #include "PIDInterface.h" #include "HAL/CanTalonSRX.h" #include "MotorSafetyHelper.h" #include "LiveWindow/LiveWindowSendable.h" #include "tables/ITable.h" #include <memory> /** * CTRE Talon SRX Speed Controller with CAN Control */ class CANTalon : public MotorSafety, public CANSpeedController, public ErrorBase, public LiveWindowSendable, public ITableListener, public PIDSource, public PIDInterface { public: enum FeedbackDevice { QuadEncoder = 0, AnalogPot = 2, AnalogEncoder = 3, EncRising = 4, EncFalling = 5, CtreMagEncoder_Relative = 6, //!< Cross The Road Electronics Magnetic Encoder in Absolute/PulseWidth Mode CtreMagEncoder_Absolute = 7, //!< Cross The Road Electronics Magnetic Encoder in Relative/Quadrature Mode PulseWidth = 8, }; /** * Depending on the sensor type, Talon can determine if sensor is plugged in ot not. */ enum FeedbackDeviceStatus { FeedbackStatusUnknown = 0, //!< Sensor status could not be determined. Not all sensors can do this. FeedbackStatusPresent = 1, //!< Sensor is present and working okay. FeedbackStatusNotPresent = 2, //!< Sensor is not present, not plugged in, not powered, etc... }; enum StatusFrameRate { StatusFrameRateGeneral = 0, StatusFrameRateFeedback = 1, StatusFrameRateQuadEncoder = 2, StatusFrameRateAnalogTempVbat = 3, StatusFrameRatePulseWidthMeas = 4, }; /** * Enumerated types for Motion Control Set Values. * When in Motion Profile control mode, these constants are paseed * into set() to manipulate the motion profile executer. * When changing modes, be sure to read the value back using getMotionProfileStatus() * to ensure changes in output take effect before performing buffering actions. * Disable will signal Talon to put motor output into neutral drive. * Talon will stop processing motion profile points. This means the buffer is * effectively disconnected from the executer, allowing the robot to gracefully * clear and push new traj points. isUnderrun will get cleared. * The active trajectory is also cleared. * Enable will signal Talon to pop a trajectory point from it's buffer and process it. * If the active trajectory is empty, Talon will shift in the next point. * If the active traj is empty, and so is the buffer, the motor drive is neutral and * isUnderrun is set. When active traj times out, and buffer has at least one point, * Talon shifts in next one, and isUnderrun is cleared. When active traj times out, * and buffer is empty, Talon keeps processing active traj and sets IsUnderrun. * Hold will signal Talon keep processing the active trajectory indefinitely. * If the active traj is cleared, Talon will neutral motor drive. Otherwise * Talon will keep processing the active traj but it will not shift in * points from the buffer. This means the buffer is effectively disconnected * from the executer, allowing the robot to gracefully clear and push * new traj points. * isUnderrun is set if active traj is empty, otherwise it is cleared. * isLast signal is also cleared. * * Typical workflow: * set(Disable), * Confirm Disable takes effect, * clear buffer and push buffer points, * set(Enable) when enough points have been pushed to ensure no underruns, * wait for MP to finish or decide abort, * If MP finished gracefully set(Hold) to hold position servo and disconnect buffer, * If MP is being aborted set(Disable) to neutral the motor and disconnect buffer, * Confirm mode takes effect, * clear buffer and push buffer points, and rinse-repeat. */ enum SetValueMotionProfile { SetValueMotionProfileDisable = 0, SetValueMotionProfileEnable = 1, SetValueMotionProfileHold = 2, }; /** * Motion Profile Trajectory Point * This is simply a data transer object. */ struct TrajectoryPoint { double position; //!< The position to servo to. double velocity; //!< The velocity to feed-forward. /** * Time in milliseconds to process this point. * Value should be between 1ms and 255ms. If value is zero * then Talon will default to 1ms. If value exceeds 255ms API will cap it. */ unsigned int timeDurMs; /** * Which slot to get PIDF gains. * PID is used for position servo. * F is used as the Kv constant for velocity feed-forward. * Typically this is hardcoded to the a particular slot, but you are free * gain schedule if need be. */ unsigned int profileSlotSelect; /** * Set to true to only perform the velocity feed-forward and not perform * position servo. This is useful when learning how the position servo * changes the motor response. The same could be accomplish by clearing the * PID gains, however this is synchronous the streaming, and doesn't require restoing * gains when finished. * * Additionaly setting this basically gives you direct control of the motor output * since motor output = targetVelocity X Kv, where Kv is our Fgain. * This means you can also scheduling straight-throttle curves without relying on * a sensor. */ bool velocityOnly; /** * Set to true to signal Talon that this is the final point, so do not * attempt to pop another trajectory point from out of the Talon buffer. * Instead continue processing this way point. Typically the velocity * member variable should be zero so that the motor doesn't spin indefinitely. */ bool isLastPoint; /** * Set to true to signal Talon to zero the selected sensor. * When generating MPs, one simple method is to make the first target position zero, * and the final target position the target distance from the current position. * Then when you fire the MP, the current position gets set to zero. * If this is the intent, you can set zeroPos on the first trajectory point. * * Otherwise you can leave this false for all points, and offset the positions * of all trajectory points so they are correct. */ bool zeroPos; }; /** * Motion Profile Status * This is simply a data transer object. */ struct MotionProfileStatus { /** * The available empty slots in the trajectory buffer. * * The robot API holds a "top buffer" of trajectory points, so your applicaion * can dump several points at once. The API will then stream them into the Talon's * low-level buffer, allowing the Talon to act on them. */ unsigned int topBufferRem; /** * The number of points in the top trajectory buffer. */ unsigned int topBufferCnt; /** * The number of points in the low level Talon buffer. */ unsigned int btmBufferCnt; /** * Set if isUnderrun ever gets set. * Only is cleared by clearMotionProfileHasUnderrun() to ensure * robot logic can react or instrument it. * @see clearMotionProfileHasUnderrun() */ bool hasUnderrun; /** * This is set if Talon needs to shift a point from its buffer into * the active trajectory point however the buffer is empty. This gets cleared * automatically when is resolved. */ bool isUnderrun; /** * True if the active trajectory point has not empty, false otherwise. * The members in activePoint are only valid if this signal is set. */ bool activePointValid; /** * The number of points in the low level Talon buffer. */ TrajectoryPoint activePoint; /** * The current output mode of the motion profile executer (disabled, enabled, or hold). * When changing the set() value in MP mode, it's important to check this signal to * confirm the change takes effect before interacting with the top buffer. */ SetValueMotionProfile outputEnable; }; explicit CANTalon(int deviceNumber); explicit CANTalon(int deviceNumber, int controlPeriodMs); DEFAULT_MOVE_CONSTRUCTOR(CANTalon); virtual ~CANTalon(); // PIDOutput interface virtual void PIDWrite(float output) override; // PIDSource interface virtual double PIDGet() override; // MotorSafety interface virtual void SetExpiration(float timeout) override; virtual float GetExpiration() const override; virtual bool IsAlive() const override; virtual void StopMotor() override; virtual void SetSafetyEnabled(bool enabled) override; virtual bool IsSafetyEnabled() const override; virtual void GetDescription(std::ostringstream& desc) const override; // CANSpeedController interface virtual float Get() const override; virtual void Set(float value, uint8_t syncGroup = 0) override; virtual void Reset() override; virtual void SetSetpoint(float value) override; virtual void Disable() override; virtual void EnableControl(); virtual void Enable() override; virtual void SetP(double p) override; virtual void SetI(double i) override; virtual void SetD(double d) override; void SetF(double f); void SetIzone(unsigned iz); virtual void SetPID(double p, double i, double d) override; virtual void SetPID(double p, double i, double d, double f); virtual double GetP() const override; virtual double GetI() const override; virtual double GetD() const override; virtual double GetF() const; virtual bool IsModePID(CANSpeedController::ControlMode mode) const override; virtual float GetBusVoltage() const override; virtual float GetOutputVoltage() const override; virtual float GetOutputCurrent() const override; virtual float GetTemperature() const override; void SetPosition(double pos); virtual double GetPosition() const override; virtual double GetSpeed() const override; virtual int GetClosedLoopError() const; virtual void SetAllowableClosedLoopErr(uint32_t allowableCloseLoopError); virtual int GetAnalogIn() const; virtual void SetAnalogPosition(int newPosition); virtual int GetAnalogInRaw() const; virtual int GetAnalogInVel() const; virtual int GetEncPosition() const; virtual void SetEncPosition(int); virtual int GetEncVel() const; int GetPinStateQuadA() const; int GetPinStateQuadB() const; int GetPinStateQuadIdx() const; int IsFwdLimitSwitchClosed() const; int IsRevLimitSwitchClosed() const; int GetNumberOfQuadIdxRises() const; void SetNumberOfQuadIdxRises(int rises); virtual int GetPulseWidthPosition() const; virtual void SetPulseWidthPosition(int newpos); virtual int GetPulseWidthVelocity() const; virtual int GetPulseWidthRiseToFallUs() const; virtual int GetPulseWidthRiseToRiseUs() const; virtual FeedbackDeviceStatus IsSensorPresent(FeedbackDevice feedbackDevice)const; virtual bool GetForwardLimitOK() const override; virtual bool GetReverseLimitOK() const override; virtual uint16_t GetFaults() const override; uint16_t GetStickyFaults() const; void ClearStickyFaults(); virtual void SetVoltageRampRate(double rampRate) override; virtual void SetVoltageCompensationRampRate(double rampRate); virtual uint32_t GetFirmwareVersion() const override; virtual void ConfigNeutralMode(NeutralMode mode) override; virtual void ConfigEncoderCodesPerRev(uint16_t codesPerRev) override; virtual void ConfigPotentiometerTurns(uint16_t turns) override; virtual void ConfigSoftPositionLimits(double forwardLimitPosition, double reverseLimitPosition) override; virtual void DisableSoftPositionLimits() override; virtual void ConfigLimitMode(LimitMode mode) override; virtual void ConfigForwardLimit(double forwardLimitPosition) override; virtual void ConfigReverseLimit(double reverseLimitPosition) override; /** * Change the fwd limit switch setting to normally open or closed. * Talon will disable momentarilly if the Talon's current setting * is dissimilar to the caller's requested setting. * * Since Talon saves setting to flash this should only affect * a given Talon initially during robot install. * * @param normallyOpen true for normally open. false for normally closed. */ void ConfigFwdLimitSwitchNormallyOpen(bool normallyOpen); /** * Change the rev limit switch setting to normally open or closed. * Talon will disable momentarilly if the Talon's current setting * is dissimilar to the caller's requested setting. * * Since Talon saves setting to flash this should only affect * a given Talon initially during robot install. * * @param normallyOpen true for normally open. false for normally closed. */ void ConfigRevLimitSwitchNormallyOpen(bool normallyOpen); virtual void ConfigMaxOutputVoltage(double voltage) override; void ConfigPeakOutputVoltage(double forwardVoltage,double reverseVoltage); void ConfigNominalOutputVoltage(double forwardVoltage,double reverseVoltage); /** * Enables Talon SRX to automatically zero the Sensor Position whenever an * edge is detected on the index signal. * @param enable boolean input, pass true to enable feature or false to disable. * @param risingEdge boolean input, pass true to clear the position on rising edge, * pass false to clear the position on falling edge. */ void EnableZeroSensorPositionOnIndex(bool enable, bool risingEdge); void ConfigSetParameter(uint32_t paramEnum, double value); bool GetParameter(uint32_t paramEnum, double & dvalue) const; virtual void ConfigFaultTime(float faultTime) override; virtual void SetControlMode(ControlMode mode); void SetFeedbackDevice(FeedbackDevice device); void SetStatusFrameRateMs(StatusFrameRate stateFrame, int periodMs); virtual ControlMode GetControlMode() const; void SetSensorDirection(bool reverseSensor); void SetClosedLoopOutputDirection(bool reverseOutput); void SetCloseLoopRampRate(double rampRate); void SelectProfileSlot(int slotIdx); int GetIzone() const; int GetIaccum() const; void ClearIaccum(); int GetBrakeEnableDuringNeutral() const; bool IsControlEnabled() const; bool IsEnabled() const override; double GetSetpoint() const override; /** * Calling application can opt to speed up the handshaking between the robot API and the Talon to increase the * download rate of the Talon's Motion Profile. Ideally the period should be no more than half the period * of a trajectory point. */ void ChangeMotionControlFramePeriod(int periodMs); /** * Clear the buffered motion profile in both Talon RAM (bottom), and in the API (top). * Be sure to check GetMotionProfileStatus() to know when the buffer is actually cleared. */ void ClearMotionProfileTrajectories(); /** * Retrieve just the buffer count for the api-level (top) buffer. * This routine performs no CAN or data structure lookups, so its fast and ideal * if caller needs to quickly poll the progress of trajectory points being emptied * into Talon's RAM. Otherwise just use GetMotionProfileStatus. * @return number of trajectory points in the top buffer. */ int GetMotionProfileTopLevelBufferCount(); /** * Push another trajectory point into the top level buffer (which is emptied into * the Talon's bottom buffer as room allows). * @param trajPt the trajectory point to insert into buffer. * @return true if trajectory point push ok. CTR_BufferFull if buffer is full * due to kMotionProfileTopBufferCapacity. */ bool PushMotionProfileTrajectory(const TrajectoryPoint & trajPt); /** * @return true if api-level (top) buffer is full. */ bool IsMotionProfileTopLevelBufferFull(); /** * This must be called periodically to funnel the trajectory points from the API's top level buffer to * the Talon's bottom level buffer. Recommendation is to call this twice as fast as the executation rate of the motion profile. * So if MP is running with 20ms trajectory points, try calling this routine every 10ms. All motion profile functions are thread-safe * through the use of a mutex, so there is no harm in having the caller utilize threading. */ void ProcessMotionProfileBuffer(); /** * Retrieve all status information. * Since this all comes from one CAN frame, its ideal to have one routine to retrieve the frame once and decode everything. * @param [out] motionProfileStatus contains all progress information on the currently running MP. */ void GetMotionProfileStatus(MotionProfileStatus & motionProfileStatus); /** * Clear the hasUnderrun flag in Talon's Motion Profile Executer when MPE is ready for another point, * but the low level buffer is empty. * * Once the Motion Profile Executer sets the hasUnderrun flag, it stays set until * Robot Application clears it with this routine, which ensures Robot Application * gets a chance to instrument or react. Caller could also check the isUnderrun flag * which automatically clears when fault condition is removed. */ void ClearMotionProfileHasUnderrun(); // LiveWindow stuff. void ValueChanged(ITable* source, llvm::StringRef key, std::shared_ptr<nt::Value> value, bool isNew) override; void UpdateTable() override; void StartLiveWindowMode() override; void StopLiveWindowMode() override; std::string GetSmartDashboardType() const override; void InitTable(std::shared_ptr<ITable> subTable) override; std::shared_ptr<ITable> GetTable() const override; // SpeedController overrides virtual void SetInverted(bool isInverted) override; virtual bool GetInverted() const override; private: // Values for various modes as is sent in the CAN packets for the Talon. enum TalonControlMode { kThrottle = 0, kFollowerMode = 5, kVoltageMode = 4, kPositionMode = 1, kSpeedMode = 2, kCurrentMode = 3, kMotionProfileMode = 6, kDisabled = 15 }; int m_deviceNumber; std::unique_ptr<CanTalonSRX> m_impl; std::unique_ptr<MotorSafetyHelper> m_safetyHelper; int m_profile = 0; // Profile from CANTalon to use. Set to zero until we can // actually test this. bool m_controlEnabled = true; ControlMode m_controlMode = kPercentVbus; TalonControlMode m_sendMode; double m_setPoint = 0; /** * Encoder CPR, counts per rotations, also called codes per revoluion. * Default value of zero means the API behaves as it did during the 2015 season, each position * unit is a single pulse and there are four pulses per count (4X). * Caller can use ConfigEncoderCodesPerRev to set the quadrature encoder CPR. */ uint32_t m_codesPerRev = 0; /** * Number of turns per rotation. For example, a 10-turn pot spins ten full rotations from * a wiper voltage of zero to 3.3 volts. Therefore knowing the * number of turns a full voltage sweep represents is necessary for calculating rotations * and velocity. * A default value of zero means the API behaves as it did during the 2015 season, there are 1024 * position units from zero to 3.3V. */ uint32_t m_numPotTurns = 0; /** * Although the Talon handles feedback selection, caching the feedback selection is helpful at the API level * for scaling into rotations and RPM. */ FeedbackDevice m_feedbackDevice = QuadEncoder; static const unsigned int kDelayForSolicitedSignalsUs = 4000; /** * @param devToLookup FeedbackDevice to lookup the scalar for. Because Talon * allows multiple sensors to be attached simultaneously, caller must * specify which sensor to lookup. * @return The number of native Talon units per rotation of the selected sensor. * Zero if the necessary sensor information is not available. * @see ConfigEncoderCodesPerRev * @see ConfigPotentiometerTurns */ double GetNativeUnitsPerRotationScalar(FeedbackDevice devToLookup)const; /** * Fixup the sendMode so Set() serializes the correct demand value. * Also fills the modeSelecet in the control frame to disabled. * @param mode Control mode to ultimately enter once user calls Set(). * @see Set() */ void ApplyControlMode(CANSpeedController::ControlMode mode); /** * @param fullRotations double precision value representing number of rotations of selected feedback sensor. * If user has never called the config routine for the selected sensor, then the caller * is likely passing rotations in engineering units already, in which case it is returned * as is. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return fullRotations in native engineering units of the Talon SRX firmware. */ int32_t ScaleRotationsToNativeUnits(FeedbackDevice devToLookup, double fullRotations) const; /** * @param rpm double precision value representing number of rotations per minute of selected feedback sensor. * If user has never called the config routine for the selected sensor, then the caller * is likely passing rotations in engineering units already, in which case it is returned * as is. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return sensor velocity in native engineering units of the Talon SRX firmware. */ int32_t ScaleVelocityToNativeUnits(FeedbackDevice devToLookup, double rpm) const; /** * @param nativePos integral position of the feedback sensor in native Talon SRX units. * If user has never called the config routine for the selected sensor, then the return * will be in TALON SRX units as well to match the behavior in the 2015 season. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return double precision number of rotations, unless config was never performed. */ double ScaleNativeUnitsToRotations(FeedbackDevice devToLookup, int32_t nativePos) const; /** * @param nativeVel integral velocity of the feedback sensor in native Talon SRX units. * If user has never called the config routine for the selected sensor, then the return * will be in TALON SRX units as well to match the behavior in the 2015 season. * @see ConfigPotentiometerTurns * @see ConfigEncoderCodesPerRev * @return double precision of sensor velocity in RPM, unless config was never performed. */ double ScaleNativeUnitsToRpm(FeedbackDevice devToLookup, int32_t nativeVel) const; // LiveWindow stuff. std::shared_ptr<ITable> m_table; bool m_isInverted; HasBeenMoved m_hasBeenMoved; };
44.814745
136
0.708356
[ "object" ]
b779f6adda0270e34a31a9c1f52ccf6bed314064
25,891
h
C
branches/g3d-8.0-64ffmpeg-win/GLG3D.lib/include/GLG3D/GuiTheme.h
brown-ccv/VRG3D
0854348453ac150b27a8ae89024ef57360f15d45
[ "BSD-3-Clause" ]
null
null
null
branches/g3d-8.0-64ffmpeg-win/GLG3D.lib/include/GLG3D/GuiTheme.h
brown-ccv/VRG3D
0854348453ac150b27a8ae89024ef57360f15d45
[ "BSD-3-Clause" ]
null
null
null
branches/g3d-8.0-64ffmpeg-win/GLG3D.lib/include/GLG3D/GuiTheme.h
brown-ccv/VRG3D
0854348453ac150b27a8ae89024ef57360f15d45
[ "BSD-3-Clause" ]
null
null
null
/** \file GuiTheme.h \maintainer Morgan McGuire, http://graphics.cs.williams.edu Copyright 2000-2010, Morgan McGuire All rights reserved */ #ifndef G3D_GuiTheme_H #define G3D_GuiTheme_H #include "G3D/platform.h" #include "G3D/Rect2D.h" #include "GLG3D/Texture.h" #include "GLG3D/GFont.h" #include "G3D/Table.h" #include "GLG3D/GuiText.h" namespace G3D { namespace _internal { class Morph { public: bool active; Rect2D start; RealTime startTime; RealTime duration; Rect2D end; Morph(); void morphTo(const Rect2D& s, const Rect2D& e); /** Morph the object using setRect */ template<class T> void update(T* object) { RealTime now = System::time(); float alpha = (now - startTime) / duration; if (alpha > 1.0f) { object->setRect(end); active = false; // The setRect will terminate the morph } else { object->setRect(start.lerp(end, alpha)); // setRect turns off morphing, so we have to turn it back // on explicitly active = true; } } }; } typedef ReferenceCountedPointer<class GuiTheme> GuiThemeRef; /** Renders UI elements. Loads and renders G3D GUI .gtm files, which can be used with G3D::Gui. .gtm files can be found in the data module data/gui directory. Can also be used to explicitly render a UI without actual controls behind it, for example: <pre> theme->beginRendering(rd); theme->renderWindow(Rect2D::xywh(80, 70, 550, 250), false, false, false, false, "Window", GuiTheme::NORMAL_WINDOW_STYLE); theme->renderWindow(Rect2D::xywh(500, 120, 50, 150), true, true, true, "Tools", GuiTheme::TOOL_WINDOW_STYLE); theme->renderCheckBox(Rect2D::xywh(100, 100, 20, 20), true, true, true, "Check box"); theme->renderRadioButton(Rect2D::xywh(100, 120, 20, 20), true, false, false, "Radio button"); theme->renderButton(Rect2D::xywh(100, 160, 80, 27), true, true, true, "Button"); theme->setFont(timesFont, 12, Color3::black(), Color4::clear()); theme->renderButton(Rect2D::xywh(200, 160, 80, 27), true, true, true, "New Font"); theme->setFont(arialFont, 10, Color3::black(), Color4::clear()); theme->renderHorizontalSlider(Rect2D::xywh(100, 200, 150, 27), 0.5f, true, false, "Slider"); int s = 30; theme->renderButton(Rect2D::xywh(100 + s * 0, 230, 30, 30), true, false, false, GuiText("7", iconFont)); theme->renderButton(Rect2D::xywh(100 + s * 1, 230, 30, 30), true, false, false, GuiText("4", iconFont)); theme->renderButton(Rect2D::xywh(100 + s * 2, 230, 30, 30), true, false, false, GuiText("=", iconFont)); theme->renderButton(Rect2D::xywh(100 + s * 3, 230, 30, 30), true, false, true, GuiText(";", iconFont)); theme->renderButton(Rect2D::xywh(100 + s * 4, 230, 30, 30), true, false, false, GuiText("<", iconFont)); theme->renderButton(Rect2D::xywh(100 + s * 5, 230, 30, 30), true, false, false, GuiText("8", iconFont)); theme->setFont(arialFont, 10, Color3::black(), Color4::clear()); theme->endRendering(); </pre> @sa G3D::GuiWindow */ class GuiTheme : public ReferenceCountedObject { public: typedef ReferenceCountedPointer<class GuiTheme> Ref; /** Scale for sliders */ enum SliderScale {NO_SLIDER, LINEAR_SLIDER, LOG_SLIDER}; /** Controls the appearance of the window's borders and background. NORMAL - regular border and title TOOL - small title, thin border DIALOG - thicker border MENU - Menu; no title-bar NO - do not render any background at all */ enum WindowStyle { NORMAL_WINDOW_STYLE, TOOL_WINDOW_STYLE, DIALOG_WINDOW_STYLE, DRAWER_WINDOW_STYLE, MENU_WINDOW_STYLE, NO_WINDOW_STYLE, WINDOW_STYLE_COUNT }; /** NO_PANE_STYLE has no visible borders or back */ enum PaneStyle { SIMPLE_PANE_STYLE, ORNATE_PANE_STYLE, NO_PANE_STYLE, PANE_STYLE_COUNT }; /** Controls the appearance of the button. Tool buttons are square and less 3D. They are also able to shrink to smaller sizes. The NO_STYLE creates buttons with a caption but no visible borders. */ enum ButtonStyle { NORMAL_BUTTON_STYLE, TOOL_BUTTON_STYLE, NO_BUTTON_STYLE, BUTTON_STYLE_COUNT }; /** NORMAL_CHECK_BOX_STYLE is the normal checkbox appearance. BUTTON_CHECK_BOX_STYLE makes checkbox that looks like a button, TOOL_CHECK_BOX_STYLE appears as a tool-bar button. */ enum CheckBoxStyle { NORMAL_CHECK_BOX_STYLE, BUTTON_CHECK_BOX_STYLE, TOOL_CHECK_BOX_STYLE, CHECK_BOX_STYLE_COUNT }; enum RadioButtonStyle { NORMAL_RADIO_BUTTON_STYLE, BUTTON_RADIO_BUTTON_STYLE = 1, TOOL_RADIO_BUTTON_STYLE, RADIO_BUTTON_STYLE_COUNT }; public: /** Default style information for captions. */ class TextStyle { public: GFont::Ref font; Color4 color; Color4 outlineColor; float size; TextStyle() : color(-1,-1,-1,-1), outlineColor(-1,-1,-1,-1), size(-1) {} void load(const Any& any); }; private: friend class GuiThemeEditor; /** Used for delayed text rendering. */ class Text { public: Vector2 position; std::string text; GFont::XAlign xAlign; GFont::YAlign yAlign; float size; Color4 color; Color4 outlineColor; }; /** Delayed text, organized by the associated font.*/ Table<GFont::Ref, Array<Text> > m_delayedText; /** Number of values in delayedText's arrays. Used to detect when we need to enter font rendering mode. */ int m_delayedTextCount; /** Clears the delayedText array. */ void drawDelayedText() const; /** Postpones rendering the specified text until later. Switching between the GUI texture and the font texture is relatively slow, so delaying text rendering until a few controls have been put down increases performance. Note that delayed text must be drawn before the clipping region is changed or another window is rendered. */ void addDelayedText(GFont::Ref font, const std::string& text, const Vector2& position, float size, const Color4& color, const Color4& outlineColor, GFont::XAlign xalign, GFont::YAlign yalign = GFont::YALIGN_CENTER) const; void addDelayedText(const GuiText& text, const TextStyle& defaults, const Vector2& position, GFont::XAlign xalign, GFont::YAlign yalign = GFont::YALIGN_CENTER) const; enum {TEXTURE_UNIT = 0}; enum StretchMode {TILE, STRETCH}; // All internal coordinates are stored in texture coordinates /** */ class Fill { public: StretchMode horizontalMode; StretchMode verticalMode; /** Source rectangle. This does not have to correspond to the dimensions of the destination rectangle at all. When rendered, mode will be used to fill the destination rectangle up to the correct dimensions if source is too small. If too source is too large it is cropped on the bottom and right. */ Rect2D source; void load(const Any& any); void render(class RenderDevice* rd, const Rect2D& bounds, const Vector2& texOffset) const; }; /** Horizontal stretch--two caps and a center fill */ class StretchRectH { public: Rect2D left; Fill center; Rect2D right; void load(const Any& any); /** Bounds height must match left.height and right.height */ void render(class RenderDevice* rd, const Rect2D& bounds, const Vector2& texOffset) const; float height() const { return left.height(); } }; /** Stretchable in horizontal and vertical direction. */ class StretchRectHV { public: StretchRectH top; Fill centerLeft; Fill centerCenter; Fill centerRight; StretchRectH bottom; void load(const Any& any); void render(class RenderDevice* rd, const Rect2D& bounds, const Vector2& texOffset) const; }; class Pad { public: Vector2 topLeft; Vector2 bottomRight; void load(const Any& any); /** Net width and height of the padding */ inline Vector2 wh() const { return topLeft + bottomRight; } }; class DropDownList { public: StretchRectH base; /** Offsets from base of area for text display */ Pad textPad; class Pair { public: /** For use during selection */ Vector2 down; Vector2 up; void load(const Any& any); }; class Focus { public: Pair focused; Vector2 defocused; void load(const Any& any); }; Focus enabled; Vector2 disabled; TextStyle textStyle; TextStyle disabledTextStyle; void load(const Any& any); void render(RenderDevice* rd, const Rect2D& bounds, bool enabled, bool focused, bool pushed) const; }; class Button { public: /** General texture coordinates for any mode of the button */ StretchRectHV base; /** Displacement from bounds center. */ Vector2 textOffset; /** Defaults */ TextStyle textStyle; TextStyle disabledTextStyle; class Pair { public: /** TexOffset from base of this image */ Vector2 down; /** TexOffset from base of this image */ Vector2 up; void load(const Any& any); }; class Focus { public: Pair focused; Pair defocused; void load(const Any& any); }; Focus enabled; Pair disabled; void load(const Any& any); void render(RenderDevice* rd, const Rect2D& bounds, bool enabled, bool focused, bool pushed) const; }; class TextBox { public: /** General texture coordinates for any mode */ StretchRectHV base; Pad textPad; /** Defaults */ TextStyle textStyle; TextStyle disabledTextStyle; /** For the user value*/ TextStyle contentStyle; class Focus { public: Vector2 focused; Vector2 defocused; void load(const Any& any); }; Focus enabled; Vector2 disabled; void load(const Any& any); void render(RenderDevice* rd, const Rect2D& bounds, bool enabled, bool focused) const; }; class Canvas { public: /** General texture coordinates for any mode */ StretchRectHV base; Pad pad; /** Defaults */ TextStyle textStyle; TextStyle disabledTextStyle; TextBox::Focus enabled; Vector2 disabled; void load(const Any& any); void render(RenderDevice* rd, const Rect2D& bounds, bool enabled, bool focused) const; }; /** Used for radio and check boxes */ class Checkable { public: class Pair { public: Rect2D checked; Rect2D unchecked; void load(const Any& any); }; class Focus { public: Pair focused; Pair defocused; void load(const Any& any); }; Focus enabled; Pair disabled; Vector2 textOffset; /** Defaults */ TextStyle textStyle; TextStyle disabledTextStyle; void load(const Any& any); void render(RenderDevice* rd, const Rect2D& bounds, bool enabled, bool focused, bool checked) const; float width() const { return disabled.checked.width(); } float height() const { return disabled.checked.height(); } }; /** Window close, minimize, maximize */ class WindowButton { public: Rect2D base; Vector2 focusedUp; Vector2 focusedDown; Vector2 defocused; Vector2 windowDefocused; void load(const Any& any); }; class Window { public: StretchRectHV base; /** Distance from edge to border */ Pad borderPad; /** Thickness of border on each side (not counting rounded corners) */ Pad borderThickness; /** Distance from border exterior to client area */ Pad netClientPad; Vector2 focused; Vector2 defocused; /** Defaults */ TextStyle textStyle; TextStyle defocusedTextStyle; void load(const Any& any); /** Pass the bounds outside the border; the borderPad will automatically be added. */ void render(RenderDevice* rd, const Rect2D& bounds, bool focused) const; }; class HSlider { public: class Bar { public: StretchRectH base; Vector2 enabled; Vector2 disabled; void load(const Any& any); }; class Thumb { public: Rect2D base; class Focus { public: Vector2 focused; Vector2 defocused; void load(const Any& any); }; Focus enabled; Vector2 disabled; void load(const Any& any); }; Bar bar; Thumb thumb; /** Defaults */ TextStyle textStyle; TextStyle disabledTextStyle; void load(const Any& any); /** Renders along the center of the vertical bounds and stretches to fill horizontally.*/ void render(RenderDevice* rd, const Rect2D& bounds, float thumbPos, bool enabled, bool focused) const; /** Given the bounds on the graphical part of the slider, returns the bounds on the track.*/ Rect2D trackBounds(const Rect2D& sliderBounds) const; Rect2D thumbBounds(const Rect2D& sliderBounds, float pos) const; }; class Pane { public: /** Defaults */ TextStyle textStyle; TextStyle disabledTextStyle; StretchRectHV frame; Pad clientPad; void load(const Any& any); }; Checkable m_checkBox; Checkable m_radioButton; Button m_button[BUTTON_STYLE_COUNT]; Window m_window[WINDOW_STYLE_COUNT]; HSlider m_hSlider; Pane m_pane[PANE_STYLE_COUNT]; WindowButton m_closeButton; TextBox m_textBox; Canvas m_canvas; DropDownList m_dropDownList; /** If true, the close button is on the left. If false, it is on the right */ bool m_osxWindowButtons; StretchRectHV m_selection; /** Defaults */ TextStyle m_textStyle; TextStyle m_disabledTextStyle; Texture::Ref m_texture; /** The transformation matrix used to scale texture coordinates to the resolution of the texture. OpenGL-style matrix */ float m_guiTextureMatrix[16]; /** True between beginRendering and endRendering */ bool m_inRendering; RenderDevice* m_rd; /** Used by push/popClientRect */ Array<Rect2D> m_scissorStack; /** Used by push/popClientRect */ Array<CoordinateFrame> m_coordinateFrameStack; static void drawRect(const Rect2D& vertex, const Rect2D& texCoord, RenderDevice* rd); void drawCheckable(const Checkable& control, const Rect2D& bounds, bool enabled, bool focused, bool selected, const GuiText& text) const; void drawWindow(const Window& window, const Rect2D& bounds, bool focused, bool close, bool closeDown, bool closeIsFocused, const GuiText& text) const; static StretchMode stringToStretchMode(const std::string& name); GuiTheme(const std::string& filename, const GFont::Ref& fallbackFont, float fallbackSize, const Color4& fallbackColor, const Color4& fallbackOutlineColor); /** Unpacks a .gtm file and loads the theme. Usually called from constructor. */ void loadTheme(BinaryInput& b); /** Loads the theme specification. */ void loadCoords(const Any& any); /** Call before GFont::send2DQuads */ void beginText() const; /** Call after GFont::send2DQuads */ void endText() const; Rect2D horizontalSliderToSliderBounds(const Rect2D& bounds, float captionWidth) const; Rect2D closeButtonBounds(const Window& window, const Rect2D& bounds) const; /** Returns the amount of space to reserve at the top of a pane with this caption */ float paneTopPadding(const GuiText& caption, PaneStyle paneStyle) const; public: /** Return the default text style */ const TextStyle& defaultStyle() const { return m_textStyle; } /** May return a cached copy. @param filename Name of the .gtm file. */ static GuiTheme::Ref fromFile( const std::string& filename, GFont::Ref fallbackFont = NULL, float fallbackSize = 11, const Color4& fallbackColor = Color3::black(), const Color4& fallbackOutlineColor = Color4::clear()); /** Call before all other render methods. */ void beginRendering(class RenderDevice* rd); static WeakReferenceCountedPointer<GuiTheme> lastThemeLoaded; /** Offsets all subsequent rendering by r.x0y0() and sets the clipping region to r. Call only between beginRendering and endRendering. */ void pushClientRect(const Rect2D& r); void popClientRect(); /** Call after all other render methods. */ void endRendering(); /** Invoke from a custom GuiControl::render to make arbitrary RenderDevice calls. Be sure to call resumeRendering() when done. Invokes RenderDevice::pushState automatically. */ void pauseRendering(); void resumeRendering(); /** Only call between beginRendering and endRendering */ void renderCheckBox(const Rect2D& bounds, bool enabled, bool focused, bool checked, const GuiText& text) const; /** Render a single-line text box. Only call between beginRendering and endRendering. Automatically shifts text so that a cursor at character index given by cursorPosition is visible on screen. */ void renderTextBox( const Rect2D& bounds, bool enabled, bool focused, const GuiText& caption, float captionWidth, const GuiText& text, const GuiText& cursor, int cursorPosition) const; /** Render a drawing area with borders that look like a text box. The caption for a canvas is rendered above it and the canvas has the full width of its bounds. */ void renderCanvas( const Rect2D& bounds, bool enabled, bool focused, const GuiText& caption, float captionHeight) const; /** Render the selection region for a menu or list. */ void renderSelection(const Rect2D& bounds) const; void renderDropDownList ( const Rect2D& bounds, bool enabled, bool focused, bool menuOpen, const GuiText& contentText, const GuiText& text, float captionWidth) const; /** Only call between beginRendering and endRendering */ void renderRadioButton(const Rect2D& bounds, bool enabled, bool focused, bool checked, const GuiText& text) const; /** Only call between beginRendering and endRendering */ void renderButton(const Rect2D& bounds, bool enabled, bool focused, bool pushed, const GuiText& text, ButtonStyle buttonStyle) const; /** Only call between beginRendering and endRendering. @param bounds Corresponds to the footprint of the window; dropshadows and glows may still render outside this area.*/ void renderWindow(const Rect2D& bounds, bool focused, bool hasCloseButton, bool closeButtonIsDown, bool closeIsFocused, const GuiText& text, WindowStyle frameStyle) const; /** Given the bounds of a full dropDownList and caption, returns the bounds around just the control itself. */ Rect2D dropDownListToClickBounds(const Rect2D& bounds, float captionWidth) const; Rect2D textBoxToClickBounds(const Rect2D& bounds, float captionWidth) const; Rect2D canvasToClickBounds(const Rect2D& bounds, float captionHeight) const; /** Given the full bounds around a canvas, returns the internal region for rendering in. */ Rect2D canvasToClientBounds(const Rect2D& bounds, float captionHeight) const; /** Given the bounds on a window's borders, returns the bounds of the area inside the window where controls will appear.*/ Rect2D windowToClientBounds(const Rect2D& bounds, WindowStyle frameStyle) const; /** Given the area that controls should appear in for a window, returns the bounds that should be used to draw the window. Note that the window's shadow or other effects may exceed these bounds when rendering.*/ Rect2D clientToWindowBounds(const Rect2D& bounds, WindowStyle frameStyle) const; Rect2D windowToTitleBounds(const Rect2D& bounds, WindowStyle frameStyle) const; Rect2D windowToCloseButtonBounds(const Rect2D& bounds, WindowStyle frameStyle) const; /** Returns the position of the thumb button, which is needed for processing UI events for the slider. */ Rect2D horizontalSliderToThumbBounds(const Rect2D& bounds, float pos, float captionWidth) const; Rect2D horizontalSliderToTrackBounds(const Rect2D& bounds, float captionWidth) const; Rect2D paneToClientBounds(const Rect2D& bounds, const GuiText& caption, PaneStyle paneStyle) const; Rect2D clientToPaneBounds(const Rect2D& bounds, const GuiText& caption, PaneStyle paneStyle) const; /** Computes the rendered size of this text (max of enabled and disabled versions) */ Vector2 bounds(const GuiText& text) const; /** Only call between beginRendering and endRendering. Label is on the right, slider is aligned with the left edge @param pos 0 = left edge, 1 = right edge*/ void renderHorizontalSlider(const Rect2D& bounds, float pos, bool enabled, bool focused, const GuiText& text, float captionWidth) const; /** Only call between beginRendering and endRendering */ void renderLabel(const Rect2D& bounds, const GuiText& text, GFont::XAlign xalign, GFont::YAlign yalign, bool enabled) const; void renderPane(const Rect2D& fullBounds, const GuiText& caption, PaneStyle paneStyle) const; /** Create a .gtm file from source files. Used as a preprocess when creating new themes. You probably don't need to call this because most people will want to use pre-existing skins (making a theme is a time-consuming artistic process!) @param sourceDir Must end in a slash. @param whiteName Image of controls on a white background, must be in sourceDir @param blackName Image of controls on a black background, must be in sourceDir @param coordsFile Text file describing the location of controls @param destFile Output .gtm file, not relative to sourceDir */ static void makeThemeFromSourceFiles( const std::string& sourceDir, const std::string& whiteName, const std::string& blackName, const std::string& coordsFile, const std::string& destFile); /** Returns the size a button would have to be to enclose this caption.*/ Vector2 minButtonSize(const GuiText& text, ButtonStyle buttonStyle) const; }; // GuiTheme } // namespace G3D #endif // G3D_GuiTheme_H
32.814956
128
0.588776
[ "render", "object", "3d" ]