diff
stringlengths
41
2.03M
msg
stringlengths
1
1.5k
repo
stringlengths
5
40
sha
stringlengths
40
40
time
stringlengths
20
20
mmm a / Telegram / SourceFiles / mtproto / session_private . cpp <nl> ppp b / Telegram / SourceFiles / mtproto / session_private . cpp <nl> constexpr auto kTestModeDcIdShift = 10000 ; <nl> constexpr auto kCheckSentRequestsEach = 1 * crl : : time ( 1000 ) ; <nl> constexpr auto kKeyOldEnoughForDestroy = 60 * crl : : time ( 1000 ) ; <nl> constexpr auto kSentContainerLives = 600 * crl : : time ( 1000 ) ; <nl> + constexpr auto kFastRequestDuration = crl : : time ( 500 ) ; <nl> <nl> / / If we can ' t connect for this time we will ask _instance to update config . <nl> constexpr auto kRequestConfigTimeout = 8 * crl : : time ( 1000 ) ; <nl> constexpr auto kSendStateRequestWaiting = crl : : time ( 1000 ) ; <nl> / / How much time to wait for some more requests , when sending msg acks . <nl> constexpr auto kAckSendWaiting = 10 * crl : : time ( 1000 ) ; <nl> <nl> + auto SyncTimeRequestDuration = kFastRequestDuration ; <nl> + <nl> using namespace details ; <nl> <nl> [ [ nodiscard ] ] QString LogIdsVector ( const QVector < MTPlong > & ids ) { <nl> SessionPrivate : : HandleResult SessionPrivate : : handleOneReceived ( <nl> return badTime ? HandleResult : : Ignored : HandleResult : : Success ; <nl> } <nl> <nl> - if ( badTime & & ! requestsFixTimeSalt ( ids , serverTime , serverSalt ) ) { <nl> - return HandleResult : : Ignored ; <nl> + if ( badTime ) { <nl> + if ( ! requestsFixTimeSalt ( ids , serverTime , serverSalt ) ) { <nl> + return HandleResult : : Ignored ; <nl> + } <nl> + } else { <nl> + correctUnixtimeByFastRequest ( ids , serverTime ) ; <nl> } <nl> requestsAcked ( ids ) ; <nl> } return HandleResult : : Success ; <nl> SessionPrivate : : HandleResult SessionPrivate : : handleOneReceived ( <nl> if ( serverSalt ) { <nl> _sessionSalt = serverSalt ; <nl> } <nl> - base : : unixtime : : update ( serverTime , true ) ; <nl> + <nl> + correctUnixtimeWithBadLocal ( serverTime ) ; <nl> <nl> DEBUG_LOG ( ( " Message Info : unixtime updated , now % 1 , resending in container . . . " ) . arg ( serverTime ) ) ; <nl> <nl> SessionPrivate : : HandleResult SessionPrivate : : handleOneReceived ( <nl> if ( serverSalt ) { <nl> _sessionSalt = serverSalt ; <nl> } <nl> - base : : unixtime : : update ( serverTime , true ) ; <nl> + correctUnixtimeWithBadLocal ( serverTime ) ; <nl> badTime = false ; <nl> } <nl> LOG ( ( " Message Info : bad message notification received , msgId % 1 , error_code % 2 " ) . arg ( data . vbad_msg_id ( ) . v ) . arg ( errorCode ) ) ; <nl> SessionPrivate : : HandleResult SessionPrivate : : handleOneReceived ( <nl> } <nl> <nl> _sessionSalt = data . vnew_server_salt ( ) . v ; <nl> - base : : unixtime : : update ( serverTime ) ; <nl> + correctUnixtimeWithBadLocal ( serverTime ) ; <nl> <nl> if ( setState ( ConnectedState , ConnectingState ) ) { <nl> resendAll ( ) ; <nl> SessionPrivate : : HandleResult SessionPrivate : : handleOneReceived ( <nl> if ( serverSalt ) { <nl> _sessionSalt = serverSalt ; / / requestsFixTimeSalt with no lookup <nl> } <nl> - base : : unixtime : : update ( serverTime , true ) ; <nl> + correctUnixtimeWithBadLocal ( serverTime ) ; <nl> <nl> DEBUG_LOG ( ( " Message Info : unixtime updated from mtpc_msgs_state_info , now % 1 " ) . arg ( serverTime ) ) ; <nl> <nl> mtpBuffer SessionPrivate : : ungzip ( const mtpPrime * from , const mtpPrime * end ) cons <nl> } <nl> <nl> bool SessionPrivate : : requestsFixTimeSalt ( const QVector < MTPlong > & ids , int32 serverTime , uint64 serverSalt ) { <nl> - uint32 idsCount = ids . size ( ) ; <nl> - <nl> - for ( uint32 i = 0 ; i < idsCount ; + + i ) { <nl> - if ( wasSent ( ids [ i ] . v ) ) { / / found such msg_id in recent acked requests or in recent sent requests <nl> + for ( const auto & id : ids ) { <nl> + if ( wasSent ( id . v ) ) { <nl> + / / Found such msg_id in recent acked or in recent sent requests . <nl> if ( serverSalt ) { <nl> _sessionSalt = serverSalt ; <nl> } <nl> - base : : unixtime : : update ( serverTime , true ) ; <nl> + correctUnixtimeWithBadLocal ( serverTime ) ; <nl> return true ; <nl> } <nl> } <nl> return false ; <nl> } <nl> <nl> + void SessionPrivate : : correctUnixtimeByFastRequest ( <nl> + const QVector < MTPlong > & ids , <nl> + TimeId serverTime ) { <nl> + const auto now = crl : : now ( ) ; <nl> + <nl> + QReadLocker locker ( _sessionData - > haveSentMutex ( ) ) ; <nl> + const auto & haveSent = _sessionData - > haveSentMap ( ) ; <nl> + for ( const auto & id : ids ) { <nl> + const auto i = haveSent . find ( id . v ) ; <nl> + if ( i = = haveSent . end ( ) ) { <nl> + continue ; <nl> + } <nl> + const auto duration = ( now - i - > second - > lastSentTime ) ; <nl> + if ( duration < 0 | | duration > SyncTimeRequestDuration ) { <nl> + continue ; <nl> + } <nl> + locker . unlock ( ) ; <nl> + <nl> + SyncTimeRequestDuration = duration ; <nl> + base : : unixtime : : update ( serverTime , true ) ; <nl> + return ; <nl> + } <nl> + } <nl> + <nl> + void SessionPrivate : : correctUnixtimeWithBadLocal ( TimeId serverTime ) { <nl> + SyncTimeRequestDuration = kFastRequestDuration ; <nl> + base : : unixtime : : update ( serverTime , true ) ; <nl> + } <nl> + <nl> void SessionPrivate : : requestsAcked ( const QVector < MTPlong > & ids , bool byResponse ) { <nl> uint32 idsCount = ids . size ( ) ; <nl> <nl> mmm a / Telegram / SourceFiles / mtproto / session_private . h <nl> ppp b / Telegram / SourceFiles / mtproto / session_private . h <nl> class SessionPrivate final : public QObject { <nl> / / if badTime received - search for ids in sessionData - > haveSent and sessionData - > wereAcked and sync time / salt , return true if found <nl> bool requestsFixTimeSalt ( const QVector < MTPlong > & ids , int32 serverTime , uint64 serverSalt ) ; <nl> <nl> + / / if we had a confirmed fast request use its unixtime as a correct one . <nl> + void correctUnixtimeByFastRequest ( <nl> + const QVector < MTPlong > & ids , <nl> + TimeId serverTime ) ; <nl> + void correctUnixtimeWithBadLocal ( TimeId serverTime ) ; <nl> + <nl> / / remove msgs with such ids from sessionData - > haveSent , add to sessionData - > wereAcked <nl> void requestsAcked ( const QVector < MTPlong > & ids , bool byResponse = false ) ; <nl> <nl> mmm a / Telegram / lib_base <nl> ppp b / Telegram / lib_base <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit 9e01ede6661e2a74697283c7836d4fae433f50ce <nl> + Subproject commit b376282b656b13c54cd892e3c2742bb26acf42fe <nl>
Use precise sync of the server unixtime .
telegramdesktop/tdesktop
7883f97c9480f1d5ce2a1a6c01b83a4f605fc3cb
2020-05-12T13:33:06Z
mmm a / dbms / src / Access / SettingsConstraints . cpp <nl> ppp b / dbms / src / Access / SettingsConstraints . cpp <nl> const SettingsConstraints : : Constraint * SettingsConstraints : : tryGetConstraint ( si <nl> <nl> void SettingsConstraints : : setProfile ( const String & profile_name , const Poco : : Util : : AbstractConfiguration & config ) <nl> { <nl> - String parent_profile = " profiles . " + profile_name + " . profile " ; <nl> - if ( config . has ( parent_profile ) ) <nl> - setProfile ( parent_profile , config ) ; / / Inheritance of one profile from another . <nl> + String elem = " profiles . " + profile_name ; <nl> + <nl> + Poco : : Util : : AbstractConfiguration : : Keys config_keys ; <nl> + config . keys ( elem , config_keys ) ; <nl> + <nl> + for ( const std : : string & key : config_keys ) <nl> + { <nl> + if ( key = = " profile " | | 0 = = key . compare ( 0 , strlen ( " profile [ " ) , " profile [ " ) ) / / / Inheritance of profiles from the current one . <nl> + setProfile ( config . getString ( elem + " . " + key ) , config ) ; <nl> + else <nl> + continue ; <nl> + } <nl> <nl> String path_to_constraints = " profiles . " + profile_name + " . constraints " ; <nl> if ( config . has ( path_to_constraints ) ) <nl> mmm a / dbms / src / Core / Settings . cpp <nl> ppp b / dbms / src / Core / Settings . cpp <nl> void Settings : : setProfile ( const String & profile_name , const Poco : : Util : : Abstrac <nl> { <nl> if ( key = = " constraints " ) <nl> continue ; <nl> - if ( key = = " profile " ) / / / Inheritance of one profile from another . <nl> + if ( key = = " profile " | | 0 = = key . compare ( 0 , strlen ( " profile [ " ) , " profile [ " ) ) / / / Inheritance of profiles from the current one . <nl> setProfile ( config . getString ( elem + " . " + key ) , config ) ; <nl> else <nl> set ( key , config . getString ( elem + " . " + key ) ) ; <nl> mmm a / dbms / src / Interpreters / DDLWorker . cpp <nl> ppp b / dbms / src / Interpreters / DDLWorker . cpp <nl> void DDLWorker : : runMainThread ( ) <nl> { <nl> try <nl> { <nl> - try <nl> - { <nl> - auto zookeeper = getAndSetZooKeeper ( ) ; <nl> - zookeeper - > createAncestors ( queue_dir + " / " ) ; <nl> - initialized = true ; <nl> - } <nl> - catch ( const Coordination : : Exception & e ) <nl> - { <nl> - if ( ! Coordination : : isHardwareError ( e . code ) ) <nl> - throw ; / / / A logical error . <nl> + auto zookeeper = getAndSetZooKeeper ( ) ; <nl> + zookeeper - > createAncestors ( queue_dir + " / " ) ; <nl> + initialized = true ; <nl> + } <nl> + catch ( const Coordination : : Exception & e ) <nl> + { <nl> + if ( ! Coordination : : isHardwareError ( e . code ) ) <nl> + throw ; / / / A logical error . <nl> <nl> - tryLogCurrentException ( __PRETTY_FUNCTION__ ) ; <nl> + tryLogCurrentException ( __PRETTY_FUNCTION__ ) ; <nl> <nl> - / / / Avoid busy loop when ZooKeeper is not available . <nl> - sleepForSeconds ( 1 ) ; <nl> - } <nl> + / / / Avoid busy loop when ZooKeeper is not available . <nl> + sleepForSeconds ( 1 ) ; <nl> } <nl> catch ( . . . ) <nl> { <nl> new file mode 100644 <nl> index 00000000000 . . e69de29bb2d <nl> new file mode 100644 <nl> index 00000000000 . . 4fbb7dcf3ff <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_inherit_multiple_profiles / configs / combined_profile . xml <nl> <nl> + < yandex > <nl> + < profiles > <nl> + < profile_1 > <nl> + < max_parallel_replicas > 2 < / max_parallel_replicas > <nl> + < ! - - max_query_size is inherited one by one and final should be 400000000 - - > <nl> + < max_query_size > 200000000 < / max_query_size > <nl> + < constraints > <nl> + < max_memory_usage > <nl> + < min > 100000000 < / min > <nl> + < / max_memory_usage > <nl> + < max_parallel_replicas > <nl> + < readonly / > <nl> + < / max_parallel_replicas > <nl> + < / constraints > <nl> + < / profile_1 > <nl> + < profile_2 > <nl> + < max_network_bytes > 1234567890 < / max_network_bytes > <nl> + < max_query_size > 300000000 < / max_query_size > <nl> + < constraints > <nl> + < max_memory_usage > <nl> + < min > 200000000 < / min > <nl> + < / max_memory_usage > <nl> + < max_network_bytes > <nl> + < min > 1234567889 < / min > <nl> + < max > 1234567891 < / max > <nl> + < / max_network_bytes > <nl> + < / constraints > <nl> + < / profile_2 > <nl> + < profile_3 > <nl> + < max_insert_block_size > 654321 < / max_insert_block_size > <nl> + < max_query_size > 400000000 < / max_query_size > <nl> + < constraints > <nl> + < max_memory_usage > <nl> + < min > 300000000 < / min > <nl> + < / max_memory_usage > <nl> + < max_insert_block_size > <nl> + < min > 654320 < / min > <nl> + < max > 654322 < / max > <nl> + < / max_insert_block_size > <nl> + < / constraints > <nl> + < / profile_3 > <nl> + < combined_profile > <nl> + < profile > profile_1 < / profile > <nl> + < profile > profile_2 < / profile > <nl> + < profile > profile_3 < / profile > <nl> + < readonly > 2 < / readonly > <nl> + < / combined_profile > <nl> + < / profiles > <nl> + < users > <nl> + < test_combined_profile > <nl> + < password > < / password > <nl> + < networks > <nl> + < ip > : : / 0 < / ip > <nl> + < / networks > <nl> + < quota > default < / quota > <nl> + < profile > combined_profile < / profile > <nl> + < / test_combined_profile > <nl> + < / users > <nl> + < / yandex > <nl> new file mode 100644 <nl> index 00000000000 . . 1540196f9b6 <nl> mmm / dev / null <nl> ppp b / dbms / tests / integration / test_inherit_multiple_profiles / test . py <nl> <nl> + import pytest <nl> + <nl> + from helpers . client import QueryRuntimeException <nl> + from helpers . cluster import ClickHouseCluster <nl> + from helpers . test_tools import TSV <nl> + <nl> + <nl> + cluster = ClickHouseCluster ( __file__ ) <nl> + instance = cluster . add_instance ( ' instance ' , <nl> + user_configs = [ ' configs / combined_profile . xml ' ] ) <nl> + q = instance . query <nl> + <nl> + <nl> + @ pytest . fixture ( scope = " module " ) <nl> + def started_cluster ( ) : <nl> + try : <nl> + cluster . start ( ) <nl> + <nl> + yield cluster <nl> + <nl> + finally : <nl> + cluster . shutdown ( ) <nl> + <nl> + <nl> + def test_combined_profile ( started_cluster ) : <nl> + settings = q ( ' ' ' <nl> + SELECT name , value FROM system . settings <nl> + WHERE name IN <nl> + ( ' max_insert_block_size ' , ' max_network_bytes ' , ' max_query_size ' , <nl> + ' max_parallel_replicas ' , ' readonly ' ) <nl> + AND changed <nl> + ORDER BY name <nl> + ' ' ' , user = ' test_combined_profile ' ) <nl> + <nl> + expected1 = ' ' ' \ <nl> + max_insert_block_size 654321 <nl> + max_network_bytes 1234567890 <nl> + max_parallel_replicas 2 <nl> + max_query_size 400000000 <nl> + readonly 2 ' ' ' <nl> + <nl> + assert TSV ( settings ) = = TSV ( expected1 ) <nl> + <nl> + with pytest . raises ( QueryRuntimeException ) as exc : <nl> + q ( ' ' ' <nl> + SET max_insert_block_size = 1000 ; <nl> + ' ' ' , user = ' test_combined_profile ' ) <nl> + <nl> + assert ( " max_insert_block_size shouldn ' t be less than 654320 . " in <nl> + str ( exc . value ) ) <nl> + <nl> + with pytest . raises ( QueryRuntimeException ) as exc : <nl> + q ( ' ' ' <nl> + SET max_network_bytes = 2000000000 ; <nl> + ' ' ' , user = ' test_combined_profile ' ) <nl> + <nl> + assert ( " max_network_bytes shouldn ' t be greater than 1234567891 . " in <nl> + str ( exc . value ) ) <nl> + <nl> + with pytest . raises ( QueryRuntimeException ) as exc : <nl> + q ( ' ' ' <nl> + SET max_parallel_replicas = 1000 ; <nl> + ' ' ' , user = ' test_combined_profile ' ) <nl> + <nl> + assert ( ' max_parallel_replicas should not be changed . ' in <nl> + str ( exc . value ) ) <nl> + <nl> + with pytest . raises ( QueryRuntimeException ) as exc : <nl> + q ( ' ' ' <nl> + SET max_memory_usage = 1000 ; <nl> + ' ' ' , user = ' test_combined_profile ' ) <nl> + <nl> + assert ( " max_memory_usage shouldn ' t be less than 300000000 . " in <nl> + str ( exc . value ) ) <nl> mmm a / dbms / tests / integration / test_ttl_move / test . py <nl> ppp b / dbms / tests / integration / test_ttl_move / test . py <nl> def test_ttls_do_not_work_after_alter ( started_cluster , name , engine , positive ) : <nl> <nl> finally : <nl> node1 . query ( " DROP TABLE IF EXISTS { } " . format ( name ) ) <nl> + <nl> + <nl> + @ pytest . mark . parametrize ( " name , engine , positive " , [ <nl> + ( " mt_test_alter_multiple_ttls_positive " , " MergeTree ( ) " , True ) , <nl> + ( " mt_replicated_test_alter_multiple_ttls_positive " , " ReplicatedMergeTree ( ' / clickhouse / replicated_test_alter_multiple_ttls_positive ' , ' 1 ' ) " , True ) , <nl> + ( " mt_test_alter_multiple_ttls_negative " , " MergeTree ( ) " , False ) , <nl> + ( " mt_replicated_test_alter_multiple_ttls_negative " , " ReplicatedMergeTree ( ' / clickhouse / replicated_test_alter_multiple_ttls_negative ' , ' 1 ' ) " , False ) , <nl> + ] ) <nl> + def test_alter_multiple_ttls ( started_cluster , name , engine , positive ) : <nl> + " " " Copyright 2019 , Altinity LTD <nl> + <nl> + Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + you may not use this file except in compliance with the License . <nl> + You may obtain a copy of the License at <nl> + <nl> + http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + <nl> + Unless required by applicable law or agreed to in writing , software <nl> + distributed under the License is distributed on an " AS IS " BASIS , <nl> + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + See the License for the specific language governing permissions and <nl> + limitations under the License . " " " <nl> + " " " Check that when multiple TTL expressions are set <nl> + and before any parts are inserted the TTL expressions <nl> + are changed with ALTER command then all old <nl> + TTL expressions are removed and the <nl> + the parts are moved to the specified disk or volume or <nl> + deleted if the new TTL expression is triggered <nl> + and are not moved or deleted when it is not . <nl> + " " " <nl> + now = time . time ( ) <nl> + try : <nl> + node1 . query ( " " " <nl> + CREATE TABLE { name } ( <nl> + p1 Int64 , <nl> + s1 String , <nl> + d1 DateTime <nl> + ) ENGINE = { engine } <nl> + ORDER BY tuple ( ) <nl> + PARTITION BY p1 <nl> + TTL d1 + INTERVAL 30 SECOND TO DISK ' jbod2 ' , <nl> + d1 + INTERVAL 60 SECOND TO VOLUME ' external ' <nl> + SETTINGS storage_policy = ' jbods_with_external ' , merge_with_ttl_timeout = 0 <nl> + " " " . format ( name = name , engine = engine ) ) <nl> + <nl> + node1 . query ( " " " <nl> + ALTER TABLE { name } MODIFY <nl> + TTL d1 + INTERVAL 0 SECOND TO DISK ' jbod2 ' , <nl> + d1 + INTERVAL 5 SECOND TO VOLUME ' external ' , <nl> + d1 + INTERVAL 10 SECOND DELETE <nl> + " " " . format ( name = name ) ) <nl> + <nl> + for p in range ( 3 ) : <nl> + data = [ ] # 6MB in total <nl> + now = time . time ( ) <nl> + for i in range ( 2 ) : <nl> + p1 = p <nl> + s1 = get_random_string ( 1024 * 1024 ) # 1MB <nl> + d1 = now - 1 if i > 0 or positive else now + 300 <nl> + data . append ( " ( { } , ' { } ' , toDateTime ( { } ) ) " . format ( p1 , s1 , d1 ) ) <nl> + node1 . query ( " INSERT INTO { name } ( p1 , s1 , d1 ) VALUES { values } " . format ( name = name , values = " , " . join ( data ) ) ) <nl> + <nl> + used_disks = get_used_disks_for_table ( node1 , name ) <nl> + assert set ( used_disks ) = = { " jbod2 " } if positive else { " jbod1 " , " jbod2 " } <nl> + <nl> + assert node1 . query ( " SELECT count ( ) FROM { name } " . format ( name = name ) ) . splitlines ( ) = = [ " 6 " ] <nl> + <nl> + time . sleep ( 5 ) <nl> + <nl> + used_disks = get_used_disks_for_table ( node1 , name ) <nl> + assert set ( used_disks ) = = { " external " } if positive else { " jbod1 " , " jbod2 " } <nl> + <nl> + assert node1 . query ( " SELECT count ( ) FROM { name } " . format ( name = name ) ) . splitlines ( ) = = [ " 6 " ] <nl> + <nl> + time . sleep ( 5 ) <nl> + <nl> + node1 . query ( " OPTIMIZE TABLE { name } FINAL " . format ( name = name ) ) <nl> + <nl> + assert node1 . query ( " SELECT count ( ) FROM { name } " . format ( name = name ) ) . splitlines ( ) = = [ " 0 " ] if positive else [ " 3 " ] <nl> + <nl> + finally : <nl> + node1 . query ( " DROP TABLE IF EXISTS { name } " . format ( name = name ) ) <nl> mmm a / docs / en / operations / settings / settings_profiles . md <nl> ppp b / docs / en / operations / settings / settings_profiles . md <nl> Example : <nl> <nl> The example specifies two profiles : ` default ` and ` web ` . The ` default ` profile has a special purpose : it must always be present and is applied when starting the server . In other words , the ` default ` profile contains default settings . The ` web ` profile is a regular profile that can be set using the ` SET ` query or using a URL parameter in an HTTP query . <nl> <nl> - Settings profiles can inherit from each other . To use inheritance , indicate the ` profile ` setting before the other settings that are listed in the profile . <nl> + Settings profiles can inherit from each other . To use inheritance , indicate one or multiple ` profile ` settings before the other settings that are listed in the profile . In case when one setting is defined in different profiles , the latest defined is used . <nl> <nl> <nl> [ Original article ] ( https : / / clickhouse . yandex / docs / en / operations / settings / settings_profiles / ) < ! - - hide - - > <nl> mmm a / docs / ru / operations / settings / settings_profiles . md <nl> ppp b / docs / ru / operations / settings / settings_profiles . md <nl> SET profile = ' web ' <nl> <nl> В примере задано два профиля : ` default ` и ` web ` . Профиль ` default ` имеет специальное значение - он всегда обязан присутствовать и применяется при запуске сервера . То есть , профиль ` default ` содержит настройки по умолчанию . Профиль ` web ` - обычный профиль , который может быть установлен с помощью запроса ` SET ` или с помощью параметра URL при запросе по HTTP . <nl> <nl> - Профили настроек могут наследоваться от друг - друга - это реализуется указанием настройки ` profile ` перед остальными настройками , перечисленными в профиле . <nl> + Профили настроек могут наследоваться от друг - друга - это реализуется указанием одной или нескольких настроек ` profile ` перед остальными настройками , перечисленными в профиле . Если одна настройка указана в нескольких профилях , используется последнее из значений . <nl> <nl> [ Оригинальная статья ] ( https : / / clickhouse . yandex / docs / ru / operations / settings / settings_profiles / ) < ! - - hide - - > <nl> deleted file mode 100644 <nl> index c335e249212 . . 00000000000 <nl> mmm a / docs / zh / operations / settings / settings_profiles . md <nl> ppp / dev / null <nl> <nl> - <nl> - # Settings profiles <nl> - <nl> - A settings profile is a collection of settings grouped under the same name . Each ClickHouse user has a profile . <nl> - To apply all the settings in a profile , set the ` profile ` setting . <nl> - <nl> - Example : <nl> - <nl> - Install the ` web ` profile . <nl> - <nl> - ` ` ` sql <nl> - SET profile = ' web ' <nl> - ` ` ` <nl> - <nl> - Settings profiles are declared in the user config file . This is usually ` users . xml ` . <nl> - <nl> - Example : <nl> - <nl> - ` ` ` xml <nl> - < ! - - Settings profiles - - > <nl> - < profiles > <nl> - < ! - - Default settings - - > <nl> - < default > <nl> - < ! - - The maximum number of threads when running a single query . - - > <nl> - < max_threads > 8 < / max_threads > <nl> - < / default > <nl> - <nl> - < ! - - Settings for quries from the user interface - - > <nl> - < web > <nl> - < max_rows_to_read > 1000000000 < / max_rows_to_read > <nl> - < max_bytes_to_read > 100000000000 < / max_bytes_to_read > <nl> - <nl> - < max_rows_to_group_by > 1000000 < / max_rows_to_group_by > <nl> - < group_by_overflow_mode > any < / group_by_overflow_mode > <nl> - <nl> - < max_rows_to_sort > 1000000 < / max_rows_to_sort > <nl> - < max_bytes_to_sort > 1000000000 < / max_bytes_to_sort > <nl> - <nl> - < max_result_rows > 100000 < / max_result_rows > <nl> - < max_result_bytes > 100000000 < / max_result_bytes > <nl> - < result_overflow_mode > break < / result_overflow_mode > <nl> - <nl> - < max_execution_time > 600 < / max_execution_time > <nl> - < min_execution_speed > 1000000 < / min_execution_speed > <nl> - < timeout_before_checking_execution_speed > 15 < / timeout_before_checking_execution_speed > <nl> - <nl> - < max_columns_to_read > 25 < / max_columns_to_read > <nl> - < max_temporary_columns > 100 < / max_temporary_columns > <nl> - < max_temporary_non_const_columns > 50 < / max_temporary_non_const_columns > <nl> - <nl> - < max_subquery_depth > 2 < / max_subquery_depth > <nl> - < max_pipeline_depth > 25 < / max_pipeline_depth > <nl> - < max_ast_depth > 50 < / max_ast_depth > <nl> - < max_ast_elements > 100 < / max_ast_elements > <nl> - <nl> - < readonly > 1 < / readonly > <nl> - < / web > <nl> - < / profiles > <nl> - ` ` ` <nl> - <nl> - The example specifies two profiles : ` default ` and ` web ` . The ` default ` profile has a special purpose : it must always be present and is applied when starting the server . In other words , the ` default ` profile contains default settings . The ` web ` profile is a regular profile that can be set using the ` SET ` query or using a URL parameter in an HTTP query . <nl> - <nl> - Settings profiles can inherit from each other . To use inheritance , indicate the ` profile ` setting before the other settings that are listed in the profile . <nl> - <nl> - <nl> - [ Original article ] ( https : / / clickhouse . yandex / docs / en / operations / settings / settings_profiles / ) < ! - - hide - - > <nl> new file mode 120000 <nl> index 00000000000 . . 35d9747ad56 <nl> mmm / dev / null <nl> ppp b / docs / zh / operations / settings / settings_profiles . md <nl> @ @ - 0 , 0 + 1 @ @ <nl> + . . / . . / . . / en / operations / settings / settings_profiles . md <nl> \ No newline at end of file <nl>
Merge with master
ClickHouse/ClickHouse
10312a1d88c5835d5f700780ecab28dfe1609b50
2019-12-28T09:56:14Z
mmm a / tensorflow / core / ops / compat / ops_history . v1 . pbtxt <nl> ppp b / tensorflow / core / ops / compat / ops_history . v1 . pbtxt <nl> op { <nl> minimum : 1 <nl> } <nl> } <nl> + op { <nl> + name : " ExperimentalChooseFastestDataset " <nl> + input_arg { <nl> + name : " input_datasets " <nl> + type : DT_VARIANT <nl> + number_attr : " N " <nl> + } <nl> + output_arg { <nl> + name : " handle " <nl> + type : DT_VARIANT <nl> + } <nl> + attr { <nl> + name : " N " <nl> + type : " int " <nl> + has_minimum : true <nl> + minimum : 2 <nl> + } <nl> + attr { <nl> + name : " num_experiments " <nl> + type : " int " <nl> + } <nl> + attr { <nl> + name : " output_types " <nl> + type : " list ( type ) " <nl> + has_minimum : true <nl> + minimum : 1 <nl> + } <nl> + attr { <nl> + name : " output_shapes " <nl> + type : " list ( shape ) " <nl> + has_minimum : true <nl> + minimum : 1 <nl> + } <nl> + } <nl> op { <nl> name : " ExperimentalDatasetCardinality " <nl> input_arg { <nl> mmm a / tensorflow / core / ops / ops . pbtxt <nl> ppp b / tensorflow / core / ops / ops . pbtxt <nl> op { <nl> name : " num_experiments " <nl> type : " int " <nl> } <nl> + attr { <nl> + name : " output_types " <nl> + type : " list ( type ) " <nl> + has_minimum : true <nl> + minimum : 1 <nl> + } <nl> + attr { <nl> + name : " output_shapes " <nl> + type : " list ( shape ) " <nl> + has_minimum : true <nl> + minimum : 1 <nl> + } <nl> } <nl> op { <nl> name : " ExperimentalDatasetCardinality " <nl>
Update ops - related pbtxt files .
tensorflow/tensorflow
7bb36fb62d6c5b3e24deb1a479035963beaee8b3
2019-01-26T01:49:47Z
mmm a / hphp / runtime / vm / jit / check . cpp <nl> ppp b / hphp / runtime / vm / jit / check . cpp <nl> using TypeNames : : TCA ; <nl> # define DVArr <nl> # define DDArr <nl> # define DStaticDArr <nl> - # define DCheckDV ( . . . ) <nl> # define DCol <nl> # define DCns <nl> # define DMemoKey <nl> mmm a / hphp / runtime / vm / jit / ir - instruction . cpp <nl> ppp b / hphp / runtime / vm / jit / ir - instruction . cpp <nl> Type outputType ( const IRInstruction * inst , int / * dstId * / ) { <nl> # define DVArr return checkLayoutFlags ( RO : : EvalHackArrDVArrs ? TVec : TVArr ) ; <nl> # define DDArr return checkLayoutFlags ( RO : : EvalHackArrDVArrs ? TDict : TDArr ) ; <nl> # define DStaticDArr return ( TStaticDict | TStaticArr ) & [ & ] { DDArr } ( ) ; <nl> - / / Refine the input type to be either a TVArr or TDArr , as appropriate . <nl> - # define DCheckDV ( k ) return inst - > getPassthroughValue ( ) - > type ( ) & T # # k # # Arr ; <nl> # define DCol return newColReturn ( inst ) ; <nl> # define DMulti return TBottom ; <nl> # define DSetElem return setElemReturn ( inst ) ; <nl> mmm a / hphp / runtime / vm / jit / ir - opcode . cpp <nl> ppp b / hphp / runtime / vm / jit / ir - opcode . cpp <nl> TRACE_SET_MOD ( hhir ) ; <nl> # define DVArr HasDest <nl> # define DDArr HasDest <nl> # define DStaticDArr HasDest <nl> - # define DCheckDV ( . . . ) HasDest <nl> # define DCol HasDest <nl> # define DMulti NaryDest <nl> # define DSetElem HasDest <nl> OpInfo g_opInfo [ ] = { <nl> # undef DVArr <nl> # undef DDArr <nl> # undef DStaticDArr <nl> - # undef DCheckDV <nl> # undef DCol <nl> # undef DAllocObj <nl> # undef DMulti <nl> mmm a / hphp / runtime / vm / jit / ir - opcode . h <nl> ppp b / hphp / runtime / vm / jit / ir - opcode . h <nl> struct SSATmp ; <nl> on configuration <nl> * DDArr single dst is either a mixed array type or dict , depending <nl> on configuration <nl> - * DCheckDV ( kind ) single dst either has the given array kind or is bespoke ; <nl> - if the src is vanilla , the dst is vanilla as well <nl> * DArrElem single dst has type based on reading an array element , <nl> * intersected with an optional type parameter <nl> * DVecElem single dst has type based on reading a vec element , <nl>
Remove DCheckDV
facebook/hhvm
bc960aaf0017ed94b6c80fd35af7a3f626d258b3
2020-07-06T19:04:43Z
mmm a / arcanist_util / config / FacebookArcanistConfiguration . php <nl> ppp b / arcanist_util / config / FacebookArcanistConfiguration . php <nl> <nl> / / This source code is licensed under the BSD - style license found in the <nl> / / LICENSE file in the root directory of this source tree . An additional grant <nl> / / of patent rights can be found in the PATENTS file in the same directory . <nl> + <nl> + require ( ' RocksDBCommonHelper . php ' ) ; <nl> + <nl> + define ( " DIFF_COMMAND " , " diff " ) ; <nl> + <nl> class FacebookArcanistConfiguration extends ArcanistConfiguration { <nl> <nl> public function didRunWorkflow ( $ command , <nl> ArcanistWorkflow $ workflow , <nl> $ error_code ) { <nl> - if ( $ command = = ' diff ' & & ! $ workflow - > isRawDiffSource ( ) ) { <nl> - $ this - > startTestsInSandcastle ( $ workflow ) ; <nl> - } <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / * Run tests in sandcastle * / <nl> - function postURL ( $ diffID , $ url ) { <nl> - $ cmd = ' echo \ ' { " diff_id " : " ' . $ diffID . ' " , ' <nl> - . ' " name " : " click here for sandcastle tests for D ' . $ diffID . ' " , ' <nl> - . ' " link " : " ' . $ url . ' " } \ ' | ' <nl> - . ' http_proxy = fwdproxy . any . facebook . com : 8080 ' <nl> - . ' https_proxy = fwdproxy . any . facebook . com : 8080 arc call - conduit ' <nl> - . ' differential . updateunitresults ' ; <nl> - shell_exec ( $ cmd ) ; <nl> - } <nl> - <nl> - function updateTestCommand ( $ diffID , $ test , $ status ) { <nl> - $ cmd = ' echo \ ' { " diff_id " : " ' . $ diffID . ' " , ' <nl> - . ' " name " : " ' . $ test . ' " , ' <nl> - . ' " result " : " ' . $ status . ' " } \ ' | ' <nl> - . ' http_proxy = fwdproxy . any . facebook . com : 8080 ' <nl> - . ' https_proxy = fwdproxy . any . facebook . com : 8080 arc call - conduit ' <nl> - . ' differential . updateunitresults ' ; <nl> - return $ cmd ; <nl> - } <nl> - <nl> - function updateTest ( $ diffID , $ test ) { <nl> - shell_exec ( $ this - > updateTestCommand ( $ diffID , $ test , " waiting " ) ) ; <nl> - } <nl> - <nl> - function getSteps ( $ diffID , $ username , $ test ) { <nl> - $ arcrc_content = exec ( " cat ~ / . arcrc | gzip - f | base64 - w0 " ) ; <nl> - <nl> - / / Sandcastle machines don ' t have arc setup . We copy the user certificate <nl> - / / and authenticate using that in sandcastle <nl> - $ setup = array ( <nl> - " name " = > " Setup arcrc " , <nl> - " shell " = > " echo " . $ arcrc_content . " | base64 - - decode " <nl> - . " | gzip - d > ~ / . arcrc " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / arc demands certain permission on its config <nl> - $ fix_permission = array ( <nl> - " name " = > " Fix environment " , <nl> - " shell " = > " chmod 600 ~ / . arcrc " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / fbcode is a sub - repo . We cannot patch until we add it to ignore otherwise <nl> - / / git thinks it is uncommited change <nl> - $ fix_git_ignore = array ( <nl> - " name " = > " Fix git ignore " , <nl> - " shell " = > " echo fbcode > > . git / info / exclude " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / Patch the code ( keep your fingures crossed ) <nl> - $ patch = array ( <nl> - " name " = > " Patch " . $ diffID , <nl> - " shell " = > " HTTPS_PROXY = fwdproxy : 8080 arc - - arcrc - file ~ / . arcrc " <nl> - . " patch - - nocommit - - diff " . $ diffID , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / Clean up the user arc config we are using <nl> - $ cleanup = array ( <nl> - " name " = > " Arc cleanup " , <nl> - " shell " = > " rm - f ~ / . arcrc " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / Construct the steps in the order of execution <nl> - $ steps [ ] = $ setup ; <nl> - $ steps [ ] = $ fix_permission ; <nl> - $ steps [ ] = $ fix_git_ignore ; <nl> - $ steps [ ] = $ patch ; <nl> - <nl> - / / Run the actual command <nl> - $ this - > updateTest ( $ diffID , $ test ) ; <nl> - $ cmd = $ this - > updateTestCommand ( $ diffID , $ test , " running " ) . " ; " <nl> - . " . / build_tools / precommit_checker . py " . $ test <nl> - . " ; exit_code = $ ? ; ( [ [ \ $ exit_code - eq 0 ] ] & & " <nl> - . $ this - > updateTestCommand ( $ diffID , $ test , " pass " ) . " ) " <nl> - . " | | " . $ this - > updateTestCommand ( $ diffID , $ test , " fail " ) <nl> - . " ; cat / tmp / precommit - check . log " <nl> - . " ; for f in ` ls t / log - * ` ; do echo \ $ f ; cat \ $ f ; done ; " <nl> - . " [ [ \ $ exit_code - eq 0 ] ] " ; <nl> - <nl> - $ run_test = array ( <nl> - " name " = > " Run " . $ test , <nl> - " shell " = > $ cmd , <nl> - " user " = > " root " , <nl> - ) ; <nl> - <nl> - $ steps [ ] = $ run_test ; <nl> - $ steps [ ] = $ cleanup ; <nl> - <nl> - return $ steps ; <nl> - } <nl> - <nl> - function startTestsInSandcastle ( $ workflow ) { <nl> - / / extract information we need from workflow or CLI <nl> - $ diffID = $ workflow - > getDiffId ( ) ; <nl> - $ username = exec ( " whoami " ) ; <nl> - <nl> - if ( $ diffID = = null | | $ username = = null ) { <nl> - / / there is no diff and we can ' t extract username <nl> - / / we cannot schedule sandcasstle job <nl> - return ; <nl> - } <nl> - <nl> - if ( strcmp ( getenv ( " ROCKSDB_CHECK_ALL " ) , 1 ) = = 0 ) { <nl> - / / extract all tests from the CI definition <nl> - $ output = file_get_contents ( " build_tools / rocksdb - lego - determinator " ) ; <nl> - preg_match_all ( ' / [ ] { 2 } ( [ a - zA - Z0 - 9_ ] + ) [ \ ) ] { 1 } / ' , $ output , $ matches ) ; <nl> - $ tests = $ matches [ 1 ] ; <nl> - } else { <nl> - / / manually list of tests we want to run in sandcastle <nl> - $ tests = array ( <nl> - " unit " , " unit_481 " , " clang_unit " , " tsan " , " asan " , " lite_test " , " valgrind " <nl> - ) ; <nl> - } <nl> - <nl> - / / construct a job definition for each test and add it to the master plan <nl> - foreach ( $ tests as $ test ) { <nl> - $ arg [ ] = array ( <nl> - " name " = > " RocksDB diff " . $ diffID . " test " . $ test , <nl> - " steps " = > $ this - > getSteps ( $ diffID , $ username , $ test ) <nl> - ) ; <nl> - } <nl> - <nl> - / / we cannot submit the parallel execution master plan to sandcastle <nl> - / / we need supply the job plan as a determinator <nl> - / / so we construct a small job that will spit out the master job plan <nl> - / / which sandcastle will parse and execute <nl> - / / Why compress ? Otherwise we run over the max string size . <nl> - $ cmd = " echo " . base64_encode ( json_encode ( $ arg ) ) <nl> - . " | gzip - f | base64 - w0 " ; <nl> - $ arg_encoded = shell_exec ( $ cmd ) ; <nl> - <nl> - $ command = array ( <nl> - " name " = > " Run diff " . $ diffID . " for user " . $ username , <nl> - " steps " = > array ( ) <nl> - ) ; <nl> - <nl> - $ command [ " steps " ] [ ] = array ( <nl> - " name " = > " Generate determinator " , <nl> - " shell " = > " echo " . $ arg_encoded . " | base64 - - decode | gzip - d " <nl> - . " | base64 - - decode " , <nl> - " determinator " = > true , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / submit to sandcastle <nl> - $ url = ' https : / / interngraph . intern . facebook . com / sandcastle / generate ? ' <nl> - . ' command = SandcastleUniversalCommand ' <nl> - . ' & vcs = rocksdb - git & revision = origin % 2Fmaster & type = lego ' <nl> - . ' & user = krad & alias = rocksdb - precommit ' <nl> - . ' & command - args = ' . urlencode ( json_encode ( $ command ) ) ; <nl> - <nl> - if ( file_exists ( ' / home / krad / . sandcastle ' ) ) { <nl> - $ cmd = ' cat / home / krad / . sandcastle ' ; <nl> - } else { <nl> - $ cmd = ' cat ~ / . sandcastle ' ; <nl> - } <nl> - $ sandcastle_config = explode ( ' : ' , rtrim ( shell_exec ( $ cmd ) ) ) ; <nl> - <nl> - if ( count ( $ sandcastle_config ) ! = 2 ) { <nl> - print ( ' . sandcastle does not contain valid configuration ' ) ; <nl> - return ; <nl> - } <nl> - <nl> - $ app = $ sandcastle_config [ 0 ] ; <nl> - $ token = $ sandcastle_config [ 1 ] ; <nl> - <nl> - $ cmd = ' https_proxy = HTTPS_PROXY = curl - s - k - F app = ' . $ app . ' ' <nl> - . ' - F token = ' . $ token . ' " ' . $ url . ' " ' ; <nl> - <nl> - $ output = shell_exec ( $ cmd ) ; <nl> - <nl> - / / extract sandcastle URL from the response <nl> - preg_match ( ' / url " : " ( . + ) " / ' , $ output , $ sandcastle_url ) ; <nl> - <nl> - if ( count ( $ sandcastle_url ) > 1 ) { <nl> - echo " \ nSandcastle URL : " . $ sandcastle_url [ 1 ] . " \ n " ; <nl> - <nl> - / / Ask phabricator to display it on the diff UI <nl> - $ this - > postURL ( $ diffID , $ sandcastle_url [ 1 ] ) ; <nl> - } else { <nl> - print ( " Error submitting job to sandcastle . " ) ; <nl> - print ( $ output ) ; <nl> + / / Default options don ' t terminate on failure , but that ' s what we want . In <nl> + / / the current case we use assertions intentionally as " terminate on failure <nl> + / / invariants " . <nl> + assert_options ( ASSERT_BAIL , true ) ; <nl> + <nl> + assert ( $ workflow ) ; <nl> + assert ( strlen ( $ command ) > 0 ) ; <nl> + <nl> + if ( $ command = = DIFF_COMMAND & & ! $ workflow - > isRawDiffSource ( ) ) { <nl> + $ diffID = $ workflow - > getDiffId ( ) ; <nl> + <nl> + / / When submitting a diff this code path gets executed multiple times in <nl> + / / a row . We only care about the case when ID for the diff is provided <nl> + / / because that ' s what we need to apply the diff and trigger the tests . <nl> + if ( strlen ( $ diffID ) > 0 ) { <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + startTestsInSandcastle ( true / * $ applyDiff * / , $ workflow , $ diffID ) ; <nl> + } <nl> } <nl> } <nl> } <nl> mmm a / arcanist_util / config / FacebookOldArcanistConfiguration . php <nl> ppp b / arcanist_util / config / FacebookOldArcanistConfiguration . php <nl> <nl> / / LICENSE file in the root directory of this source tree . An additional grant <nl> / / of patent rights can be found in the PATENTS file in the same directory . <nl> <nl> + require ( ' RocksDBCommonHelper . php ' ) ; <nl> + <nl> + define ( " DIFF_COMMAND " , " diff " ) ; <nl> + <nl> class FacebookArcanistConfiguration extends ArcanistConfiguration { <nl> <nl> public function didRunWorkflow ( $ command , <nl> ArcanistBaseWorkflow $ workflow , <nl> $ error_code ) { <nl> - if ( $ command = = ' diff ' & & ! $ workflow - > isRawDiffSource ( ) ) { <nl> - $ this - > startTestsInSandcastle ( $ workflow ) ; <nl> + / / Default options don ' t terminate on failure , but that ' s what we want . In <nl> + / / the current case we use assertions intentionally as " terminate on failure <nl> + / / invariants " . <nl> + assert_options ( ASSERT_BAIL , true ) ; <nl> + <nl> + assert ( $ workflow ) ; <nl> + assert ( strlen ( $ command ) > 0 ) ; <nl> + <nl> + if ( $ command = = DIFF_COMMAND & & ! $ workflow - > isRawDiffSource ( ) ) { <nl> + $ diffID = $ workflow - > getDiffId ( ) ; <nl> + <nl> + / / When submitting a diff this code path gets executed multiple times in <nl> + / / a row . We only care about the case when ID for the diff is provided <nl> + / / because that ' s what we need to apply the diff and trigger the tests . <nl> + if ( strlen ( $ diffID ) > 0 ) { <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + startTestsInSandcastle ( true / * $ applyDiff * / , $ workflow , $ diffID ) ; <nl> + } <nl> } <nl> } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - / * Run tests in sandcastle * / <nl> - function postURL ( $ diffID , $ url ) { <nl> - $ cmd = ' echo \ ' { " diff_id " : " ' . $ diffID . ' " , ' <nl> - . ' " name " : " click here for sandcastle tests for D ' . $ diffID . ' " , ' <nl> - . ' " link " : " ' . $ url . ' " } \ ' | ' <nl> - . ' http_proxy = fwdproxy . any . facebook . com : 8080 ' <nl> - . ' https_proxy = fwdproxy . any . facebook . com : 8080 arc call - conduit ' <nl> - . ' differential . updateunitresults ' ; <nl> - shell_exec ( $ cmd ) ; <nl> - } <nl> - <nl> - function updateTestCommand ( $ diffID , $ test , $ status ) { <nl> - $ cmd = ' echo \ ' { " diff_id " : " ' . $ diffID . ' " , ' <nl> - . ' " name " : " ' . $ test . ' " , ' <nl> - . ' " result " : " ' . $ status . ' " } \ ' | ' <nl> - . ' http_proxy = fwdproxy . any . facebook . com : 8080 ' <nl> - . ' https_proxy = fwdproxy . any . facebook . com : 8080 arc call - conduit ' <nl> - . ' differential . updateunitresults ' ; <nl> - return $ cmd ; <nl> - } <nl> - <nl> - function updateTest ( $ diffID , $ test ) { <nl> - shell_exec ( $ this - > updateTestCommand ( $ diffID , $ test , " waiting " ) ) ; <nl> - } <nl> - <nl> - function getSteps ( $ diffID , $ username , $ test ) { <nl> - $ arcrc_content = exec ( " cat ~ / . arcrc | gzip - f | base64 - w0 " ) ; <nl> - <nl> - / / Sandcastle machines don ' t have arc setup . We copy the user certificate <nl> - / / and authenticate using that in sandcastle <nl> - $ setup = array ( <nl> - " name " = > " Setup arcrc " , <nl> - " shell " = > " echo " . $ arcrc_content . " | base64 - - decode " <nl> - . " | gzip - d > ~ / . arcrc " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / arc demands certain permission on its config <nl> - $ fix_permission = array ( <nl> - " name " = > " Fix environment " , <nl> - " shell " = > " chmod 600 ~ / . arcrc " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / fbcode is a sub - repo . We cannot patch until we add it to ignore otherwise <nl> - / / git thinks it is uncommited change <nl> - $ fix_git_ignore = array ( <nl> - " name " = > " Fix git ignore " , <nl> - " shell " = > " echo fbcode > > . git / info / exclude " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / Patch the code ( keep your fingures crossed ) <nl> - $ patch = array ( <nl> - " name " = > " Patch " . $ diffID , <nl> - " shell " = > " HTTPS_PROXY = fwdproxy : 8080 arc - - arcrc - file ~ / . arcrc " <nl> - . " patch - - nocommit - - diff " . $ diffID , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / Clean up the user arc config we are using <nl> - $ cleanup = array ( <nl> - " name " = > " Arc cleanup " , <nl> - " shell " = > " rm - f ~ / . arcrc " , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / Construct the steps in the order of execution <nl> - $ steps [ ] = $ setup ; <nl> - $ steps [ ] = $ fix_permission ; <nl> - $ steps [ ] = $ fix_git_ignore ; <nl> - $ steps [ ] = $ patch ; <nl> - <nl> - / / Run the actual command <nl> - $ this - > updateTest ( $ diffID , $ test ) ; <nl> - $ cmd = $ this - > updateTestCommand ( $ diffID , $ test , " running " ) . " ; " <nl> - . " . / build_tools / precommit_checker . py " . $ test <nl> - . " ; exit_code = $ ? ; ( [ [ \ $ exit_code - eq 0 ] ] & & " <nl> - . $ this - > updateTestCommand ( $ diffID , $ test , " pass " ) . " ) " <nl> - . " | | " . $ this - > updateTestCommand ( $ diffID , $ test , " fail " ) <nl> - . " ; cat / tmp / precommit - check . log " <nl> - . " ; for f in ` ls t / log - * ` ; do echo \ $ f ; cat \ $ f ; done ; " <nl> - . " [ [ \ $ exit_code - eq 0 ] ] " ; <nl> - <nl> - $ run_test = array ( <nl> - " name " = > " Run " . $ test , <nl> - " shell " = > $ cmd , <nl> - " user " = > " root " , <nl> - ) ; <nl> - <nl> - $ steps [ ] = $ run_test ; <nl> - $ steps [ ] = $ cleanup ; <nl> - <nl> - return $ steps ; <nl> - } <nl> - <nl> - function startTestsInSandcastle ( $ workflow ) { <nl> - / / extract information we need from workflow or CLI <nl> - $ diffID = $ workflow - > getDiffId ( ) ; <nl> - $ username = exec ( " whoami " ) ; <nl> - <nl> - if ( $ diffID = = null | | $ username = = null ) { <nl> - / / there is no diff and we can ' t extract username <nl> - / / we cannot schedule sandcasstle job <nl> - return ; <nl> - } <nl> - <nl> - if ( strcmp ( getenv ( " ROCKSDB_CHECK_ALL " ) , 1 ) = = 0 ) { <nl> - / / extract all tests from the CI definition <nl> - $ output = file_get_contents ( " build_tools / rocksdb - lego - determinator " ) ; <nl> - preg_match_all ( ' / [ ] { 2 } ( [ a - zA - Z0 - 9_ ] + ) [ \ ) ] { 1 } / ' , $ output , $ matches ) ; <nl> - $ tests = $ matches [ 1 ] ; <nl> - } else { <nl> - / / manually list of tests we want to run in sandcastle <nl> - $ tests = array ( <nl> - " unit " , " unit_481 " , " clang_unit " , " tsan " , " asan " , " lite_test " , " valgrind " <nl> - ) ; <nl> - } <nl> - <nl> - / / construct a job definition for each test and add it to the master plan <nl> - foreach ( $ tests as $ test ) { <nl> - $ arg [ ] = array ( <nl> - " name " = > " RocksDB diff " . $ diffID . " test " . $ test , <nl> - " steps " = > $ this - > getSteps ( $ diffID , $ username , $ test ) <nl> - ) ; <nl> - } <nl> - <nl> - / / we cannot submit the parallel execution master plan to sandcastle <nl> - / / we need supply the job plan as a determinator <nl> - / / so we construct a small job that will spit out the master job plan <nl> - / / which sandcastle will parse and execute <nl> - / / Why compress ? Otherwise we run over the max string size . <nl> - $ cmd = " echo " . base64_encode ( json_encode ( $ arg ) ) <nl> - . " | gzip - f | base64 - w0 " ; <nl> - $ arg_encoded = shell_exec ( $ cmd ) ; <nl> - <nl> - $ command = array ( <nl> - " name " = > " Run diff " . $ diffID . " for user " . $ username , <nl> - " steps " = > array ( ) <nl> - ) ; <nl> - <nl> - $ command [ " steps " ] [ ] = array ( <nl> - " name " = > " Generate determinator " , <nl> - " shell " = > " echo " . $ arg_encoded . " | base64 - - decode | gzip - d " <nl> - . " | base64 - - decode " , <nl> - " determinator " = > true , <nl> - " user " = > " root " <nl> - ) ; <nl> - <nl> - / / submit to sandcastle <nl> - $ url = ' https : / / interngraph . intern . facebook . com / sandcastle / generate ? ' <nl> - . ' command = SandcastleUniversalCommand ' <nl> - . ' & vcs = rocksdb - git & revision = origin % 2Fmaster & type = lego ' <nl> - . ' & user = krad & alias = rocksdb - precommit ' <nl> - . ' & command - args = ' . urlencode ( json_encode ( $ command ) ) ; <nl> - <nl> - $ cmd = ' https_proxy = HTTPS_PROXY = curl - s - k - F app = 659387027470559 ' <nl> - . ' - F token = AeO_3f2Ya3TujjnxGD4 " ' . $ url . ' " ' ; <nl> - <nl> - $ output = shell_exec ( $ cmd ) ; <nl> - <nl> - / / extract sandcastle URL from the response <nl> - preg_match ( ' / url " : " ( . + ) " / ' , $ output , $ sandcastle_url ) ; <nl> - <nl> - echo " \ nSandcastle URL : " . $ sandcastle_url [ 1 ] . " \ n " ; <nl> - <nl> - / / Ask phabricator to display it on the diff UI <nl> - $ this - > postURL ( $ diffID , $ sandcastle_url [ 1 ] ) ; <nl> - } <nl> } <nl> new file mode 100644 <nl> index 0000000000 . . 072f3f64fb <nl> mmm / dev / null <nl> ppp b / arcanist_util / config / RocksDBCommonHelper . php <nl> <nl> + < ? php <nl> + / / Copyright 2004 - present Facebook . All Rights Reserved . <nl> + / / This source code is licensed under the BSD - style license found in the <nl> + / / LICENSE file in the root directory of this source tree . An additional grant <nl> + / / of patent rights can be found in the PATENTS file in the same directory . <nl> + <nl> + / / Name of the environment variables which need to be set by the entity which <nl> + / / triggers continuous runs so that code at the end of the file gets executed <nl> + / / and Sandcastle run starts . <nl> + define ( " ENV_POST_RECEIVE_HOOK " , " POST_RECEIVE_HOOK " ) ; <nl> + define ( " ENV_HTTPS_APP_VALUE " , " HTTPS_APP_VALUE " ) ; <nl> + define ( " ENV_HTTPS_TOKEN_VALUE " , " HTTPS_TOKEN_VALUE " ) ; <nl> + <nl> + define ( " PRIMARY_TOKEN_FILE " , ' / home / krad / . sandcastle ' ) ; <nl> + define ( " SECONDARY_TOKEN_FILE " , ' $ HOME / . sandcastle ' ) ; <nl> + define ( " CONT_RUN_ALIAS " , " leveldb " ) ; <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / * Run tests in sandcastle * / <nl> + function postURL ( $ diffID , $ url ) { <nl> + assert ( strlen ( $ diffID ) > 0 ) ; <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + assert ( strlen ( $ url ) > 0 ) ; <nl> + <nl> + $ cmd = ' echo \ ' { " diff_id " : " ' . $ diffID . ' " , ' <nl> + . ' " name " : " click here for sandcastle tests for D ' . $ diffID . ' " , ' <nl> + . ' " link " : " ' . $ url . ' " } \ ' | ' <nl> + . ' http_proxy = fwdproxy . any . facebook . com : 8080 ' <nl> + . ' https_proxy = fwdproxy . any . facebook . com : 8080 arc call - conduit ' <nl> + . ' differential . updateunitresults ' ; <nl> + shell_exec ( $ cmd ) ; <nl> + } <nl> + <nl> + function buildUpdateTestStatusCmd ( $ diffID , $ test , $ status ) { <nl> + assert ( strlen ( $ diffID ) > 0 ) ; <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + assert ( strlen ( $ test ) > 0 ) ; <nl> + assert ( strlen ( $ status ) > 0 ) ; <nl> + <nl> + $ cmd = ' echo \ ' { " diff_id " : " ' . $ diffID . ' " , ' <nl> + . ' " name " : " ' . $ test . ' " , ' <nl> + . ' " result " : " ' . $ status . ' " } \ ' | ' <nl> + . ' http_proxy = fwdproxy . any . facebook . com : 8080 ' <nl> + . ' https_proxy = fwdproxy . any . facebook . com : 8080 arc call - conduit ' <nl> + . ' differential . updateunitresults ' ; <nl> + return $ cmd ; <nl> + } <nl> + <nl> + function updateTestStatus ( $ diffID , $ test ) { <nl> + assert ( strlen ( $ diffID ) > 0 ) ; <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + assert ( strlen ( $ test ) > 0 ) ; <nl> + <nl> + shell_exec ( buildUpdateTestStatusCmd ( $ diffID , $ test , " waiting " ) ) ; <nl> + } <nl> + <nl> + function getSteps ( $ applyDiff , $ diffID , $ username , $ test ) { <nl> + assert ( strlen ( $ username ) > 0 ) ; <nl> + assert ( strlen ( $ test ) > 0 ) ; <nl> + <nl> + if ( $ applyDiff ) { <nl> + assert ( strlen ( $ diffID ) > 0 ) ; <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + <nl> + $ arcrc_content = exec ( " cat ~ / . arcrc | gzip - f | base64 - w0 " ) ; <nl> + assert ( strlen ( $ arcrc_content ) > 0 ) ; <nl> + <nl> + / / Sandcastle machines don ' t have arc setup . We copy the user certificate <nl> + / / and authenticate using that in Sandcastle . <nl> + $ setup = array ( <nl> + " name " = > " Setup arcrc " , <nl> + " shell " = > " echo " . $ arcrc_content . " | base64 - - decode " <nl> + . " | gzip - d > ~ / . arcrc " , <nl> + " user " = > " root " <nl> + ) ; <nl> + <nl> + / / arc demands certain permission on its config . <nl> + $ fix_permission = array ( <nl> + " name " = > " Fix environment " , <nl> + " shell " = > " chmod 600 ~ / . arcrc " , <nl> + " user " = > " root " <nl> + ) ; <nl> + <nl> + / / Construct the steps in the order of execution . <nl> + $ steps [ ] = $ setup ; <nl> + $ steps [ ] = $ fix_permission ; <nl> + } <nl> + <nl> + / / fbcode is a sub - repo . We cannot patch until we add it to ignore otherwise <nl> + / / Git thinks it is an uncommited change . <nl> + $ fix_git_ignore = array ( <nl> + " name " = > " Fix git ignore " , <nl> + " shell " = > " echo fbcode > > . git / info / exclude " , <nl> + " user " = > " root " <nl> + ) ; <nl> + <nl> + $ steps [ ] = $ fix_git_ignore ; <nl> + <nl> + / / This will be the command used to execute particular type of tests . <nl> + $ cmd = " " ; <nl> + <nl> + if ( $ applyDiff ) { <nl> + / / Patch the code ( keep your fingures crossed ) . <nl> + $ patch = array ( <nl> + " name " = > " Patch " . $ diffID , <nl> + " shell " = > " HTTPS_PROXY = fwdproxy : 8080 arc - - arcrc - file ~ / . arcrc " <nl> + . " patch - - nocommit - - diff " . $ diffID , <nl> + " user " = > " root " <nl> + ) ; <nl> + <nl> + $ steps [ ] = $ patch ; <nl> + <nl> + updateTestStatus ( $ diffID , $ test ) ; <nl> + $ cmd = buildUpdateTestStatusCmd ( $ diffID , $ test , " running " ) . " ; " ; <nl> + } <nl> + <nl> + / / Run the actual command . <nl> + $ cmd = $ cmd . " . / build_tools / precommit_checker . py " . $ test <nl> + . " ; exit_code = $ ? ; " ; <nl> + <nl> + if ( $ applyDiff ) { <nl> + $ cmd = $ cmd . " ( [ [ \ $ exit_code - eq 0 ] ] & & " <nl> + . buildUpdateTestStatusCmd ( $ diffID , $ test , " pass " ) . " ) " <nl> + . " | | " . buildUpdateTestStatusCmd ( $ diffID , $ test , " fail " ) <nl> + . " ; " ; <nl> + } <nl> + <nl> + $ cmd = $ cmd . " cat / tmp / precommit - check . log " <nl> + . " ; for f in ` ls t / log - * ` ; do echo \ $ f ; cat \ $ f ; done ; " <nl> + . " [ [ \ $ exit_code - eq 0 ] ] " ; <nl> + assert ( strlen ( $ cmd ) > 0 ) ; <nl> + <nl> + $ run_test = array ( <nl> + " name " = > " Run " . $ test , <nl> + " shell " = > $ cmd , <nl> + " user " = > " root " , <nl> + ) ; <nl> + <nl> + $ steps [ ] = $ run_test ; <nl> + <nl> + if ( $ applyDiff ) { <nl> + / / Clean up the user arc config we are using . <nl> + $ cleanup = array ( <nl> + " name " = > " Arc cleanup " , <nl> + " shell " = > " rm - f ~ / . arcrc " , <nl> + " user " = > " root " <nl> + ) ; <nl> + <nl> + $ steps [ ] = $ cleanup ; <nl> + } <nl> + <nl> + assert ( count ( $ steps ) > 0 ) ; <nl> + return $ steps ; <nl> + } <nl> + <nl> + function getSandcastleConfig ( ) { <nl> + $ sandcastle_config = array ( ) ; <nl> + <nl> + / / This is a case when we ' re executed from a continuous run . Fetch the values <nl> + / / from the environment . <nl> + if ( getenv ( ENV_POST_RECEIVE_HOOK ) ) { <nl> + $ sandcastle_config [ 0 ] = getenv ( ENV_HTTPS_APP_VALUE ) ; <nl> + $ sandcastle_config [ 1 ] = getenv ( ENV_HTTPS_TOKEN_VALUE ) ; <nl> + } else { <nl> + / / This is a typical ` [ p ] arc diff ` case . Fetch the values from the specific <nl> + / / configuration files . <nl> + assert ( file_exists ( PRIMARY_TOKEN_FILE ) | | <nl> + file_exists ( SECONDARY_TOKEN_FILE ) ) ; <nl> + <nl> + / / Try the primary location first , followed by a secondary . <nl> + if ( file_exists ( PRIMARY_TOKEN_FILE ) ) { <nl> + $ cmd = ' cat ' . PRIMARY_TOKEN_FILE ; <nl> + } else { <nl> + $ cmd = ' cat ' . SECONDARY_TOKEN_FILE ; <nl> + } <nl> + <nl> + assert ( strlen ( $ cmd ) > 0 ) ; <nl> + $ sandcastle_config = explode ( ' : ' , rtrim ( shell_exec ( $ cmd ) ) ) ; <nl> + } <nl> + <nl> + / / In this case be very explicit about the implications . <nl> + if ( count ( $ sandcastle_config ) ! = 2 ) { <nl> + echo " Sandcastle configuration files don ' t contain valid information " . <nl> + " or the necessary environment variables aren ' t defined . Unable " . <nl> + " to validate the code changes . " ; <nl> + exit ( 1 ) ; <nl> + } <nl> + <nl> + assert ( strlen ( $ sandcastle_config [ 0 ] ) > 0 ) ; <nl> + assert ( strlen ( $ sandcastle_config [ 1 ] ) > 0 ) ; <nl> + assert ( count ( $ sandcastle_config ) > 0 ) ; <nl> + <nl> + return $ sandcastle_config ; <nl> + } <nl> + <nl> + / / This function can be called either from ` [ p ] arc diff ` command or during <nl> + / / the Git post - receive hook . <nl> + function startTestsInSandcastle ( $ applyDiff , $ workflow , $ diffID ) { <nl> + / / Default options don ' t terminate on failure , but that ' s what we want . In <nl> + / / the current case we use assertions intentionally as " terminate on failure <nl> + / / invariants " . <nl> + assert_options ( ASSERT_BAIL , true ) ; <nl> + <nl> + / / In case of a diff we ' ll send notificatios to the author . Else it ' ll go to <nl> + / / the entire team because failures indicate that build quality has regressed . <nl> + $ username = $ applyDiff ? exec ( " whoami " ) : CONT_RUN_ALIAS ; <nl> + assert ( strlen ( $ username ) > 0 ) ; <nl> + <nl> + if ( $ applyDiff ) { <nl> + assert ( $ workflow ) ; <nl> + assert ( strlen ( $ diffID ) > 0 ) ; <nl> + assert ( is_numeric ( $ diffID ) ) ; <nl> + } <nl> + <nl> + if ( strcmp ( getenv ( " ROCKSDB_CHECK_ALL " ) , 1 ) = = 0 ) { <nl> + / / Extract all tests from the CI definition . <nl> + $ output = file_get_contents ( " build_tools / rocksdb - lego - determinator " ) ; <nl> + assert ( strlen ( $ output ) > 0 ) ; <nl> + <nl> + preg_match_all ( ' / [ ] { 2 } ( [ a - zA - Z0 - 9_ ] + ) [ \ ) ] { 1 } / ' , $ output , $ matches ) ; <nl> + $ tests = $ matches [ 1 ] ; <nl> + assert ( count ( $ tests ) > 0 ) ; <nl> + } else { <nl> + / / Manually list of tests we want to run in Sandcastle . <nl> + $ tests = array ( <nl> + " unit " , " unit_481 " , " clang_unit " , " tsan " , " asan " , " lite_test " , <nl> + " valgrind " <nl> + ) ; <nl> + } <nl> + <nl> + $ send_email_template = array ( <nl> + ' type ' = > ' email ' , <nl> + ' triggers ' = > array ( ' fail ' ) , <nl> + ' emails ' = > array ( $ username . ' @ fb . com ' ) , <nl> + ) ; <nl> + <nl> + / / Construct a job definition for each test and add it to the master plan . <nl> + foreach ( $ tests as $ test ) { <nl> + $ stepName = " RocksDB diff " . $ diffID . " test " . $ test ; <nl> + <nl> + if ( ! $ applyDiff ) { <nl> + $ stepName = " RocksDB continuous integration test " . $ test ; <nl> + } <nl> + <nl> + $ arg [ ] = array ( <nl> + " name " = > $ stepName , <nl> + " report " = > array ( $ send_email_template ) , <nl> + " steps " = > getSteps ( $ applyDiff , $ diffID , $ username , $ test ) <nl> + ) ; <nl> + } <nl> + <nl> + / / We cannot submit the parallel execution master plan to Sandcastle and <nl> + / / need supply the job plan as a determinator . So we construct a small job <nl> + / / that will spit out the master job plan which Sandcastle will parse and <nl> + / / execute . Why compress the job definitions ? Otherwise we run over the max <nl> + / / string size . <nl> + $ cmd = " echo " . base64_encode ( json_encode ( $ arg ) ) <nl> + . " | gzip - f | base64 - w0 " ; <nl> + assert ( strlen ( $ cmd ) > 0 ) ; <nl> + <nl> + $ arg_encoded = shell_exec ( $ cmd ) ; <nl> + assert ( strlen ( $ arg_encoded ) > 0 ) ; <nl> + <nl> + $ runName = " Run diff " . $ diffID . " for user " . $ username ; <nl> + <nl> + if ( ! $ applyDiff ) { <nl> + $ runName = " RocksDB continuous integration build and test run " ; <nl> + } <nl> + <nl> + $ command = array ( <nl> + " name " = > $ runName , <nl> + " steps " = > array ( ) <nl> + ) ; <nl> + <nl> + $ command [ " steps " ] [ ] = array ( <nl> + " name " = > " Generate determinator " , <nl> + " shell " = > " echo " . $ arg_encoded . " | base64 - - decode | gzip - d " <nl> + . " | base64 - - decode " , <nl> + " determinator " = > true , <nl> + " user " = > " root " <nl> + ) ; <nl> + <nl> + / / Submit to Sandcastle . <nl> + $ url = ' https : / / interngraph . intern . facebook . com / sandcastle / generate ? ' <nl> + . ' command = SandcastleUniversalCommand ' <nl> + . ' & vcs = rocksdb - git & revision = origin % 2Fmaster & type = lego ' <nl> + . ' & user = ' . $ username . ' & alias = rocksdb - precommit ' <nl> + . ' & command - args = ' . urlencode ( json_encode ( $ command ) ) ; <nl> + <nl> + / / Fetch the configuration necessary to submit a successful HTTPS request . <nl> + $ sandcastle_config = getSandcastleConfig ( ) ; <nl> + <nl> + $ app = $ sandcastle_config [ 0 ] ; <nl> + $ token = $ sandcastle_config [ 1 ] ; <nl> + <nl> + $ cmd = ' https_proxy = HTTPS_PROXY = curl - s - k - F app = ' . $ app . ' ' <nl> + . ' - F token = ' . $ token . ' " ' . $ url . ' " ' ; <nl> + <nl> + $ output = shell_exec ( $ cmd ) ; <nl> + assert ( strlen ( $ output ) > 0 ) ; <nl> + <nl> + / / Extract Sandcastle URL from the response . <nl> + preg_match ( ' / url " : " ( . + ) " / ' , $ output , $ sandcastle_url ) ; <nl> + <nl> + assert ( count ( $ sandcastle_url ) > 0 , " Unable to submit Sandcastle request . " ) ; <nl> + assert ( strlen ( $ sandcastle_url [ 1 ] ) > 0 , " Unable to extract Sandcastle URL . " ) ; <nl> + <nl> + if ( $ applyDiff ) { <nl> + echo " \ nSandcastle URL : " . $ sandcastle_url [ 1 ] . " \ n " ; <nl> + / / Ask Phabricator to display it on the diff UI . <nl> + postURL ( $ diffID , $ sandcastle_url [ 1 ] ) ; <nl> + } else { <nl> + echo " Continuous integration started Sandcastle tests . You can look at " ; <nl> + echo " the progress at : \ n " . $ sandcastle_url [ 1 ] . " \ n " ; <nl> + } <nl> + } <nl> + <nl> + / / Continuous run cript will set the environment variable and based on that <nl> + / / we ' ll trigger the execution of tests in Sandcastle . In that case we don ' t <nl> + / / need to apply any diffs and there ' s no associated workflow either . <nl> + if ( getenv ( ENV_POST_RECEIVE_HOOK ) ) { <nl> + startTestsInSandcastle ( <nl> + false / * $ applyDiff * / , <nl> + NULL / * $ workflow * / , <nl> + NULL / * $ diffID * / ) ; <nl> + } <nl> new file mode 100755 <nl> index 0000000000 . . 390f30c7ee <nl> mmm / dev / null <nl> ppp b / build_tools / cont_integration . sh <nl> <nl> + # ! / bin / bash <nl> + # <nl> + # Copyright ( c ) 2016 , Facebook . All rights reserved . <nl> + # <nl> + # Overall wrapper script for RocksDB continuous builds . The implementation is a <nl> + # trivial pulling scheme . We loop infinitely , check if any new changes have been <nl> + # committed , if yes then trigger a Sandcastle run , and finally go to sleep again <nl> + # for a certain interval . <nl> + # <nl> + <nl> + function log { <nl> + DATE = ` date + % Y - % m - % d : % H : % M : % S ` <nl> + echo $ DATE $ @ <nl> + } <nl> + <nl> + function log_err { <nl> + log " ERROR : $ @ . Error code : $ ? . " <nl> + } <nl> + <nl> + # <nl> + # Execution starts here . <nl> + # <nl> + <nl> + # Path to the determinator from the root of the RocksDB repo . <nl> + CONTRUN_DETERMINATOR = . / arcanist_util / config / RocksDBCommonDeterminator . php <nl> + <nl> + # Value of the previous commit . <nl> + PREV_COMMIT = <nl> + <nl> + log " Starting to monitor for new RocksDB changes . . . " <nl> + log " Running under ` pwd ` as ` whoami ` . " <nl> + <nl> + # Paranoia . Make sure that we ' re using the right branch . <nl> + git checkout master <nl> + <nl> + if [ ! $ ? - eq 0 ] ; then <nl> + log_err " This is not good . Can ' t checkout master . Bye - bye ! " <nl> + exit 1 <nl> + fi <nl> + <nl> + # We ' ll run forever and let the execution environment terminate us if we ' ll <nl> + # exceed whatever timeout is set for the job . <nl> + while true ; <nl> + do <nl> + # Get the latest changes committed . <nl> + git pull - - rebase <nl> + <nl> + if [ $ ? - eq 0 ] ; then <nl> + LAST_COMMIT = ` git log - 1 | head - 1 | grep commit | awk ' { print $ 2 ; } ' ` <nl> + <nl> + log " Last commit is ' $ LAST_COMMIT ' , previous commit is ' $ PREV_COMMIT ' . " <nl> + <nl> + if [ " $ PREV_COMMIT " = = " $ LAST_COMMIT " ] ; then <nl> + log " There were no changes since the last time I checked . Going to sleep . " <nl> + else <nl> + if [ ! - z " $ LAST_COMMIT " ] ; then <nl> + log " New code has been committed or previous commit not know . " \ <nl> + " Will trigger the tests . " <nl> + <nl> + PREV_COMMIT = $ LAST_COMMIT <nl> + log " Updated previous commit to ' $ PREV_COMMIT ' . " <nl> + <nl> + # <nl> + # This is where we ' ll trigger the Sandcastle run . The values for <nl> + # HTTPS_APP_VALUE and HTTPS_APP_VALUE will be set in the container we ' re <nl> + # running in . <nl> + # <nl> + POST_RECEIVE_HOOK = 1 php $ CONTRUN_DETERMINATOR <nl> + <nl> + if [ $ ? - eq 0 ] ; then <nl> + log " Sandcastle run successfully triggered . " <nl> + else <nl> + log_err " Failed to trigger Sandcastle run . " <nl> + fi <nl> + else <nl> + log_err " Previous commit not updated . Don ' t know what the last one is . " <nl> + fi <nl> + fi <nl> + else <nl> + log_err " git pull - - rebase failed . Will skip running tests for now . " <nl> + fi <nl> + <nl> + # Always sleep , even if errors happens while trying to determine the latest <nl> + # commit . This will prevent us terminating in case of transient errors . <nl> + log " Will go to sleep for 5 minutes . " <nl> + sleep 5m <nl> + done <nl>
Framework for enabling continuous RocksDB build and tests
facebook/rocksdb
a52e4d7d0252d712f4c1c072e60c01996630e18b
2016-06-21T18:38:54Z
mmm a / hphp / runtime / ext_hhvm / CMakeLists . txt <nl> ppp b / hphp / runtime / ext_hhvm / CMakeLists . txt <nl> set ( CXX_SOURCES ) <nl> set ( C_SOURCES ) <nl> set ( CXX_HEADERS ) <nl> set ( EXT_HHVM_ARCH " x64 " ) <nl> + set ( EXT_HHVM_OS " linux " ) <nl> <nl> exec_program ( " uname - m " OUTPUT_VARIABLE UNAME_M ) <nl> if ( UNAME_M STREQUAL " aarch64 " ) <nl> set ( EXT_HHVM_ARCH " arm " ) <nl> endif ( ) <nl> <nl> - macro ( EXT_HHVM_FILE SOURCES HEADERS REL EHHVM_ARCH ) <nl> + if ( APPLE ) <nl> + set ( EXT_HHVM_OS " darwin " ) <nl> + endif ( ) <nl> + <nl> + macro ( EXT_HHVM_FILE SOURCES HEADERS REL EHHVM_OS EHHVM_ARCH ) <nl> set ( f_SRC " $ { HPHP_HOME } / hphp / $ { REL } " ) <nl> set ( f_OBJ " $ { HPHP_HOME } / hphp / CMakeFiles / hphp_runtime_static . dir / $ { REL } . o " ) <nl> list ( APPEND $ { SOURCES } " $ { f_SRC } . ext_hhvm . cpp " ) <nl> macro ( EXT_HHVM_FILE SOURCES HEADERS REL EHHVM_ARCH ) <nl> add_custom_command ( OUTPUT " $ { f_SRC } . ext_hhvm . cpp " " $ { f_SRC } . ext_hhvm . h " <nl> DEPENDS $ { f_SRC } gen - ext - hhvm <nl> COMMAND " $ { HPHP_HOME } / hphp / tools / bootstrap / gen - ext - hhvm . sh " <nl> - ARGS $ { EHHVM_ARCH } $ { f_OBJ } <nl> + ARGS $ { EHHVM_OS } $ { EHHVM_ARCH } $ { f_OBJ } <nl> " $ { f_SRC } . ext_hhvm . cpp " " $ { f_SRC } . ext_hhvm . h " <nl> WORKING_DIRECTORY " $ { HPHP_HOME } / hphp / tools / bootstrap " <nl> COMMENT " Generating ext_hhvm wrapper for $ { REL } " ) <nl> foreach ( f $ { files } ) <nl> string ( LENGTH $ { f } f_LEN ) <nl> math ( EXPR f_REL_LEN " $ { f_LEN } - $ { HPHP_DIR_LEN } " ) <nl> string ( SUBSTRING $ { f } $ { HPHP_DIR_LEN } $ { f_REL_LEN } f_REL ) <nl> - EXT_HHVM_FILE ( CXX_SOURCES CXX_HEADERS $ { f_REL } $ { EXT_HHVM_ARCH } ) <nl> + EXT_HHVM_FILE ( CXX_SOURCES CXX_HEADERS $ { f_REL } $ { EXT_HHVM_OS } $ { EXT_HHVM_ARCH } ) <nl> endif ( ) <nl> endforeach ( ) <nl> - EXT_HHVM_FILE ( CXX_SOURCES CXX_HEADERS " runtime / base / builtin_functions . cpp " $ { EXT_HHVM_ARCH } ) <nl> + EXT_HHVM_FILE ( CXX_SOURCES CXX_HEADERS " runtime / base / builtin_functions . cpp " $ { EXT_HHVM_OS } $ { EXT_HHVM_ARCH } ) <nl> <nl> foreach ( dir $ { RECURSIVE_SOURCE_SUBDIRS } ) <nl> auto_sources ( files " * . cpp " " RECURSE " " $ { CMAKE_CURRENT_SOURCE_DIR } " ) <nl> mmm a / hphp / tools / bootstrap / gen - ext - hhvm . sh <nl> ppp b / hphp / tools / bootstrap / gen - ext - hhvm . sh <nl> <nl> # ! / bin / sh <nl> <nl> - # $ 1 Machine architecture ( currently : " x64 " or " arm " ) <nl> - # $ 2 Object file to read symbols from <nl> - # $ 3 ext_hhvm . cpp source to generate <nl> - # $ 4 ext_hhvm . h header to generate <nl> - if [ " $ OSTYPE " = " darwin " * ] ; then <nl> - gobjdump - - section = " . text " - - section = " LC_SEGMENT . . text . hot . built . " - t $ 2 | \ <nl> + # $ 1 Operating System ( currently : " linux " or " darwin " ) <nl> + # $ 2 Machine architecture ( currently : " x64 " or " arm " ) <nl> + # $ 3 Object file to read symbols from <nl> + # $ 4 ext_hhvm . cpp source to generate <nl> + # $ 5 ext_hhvm . h header to generate <nl> + if [ " $ 1 " = " darwin " ] ; then <nl> + gobjdump - - section = " . text " - - section = " LC_SEGMENT . . text . hot . built . " - t $ 3 | \ <nl> awk ' { if ( $ 2 = = " g " ) print $ 8 } ' | \ <nl> $ HPHP_HOME / hphp / tools / bootstrap / gen - ext - hhvm \ <nl> - $ 1 $ 4 $ 3 $ HPHP_HOME / hphp / system / idl / * . idl . json <nl> + $ 2 $ 5 $ 4 $ HPHP_HOME / hphp / system / idl / * . idl . json <nl> else <nl> - readelf - s - W $ 2 | grep ' FUNC . * GLOBAL ' | \ <nl> + readelf - s - W $ 3 | grep ' FUNC . * GLOBAL ' | \ <nl> sed - e ' s / ^ . * DEFAULT [ 0 - 9 ] * / / ' | \ <nl> $ HPHP_HOME / hphp / tools / bootstrap / gen - ext - hhvm \ <nl> - $ 1 $ 4 $ 3 $ HPHP_HOME / hphp / system / idl / * . idl . json <nl> + $ 2 $ 5 $ 4 $ HPHP_HOME / hphp / system / idl / * . idl . json <nl> fi <nl>
Pass OS determination from CMake into gen - ext - hhvm . sh
facebook/hhvm
f9da9970d2e6b9a3407d2eaca87f7e400ac85bea
2013-07-11T03:25:50Z
mmm a / Docker / docker - compose - dawn3 . 0 . yaml <nl> ppp b / Docker / docker - compose - dawn3 . 0 . yaml <nl> version : " 3 " <nl> <nl> services : <nl> nodeosd : <nl> - image : eosio / eos : dawn3x <nl> + image : eosio / eos : latest <nl> command : / opt / eosio / bin / nodeosd . sh - - data - dir / opt / eosio / bin / data - dir <nl> hostname : nodeosd <nl> ports : <nl> services : <nl> - nodeos - data - volume : / opt / eosio / bin / data - dir <nl> <nl> keosd : <nl> - image : eosio / eos : dawn3x <nl> + image : eosio / eos : latest <nl> command : / opt / eosio / bin / keosd - - wallet - dir / opt / eosio / bin / data - dir <nl> hostname : keosd <nl> links : <nl>
change dawn3x to latest to support mongodb plugin
EOSIO/eos
10cd2663de9bd4fd8d6181e6979383ff93999d83
2018-04-21T09:39:00Z
mmm a / Code / CryEngine / CryAction / Network / GameContext . cpp <nl> ppp b / Code / CryEngine / CryAction / Network / GameContext . cpp <nl> void CGameContext : : OnSpawn ( IEntity * pEntity , SEntitySpawnParams & params ) <nl> bool calledBindToNetwork = false ; <nl> if ( m_isInLevelLoad & & gEnv - > bMultiplayer ) <nl> { <nl> - if ( ! pEntity - > GetProxy ( ENTITY_PROXY_USER ) ) <nl> + if ( pEntity - > GetScriptTable ( ) ) <nl> { <nl> - if ( pEntity - > GetScriptTable ( ) ) <nl> - { <nl> - IGameObject * pGO = CCryAction : : GetCryAction ( ) - > GetIGameObjectSystem ( ) - > CreateGameObjectForEntity ( pEntity - > GetId ( ) ) ; <nl> - if ( pGO ) <nl> - { <nl> - / / CryLog ( " Forcibly binding % s to network " , params . sName ) ; <nl> - calledBindToNetwork = true ; <nl> - pGO - > BindToNetwork ( ) ; <nl> - } <nl> - } <nl> + / / CryLog ( " Forcibly binding % s to network " , params . sName ) ; <nl> + calledBindToNetwork = true ; <nl> + pEntity - > GetNetEntity ( ) - > BindToNetwork ( ) ; <nl> } <nl> } <nl> <nl> if ( ! calledBindToNetwork ) <nl> { <nl> - if ( CGameObject * pGO = ( CGameObject * ) pEntity - > GetProxy ( ENTITY_PROXY_USER ) ) <nl> - pGO - > BindToNetwork ( eBTNM_NowInitialized ) ; <nl> + pEntity - > GetNetEntity ( ) - > BindToNetwork ( eBTNM_NowInitialized ) ; <nl> } <nl> <nl> CallOnSpawnComplete ( pEntity ) ; <nl>
! B ( CryAction ) Fix inability to send bind entities to the network unless they contained a legacy game object
CRYTEK/CRYENGINE
bbd2eb455847c0fae336788ff235decb33e68fdf
2017-12-21T11:52:57Z
mmm a / templates / cocos2dx_files . json <nl> ppp b / templates / cocos2dx_files . json <nl> <nl> " cocos / ui / UIWidget . h " , <nl> " cocos / ui / proj . win32 / libui . vcxproj " , <nl> " cocos / ui / proj . win32 / libui . vcxproj . filters " , <nl> + " cocos / ui / shaders / UIShaders . cpp " , <nl> + " cocos / ui / shaders / UIShaders . h " , <nl> + " cocos / ui / shaders / ccShader_grayscale . frag " , <nl> " docs / CODING_STYLE . md " , <nl> " docs / CONTRIBUTE . md " , <nl> " docs / Groups . h " , <nl> <nl> " cocos / scripting / lua - bindings / auto / api / ActionTimeline . lua " , <nl> " cocos / scripting / lua - bindings / auto / api / ActionTimelineCache . lua " , <nl> " cocos / scripting / lua - bindings / auto / api / ActionTimelineData . lua " , <nl> + " cocos / scripting / lua - bindings / auto / api / ActionTimelineNode . lua " , <nl> " cocos / scripting / lua - bindings / auto / api / ActionTintFrame . lua " , <nl> " cocos / scripting / lua - bindings / auto / api / ActionTween . lua " , <nl> " cocos / scripting / lua - bindings / auto / api / AmbientLight . lua " , <nl>
[ AUTO ] [ ci skip ] : updating cocos2dx_files . json
cocos2d/cocos2d-x
a8fedda82ce9370d55a0c8fc0c7f0ae2657affe2
2014-12-26T01:29:15Z
deleted file mode 100644 <nl> index 1326800820 . . 0000000000 <nl> mmm a / vnpy / api / tap / vntap / include / boost / callable_traits / remove_member_const . hpp <nl> ppp / dev / null <nl> <nl> - / * <nl> - <nl> - @ Copyright Barrett Adair 2015 - 2017 <nl> - Distributed under the Boost Software License , Version 1 . 0 . <nl> - ( See accompanying file LICENSE . md or copy at http : / / boost . org / LICENSE_1_0 . txt ) <nl> - <nl> - * / <nl> - <nl> - # ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP <nl> - # define BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP <nl> - <nl> - # include < boost / callable_traits / detail / core . hpp > <nl> - <nl> - namespace boost { namespace callable_traits { <nl> - <nl> - / / [ remove_member_const_hpp <nl> - / * ` <nl> - [ section : ref_remove_member_const remove_member_const ] <nl> - [ heading Header ] <nl> - ` ` # include < boost / callable_traits / remove_member_const . hpp > ` ` <nl> - [ heading Definition ] <nl> - * / <nl> - <nl> - template < typename T > <nl> - using remove_member_const_t = / / see below <nl> - / / < - <nl> - detail : : try_but_fail_if_invalid < <nl> - typename detail : : traits < T > : : remove_member_const , <nl> - member_qualifiers_are_illegal_for_this_type > ; <nl> - <nl> - namespace detail { <nl> - <nl> - template < typename T , typename = std : : false_type > <nl> - struct remove_member_const_impl { } ; <nl> - <nl> - template < typename T > <nl> - struct remove_member_const_impl < T , typename std : : is_same < <nl> - remove_member_const_t < T > , detail : : dummy > : : type > <nl> - { <nl> - using type = remove_member_const_t < T > ; <nl> - } ; <nl> - } <nl> - <nl> - / / - > <nl> - <nl> - template < typename T > <nl> - struct remove_member_const : detail : : remove_member_const_impl < T > { } ; <nl> - <nl> - / / < - <nl> - } } / / namespace boost : : callable_traits <nl> - / / - > <nl> - <nl> - / * ` <nl> - [ heading Constraints ] <nl> - * ` T ` must be a function type or a member function pointer type <nl> - * If ` T ` is a pointer , it may not be cv / ref qualified <nl> - <nl> - [ heading Behavior ] <nl> - * A substitution failure occurs if the constraints are violated . <nl> - * Removes the member ` const ` qualifier from ` T ` , if present . <nl> - <nl> - [ heading Input / Output Examples ] <nl> - [ table <nl> - [ [ ` T ` ] [ ` remove_member_const_t < T > ` ] ] <nl> - [ [ ` int ( ) const ` ] [ ` int ( ) ` ] ] <nl> - [ [ ` int ( foo : : * ) ( ) const ` ] [ ` int ( foo : : * ) ( ) ` ] ] <nl> - [ [ ` int ( foo : : * ) ( ) const & ` ] [ ` int ( foo : : * ) ( ) & ` ] ] <nl> - [ [ ` int ( foo : : * ) ( ) const & & ` ] [ ` int ( foo : : * ) ( ) & & ` ] ] <nl> - [ [ ` int ( foo : : * ) ( ) const ` ] [ ` int ( foo : : * ) ( ) ` ] ] <nl> - [ [ ` int ( foo : : * ) ( ) const volatile ` ] [ ` int ( foo : : * ) ( ) volatile ` ] ] <nl> - [ [ ` int ` ] [ ( substitution failure ) ] ] <nl> - [ [ ` int ( & ) ( ) ` ] [ ( substitution failure ) ] ] <nl> - [ [ ` int ( * ) ( ) ` ] [ ( substitution failure ) ] ] <nl> - [ [ ` int foo : : * ` ] [ ( substitution failure ) ] ] <nl> - [ [ ` int ( foo : : * const ) ( ) ` ] [ ( substitution failure ) ] ] <nl> - ] <nl> - <nl> - [ heading Example Program ] <nl> - [ import . . / example / remove_member_const . cpp ] <nl> - [ remove_member_const ] <nl> - [ endsect ] <nl> - * / <nl> - / / ] <nl> - <nl> - # endif / / # ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP <nl>
Delete remove_member_const . hpp
vnpy/vnpy
5c38e5b5f157245f1fea125e65933b6bf44ccf8f
2020-03-06T06:51:19Z
mmm a / libraries / chain / wasm_interface . cpp <nl> ppp b / libraries / chain / wasm_interface . cpp <nl> class privileged_api : public context_aware_api { <nl> } <nl> <nl> EOS_ASSERT ( a . keys . size ( ) = = unique_keys . size ( ) , wasm_execution_error , " producer schedule includes a duplicated key for $ { account } " , ( " account " , p . producer_name ) ) ; <nl> + EOS_ASSERT ( a . threshold > 0 , wasm_execution_error , " producer schedule includes an authority with a threshold of 0 for $ { account } " , ( " account " , p . producer_name ) ) ; <nl> EOS_ASSERT ( sum_weights > = a . threshold , wasm_execution_error , " producer schedule includes an unsatisfiable authority for $ { account } " , ( " account " , p . producer_name ) ) ; <nl> } ) ; <nl> <nl> mmm a / libraries / eos - vm <nl> ppp b / libraries / eos - vm <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit c35303702fcfadb7104627f34fd64ee3ad039a96 <nl> + Subproject commit 3abb9ed766910df2d407d02686dfe6c32345e77f <nl> mmm a / plugins / net_plugin / net_plugin . cpp <nl> ppp b / plugins / net_plugin / net_plugin . cpp <nl> namespace eosio { <nl> self - > connecting = false ; <nl> self - > syncing = false ; <nl> self - > consecutive_rejected_blocks = 0 ; <nl> - self - > trx_in_progress_size = 0 ; <nl> + + self - > consecutive_immediate_connection_close ; <nl> bool has_last_req = false ; <nl> { <nl>
Merge remote - tracking branch ' origin / develop ' into rodeos
EOSIO/eos
ad6d6d2e001b7740214adece5c830a0c90fc1caf
2019-09-27T23:25:33Z
mmm a / tensorflow / core / common_runtime / eager / BUILD <nl> ppp b / tensorflow / core / common_runtime / eager / BUILD <nl> tf_cuda_library ( <nl> " / / tensorflow / core : android_tensorflow_lib_lite " , <nl> ] , <nl> " / / conditions : default " : [ <nl> - " @ com_google_absl / / absl / types : variant " , <nl> + " @ com_google_absl / / absl / types : optional " , <nl> " / / tensorflow / core : core_cpu_lib " , <nl> " / / tensorflow / core : framework " , <nl> " / / tensorflow / core : lib " , <nl> mmm a / tensorflow / core / common_runtime / eager / process_function_library_runtime . cc <nl> ppp b / tensorflow / core / common_runtime / eager / process_function_library_runtime . cc <nl> namespace tensorflow { <nl> namespace eager { <nl> <nl> # if ! defined ( IS_MOBILE_PLATFORM ) <nl> + Status EagerFunctionArgs : : GetLocalArg ( const int index , Tensor * val ) const { <nl> + const absl : : optional < Tensor > & arg = tensor_args_ - > at ( index ) ; <nl> + if ( arg . has_value ( ) ) { <nl> + * val = arg . value ( ) ; <nl> + return Status : : OK ( ) ; <nl> + } else { <nl> + return errors : : NotFound ( " Argument " , index , " has no local tensor . " ) ; <nl> + } <nl> + } <nl> + <nl> + Status EagerFunctionArgs : : GetRemoteArg ( const int index , <nl> + RemoteTensorHandle * val ) const { <nl> + return serialize_remote_handle_ ( index , val ) ; <nl> + } <nl> + <nl> void EagerProcessFunctionLibraryRuntime : : RunRemoteDevice ( <nl> const FunctionLibraryRuntime : : Options & opts , <nl> FunctionLibraryRuntime : : Handle local_handle , const InternalArgsView & args , <nl> void EagerProcessFunctionLibraryRuntime : : RunRemoteDevice ( <nl> " EagerClusterFunctionLibraryRuntime . " ) ) ; <nl> return ; <nl> } <nl> + if ( args . remote_args = = nullptr ) { <nl> + done ( <nl> + errors : : Internal ( " EagerClusterFunctionLibraryRuntime : remote_args " <nl> + " should never be null . " ) ) ; <nl> + return ; <nl> + } <nl> parent_ - > Run ( opts , local_handle , args . remote_args , std : : move ( done ) ) ; <nl> } <nl> <nl> void EagerProcessFunctionLibraryRuntime : : Run ( <nl> const FunctionLibraryRuntime : : Options & opts , <nl> - FunctionLibraryRuntime : : Handle handle , <nl> - const std : : vector < VariantFunctionArg > & args , std : : vector < Tensor > * rets , <nl> + FunctionLibraryRuntime : : Handle handle , const FunctionArgsInterface & args , <nl> + std : : vector < Tensor > * rets , <nl> FunctionLibraryRuntime : : DoneCallback done ) const { <nl> auto * cleanup_items = new std : : vector < std : : unique_ptr < CleanUpItem > > ; <nl> done = ApplyCleanUpToDoneCallback ( cleanup_items , done ) ; <nl> <nl> - auto get_component_args = <nl> - [ & args ] ( const ComponentFunctionData & comp_data ) - > InternalArgs { <nl> - InternalArgs comp_args ; <nl> + auto get_component_args = [ & args ] ( const ComponentFunctionData & comp_data , <nl> + InternalArgs * comp_args ) - > Status { <nl> for ( int i = 0 ; i < comp_data . arg_indices_ . size ( ) ; + + i ) { <nl> - int index = comp_data . arg_indices_ . at ( i ) ; <nl> - if ( absl : : holds_alternative < Tensor > ( args . at ( index ) ) ) { <nl> - comp_args . local_args . push_back ( absl : : get < Tensor > ( args [ i ] ) ) ; <nl> + const int index = comp_data . arg_indices_ . at ( i ) ; <nl> + Tensor tensor ; <nl> + if ( args . GetLocalArg ( index , & tensor ) . ok ( ) ) { <nl> + comp_args - > local_args . push_back ( std : : move ( tensor ) ) ; <nl> } else { <nl> - comp_args . remote_args . push_back ( <nl> - absl : : get < RemoteTensorHandle * > ( args [ i ] ) ) ; <nl> + RemoteTensorHandle remote_handle ; <nl> + TF_RETURN_IF_ERROR ( args . GetRemoteArg ( index , & remote_handle ) ) ; <nl> + comp_args - > remote_args . push_back ( std : : move ( remote_handle ) ) ; <nl> } <nl> } <nl> - return comp_args ; <nl> + return Status : : OK ( ) ; <nl> } ; <nl> return RunMultiDevice ( opts , handle , rets , cleanup_items , std : : move ( done ) , <nl> std : : move ( get_component_args ) ) ; <nl> mmm a / tensorflow / core / common_runtime / eager / process_function_library_runtime . h <nl> ppp b / tensorflow / core / common_runtime / eager / process_function_library_runtime . h <nl> limitations under the License . <nl> # include " tensorflow / core / platform / platform . h " <nl> / / clang - format on <nl> <nl> - # include " absl / types / variant . h " <nl> # include " tensorflow / core / common_runtime / device_mgr . h " <nl> # include " tensorflow / core / common_runtime / process_function_library_runtime . h " <nl> # include " tensorflow / core / lib / gtl / array_slice . h " <nl> namespace tensorflow { <nl> namespace eager { <nl> <nl> # if ! defined ( IS_MOBILE_PLATFORM ) <nl> - using VariantFunctionArg = absl : : variant < Tensor , eager : : RemoteTensorHandle * > ; <nl> + class EagerFunctionArgs : public FunctionArgsInterface { <nl> + public : <nl> + EagerFunctionArgs ( const std : : vector < absl : : optional < Tensor > > * tensor_args , <nl> + std : : function < Status ( const int , RemoteTensorHandle * ) > <nl> + serialize_remote_handle ) <nl> + : tensor_args_ ( tensor_args ) , <nl> + serialize_remote_handle_ ( std : : move ( serialize_remote_handle ) ) { } <nl> + <nl> + ~ EagerFunctionArgs ( ) override { } ; <nl> + <nl> + Status GetLocalArg ( const int index , Tensor * val ) const override ; <nl> + <nl> + Status GetRemoteArg ( const int index , <nl> + eager : : RemoteTensorHandle * val ) const override ; <nl> + <nl> + private : <nl> + const std : : vector < absl : : optional < Tensor > > * tensor_args_ ; <nl> + std : : function < Status ( const int , eager : : RemoteTensorHandle * ) > <nl> + serialize_remote_handle_ ; <nl> + } ; <nl> # endif / / IS_MOBILE_PLATFORM <nl> <nl> / / A ProcessFunctionLibraryRuntime which supports running functions with inputs <nl> class EagerProcessFunctionLibraryRuntime <nl> # if ! defined ( IS_MOBILE_PLATFORM ) <nl> void Run ( const FunctionLibraryRuntime : : Options & opts , <nl> FunctionLibraryRuntime : : Handle handle , <nl> - const std : : vector < VariantFunctionArg > & args , <nl> - std : : vector < Tensor > * rets , <nl> - FunctionLibraryRuntime : : DoneCallback done ) const ; <nl> + const FunctionArgsInterface & args , std : : vector < Tensor > * rets , <nl> + FunctionLibraryRuntime : : DoneCallback done ) const override ; <nl> <nl> private : <nl> void RunRemoteDevice ( <nl> mmm a / tensorflow / core / common_runtime / process_function_library_runtime . cc <nl> ppp b / tensorflow / core / common_runtime / process_function_library_runtime . cc <nl> void ProcessFunctionLibraryRuntime : : RunMultiDevice ( <nl> FunctionLibraryRuntime : : Handle handle , std : : vector < Tensor > * rets , <nl> std : : vector < std : : unique_ptr < CleanUpItem > > * cleanup_items , <nl> FunctionLibraryRuntime : : DoneCallback done , <nl> - std : : function < InternalArgs ( const ComponentFunctionData & comp_data ) > <nl> + std : : function < Status ( const ComponentFunctionData & comp_data , <nl> + InternalArgs * args ) > <nl> get_component_args ) const { <nl> if ( opts . create_rendezvous ) { <nl> / / FLR - > Run ( ) is the default entry point . It checks for cancellation , <nl> void ProcessFunctionLibraryRuntime : : RunMultiDevice ( <nl> opts_copy . rets_alloc_attrs = comp_data . ret_alloc_attrs_ ; <nl> opts_copy . remote_execution = false ; <nl> <nl> - InternalArgs comp_args = get_component_args ( comp_data ) ; <nl> + InternalArgs comp_args ; <nl> + Status s = get_component_args ( comp_data , & comp_args ) ; <nl> + if ( ! s . ok ( ) ) { <nl> + VLOG ( 2 ) < < " Failed to get component function arguments : " < < s ; <nl> + refcounted_done - > UpdateStatus ( s ) ; <nl> + refcounted_done - > Unref ( ) ; <nl> + continue ; <nl> + } <nl> std : : vector < Tensor > * comp_rets = new std : : vector < Tensor > ; <nl> rets - > resize ( data - > num_outputs_ ) ; <nl> <nl> void ProcessFunctionLibraryRuntime : : RunMultiDevice ( <nl> VLOG ( 1 ) < < " Running component function on device " < < target <nl> < < " with handle " < < handle ; <nl> VLOG ( 4 ) < < " with " < < opts_copy . DebugString ( ) ; <nl> - InternalArgsView comp_args_view ( comp_args ) ; <nl> + InternalArgsView comp_args_view ( & comp_args ) ; <nl> RunInternal ( <nl> opts_copy , handle , comp_args_view , comp_rets , cleanup_items , <nl> [ comp_rets , rets , comp_data , refcounted_done ] ( const Status & status ) { <nl> void ProcessFunctionLibraryRuntime : : Run ( <nl> multi_device = mdevice_data_ . find ( handle ) ! = mdevice_data_ . end ( ) ; <nl> } <nl> if ( multi_device ) { <nl> - auto get_component_args = <nl> - [ & args ] ( const ComponentFunctionData & comp_data ) - > InternalArgs { <nl> - InternalArgs comp_args ; <nl> - comp_args . local_args = GetArgsForIndices ( comp_data . arg_indices_ , args ) ; <nl> - return comp_args ; <nl> + auto get_component_args = [ & args ] ( const ComponentFunctionData & comp_data , <nl> + InternalArgs * comp_args ) - > Status { <nl> + comp_args - > local_args = GetArgsForIndices ( comp_data . arg_indices_ , args ) ; <nl> + return Status : : OK ( ) ; <nl> } ; <nl> return RunMultiDevice ( opts , handle , rets , cleanup_items , std : : move ( done ) , <nl> std : : move ( get_component_args ) ) ; <nl> mmm a / tensorflow / core / common_runtime / process_function_library_runtime . h <nl> ppp b / tensorflow / core / common_runtime / process_function_library_runtime . h <nl> limitations under the License . <nl> <nl> namespace tensorflow { <nl> <nl> + class FunctionArgsInterface { <nl> + public : <nl> + virtual ~ FunctionArgsInterface ( ) { } <nl> + <nl> + virtual Status GetLocalArg ( const int index , Tensor * val ) const = 0 ; <nl> + <nl> + # if ! defined ( IS_MOBILE_PLATFORM ) <nl> + virtual Status GetRemoteArg ( const int index , <nl> + eager : : RemoteTensorHandle * val ) const = 0 ; <nl> + # endif / / IS_MOBILE_PLATFORM <nl> + } ; <nl> + <nl> / / A class that stores all the FunctionLibraryRuntime objects , one per device . <nl> class ProcessFunctionLibraryRuntime { <nl> public : <nl> class ProcessFunctionLibraryRuntime { <nl> FunctionLibraryRuntime : : Handle handle , CallFrameInterface * frame , <nl> FunctionLibraryRuntime : : DoneCallback done ) const ; <nl> <nl> + virtual void Run ( const FunctionLibraryRuntime : : Options & opts , <nl> + FunctionLibraryRuntime : : Handle handle , <nl> + const FunctionArgsInterface & args , std : : vector < Tensor > * rets , <nl> + FunctionLibraryRuntime : : DoneCallback done ) const { <nl> + done ( errors : : Unimplemented ( " Unimplemented . " ) ) ; <nl> + } <nl> + <nl> const DeviceMgr * device_mgr ( ) { return device_mgr_ ; } <nl> <nl> const DeviceSet * device_set ( ) { return & device_set_ ; } <nl> class ProcessFunctionLibraryRuntime { <nl> struct InternalArgs { <nl> std : : vector < Tensor > local_args ; <nl> # if ! defined ( IS_MOBILE_PLATFORM ) <nl> - std : : vector < eager : : RemoteTensorHandle * > remote_args ; <nl> + std : : vector < eager : : RemoteTensorHandle > remote_args ; <nl> # endif / / IS_MOBILE_PLATFORM <nl> } ; <nl> <nl> class ProcessFunctionLibraryRuntime { <nl> explicit InternalArgsView ( gtl : : ArraySlice < Tensor > tensors ) <nl> : local_args ( tensors ) { } <nl> <nl> - explicit InternalArgsView ( const InternalArgs & args ) <nl> - : local_args ( args . local_args ) { <nl> + explicit InternalArgsView ( InternalArgs * args ) <nl> + : local_args ( args - > local_args ) { <nl> # if ! defined ( IS_MOBILE_PLATFORM ) <nl> - remote_args = args . remote_args ; <nl> + remote_args = & args - > remote_args ; <nl> # endif / / IS_MOBILE_PLATFORM <nl> } <nl> <nl> gtl : : ArraySlice < Tensor > local_args ; <nl> # if ! defined ( IS_MOBILE_PLATFORM ) <nl> - absl : : Span < eager : : RemoteTensorHandle * const > remote_args ; <nl> + std : : vector < eager : : RemoteTensorHandle > * remote_args = nullptr ; <nl> # endif / / IS_MOBILE_PLATFORM <nl> } ; <nl> <nl> class ProcessFunctionLibraryRuntime { <nl> FunctionLibraryRuntime : : Handle handle , std : : vector < Tensor > * rets , <nl> std : : vector < std : : unique_ptr < CleanUpItem > > * cleanup_items , <nl> FunctionLibraryRuntime : : DoneCallback done , <nl> - std : : function < InternalArgs ( const ComponentFunctionData & comp_data ) > <nl> + std : : function < Status ( const ComponentFunctionData & comp_data , <nl> + InternalArgs * args ) > <nl> get_component_args ) const ; <nl> <nl> FunctionLibraryRuntime : : DoneCallback ApplyCleanUpToDoneCallback ( <nl> mmm a / tensorflow / core / distributed_runtime / eager / BUILD <nl> ppp b / tensorflow / core / distributed_runtime / eager / BUILD <nl> tf_cc_test ( <nl> " / / tensorflow / core / distributed_runtime : test_utils " , <nl> " / / tensorflow / core / distributed_runtime : worker_env " , <nl> " / / tensorflow / core / distributed_runtime / rpc : rpc_rendezvous_mgr " , <nl> - " @ com_google_absl / / absl / types : span " , <nl> + " @ com_google_absl / / absl / types : optional " , <nl> ] , <nl> ) <nl> <nl> mmm a / tensorflow / core / distributed_runtime / eager / cluster_function_library_runtime . cc <nl> ppp b / tensorflow / core / distributed_runtime / eager / cluster_function_library_runtime . cc <nl> void EagerClusterFunctionLibraryRuntime : : Run ( <nl> void EagerClusterFunctionLibraryRuntime : : Run ( <nl> const FunctionLibraryRuntime : : Options & opts , <nl> FunctionLibraryRuntime : : LocalHandle handle , <nl> - absl : : Span < eager : : RemoteTensorHandle * const > args , <nl> + std : : vector < eager : : RemoteTensorHandle > * args , <nl> FunctionLibraryRuntime : : DoneCallback done ) { <nl> FunctionData * function_data = nullptr ; <nl> { <nl> void EagerClusterFunctionLibraryRuntime : : Run ( <nl> eager : : EnqueueRequest * request = new eager : : EnqueueRequest ; <nl> request - > set_context_id ( function_data - > context_id ) ; <nl> eager : : Operation * remote_op = request - > add_queue ( ) - > mutable_operation ( ) ; <nl> - for ( size_t i = 0 ; i < args . size ( ) ; + + i ) { <nl> - remote_op - > add_inputs ( ) - > Swap ( args [ i ] ) ; <nl> + for ( size_t i = 0 ; i < args - > size ( ) ; + + i ) { <nl> + remote_op - > add_inputs ( ) - > Swap ( & ( * args ) [ i ] ) ; <nl> } <nl> / / TODO ( yujingzhang ) : add step_id to eager : : Operation to make sure that all <nl> / / component functions use the same step id . <nl> mmm a / tensorflow / core / distributed_runtime / eager / cluster_function_library_runtime . h <nl> ppp b / tensorflow / core / distributed_runtime / eager / cluster_function_library_runtime . h <nl> class EagerClusterFunctionLibraryRuntime <nl> <nl> void Run ( const FunctionLibraryRuntime : : Options & opts , <nl> FunctionLibraryRuntime : : LocalHandle handle , <nl> - absl : : Span < eager : : RemoteTensorHandle * const > args , <nl> + std : : vector < eager : : RemoteTensorHandle > * args , <nl> FunctionLibraryRuntime : : DoneCallback done ) override ; <nl> <nl> void CleanUp ( uint64 step_id , FunctionLibraryRuntime : : LocalHandle handle , <nl> mmm a / tensorflow / core / distributed_runtime / eager / eager_service_impl_test . cc <nl> ppp b / tensorflow / core / distributed_runtime / eager / eager_service_impl_test . cc <nl> limitations under the License . <nl> <nl> # include < string . h > <nl> <nl> - # include " absl / types / span . h " <nl> + # include < memory > <nl> + <nl> + # include " absl / types / optional . h " <nl> # include " tensorflow / c / c_api_internal . h " <nl> # include " tensorflow / core / common_runtime / eager / process_function_library_runtime . h " <nl> # include " tensorflow / core / common_runtime / eager / tensor_handle . h " <nl> TEST_F ( EagerServiceImplTest , EagerPFLRTest ) { <nl> FunctionLibraryDefinition func_lib_def { OpRegistry : : Global ( ) , { } } ; <nl> auto device_mgr = absl : : make_unique < StaticDeviceMgr > ( <nl> DeviceFactory : : NewDevice ( " CPU " , { } , " / job : localhost / replica : 0 / task : 1 " ) ) ; <nl> - auto eager_pflr = absl : : make_unique < EagerProcessFunctionLibraryRuntime > ( <nl> - device_mgr . get ( ) , Env : : Default ( ) , / * config = * / nullptr , <nl> - TF_GRAPH_DEF_VERSION , & func_lib_def , OptimizerOptions ( ) , nullptr , <nl> - eager_cluster_flr . get ( ) , nullptr ) ; <nl> + std : : unique_ptr < ProcessFunctionLibraryRuntime > eager_pflr = <nl> + absl : : make_unique < EagerProcessFunctionLibraryRuntime > ( <nl> + device_mgr . get ( ) , Env : : Default ( ) , / * config = * / nullptr , <nl> + TF_GRAPH_DEF_VERSION , & func_lib_def , OptimizerOptions ( ) , nullptr , <nl> + eager_cluster_flr . get ( ) , nullptr ) ; <nl> <nl> tensorflow : : FunctionDef fdef = MatMulFunction ( ) ; <nl> TF_ASSERT_OK ( func_lib_def . AddFunctionDef ( fdef ) ) ; <nl> TEST_F ( EagerServiceImplTest , EagerPFLRTest ) { <nl> input . set_output_num ( 0 ) ; <nl> input . set_op_device ( local_device ) ; <nl> input . set_device ( local_device ) ; <nl> - VariantFunctionArg arg ( & input ) ; <nl> + std : : vector < RemoteTensorHandle > inputs = { input } ; <nl> std : : vector < Tensor > outputs ; <nl> - eager_pflr - > Run ( opts , handle , { arg } , & outputs , <nl> + const std : : vector < absl : : optional < Tensor > > tensor_args = { absl : : nullopt } ; <nl> + const EagerFunctionArgs args ( <nl> + & tensor_args , <nl> + [ & inputs ] ( const int i , RemoteTensorHandle * handle ) - > Status { <nl> + * handle = inputs . at ( i ) ; <nl> + return Status : : OK ( ) ; <nl> + } ) ; <nl> + eager_pflr - > Run ( opts , handle , args , & outputs , <nl> [ & status , & done ] ( const Status & s ) { <nl> status = s ; <nl> done . Notify ( ) ; <nl> mmm a / tensorflow / core / framework / function . h <nl> ppp b / tensorflow / core / framework / function . h <nl> class DistributedFunctionLibraryRuntime { <nl> / / TODO ( yujingzhang ) : Support outputting tensors on remote devices . <nl> virtual void Run ( const FunctionLibraryRuntime : : Options & opts , <nl> FunctionLibraryRuntime : : LocalHandle handle , <nl> - absl : : Span < eager : : RemoteTensorHandle * const > args , <nl> + std : : vector < eager : : RemoteTensorHandle > * args , <nl> FunctionLibraryRuntime : : DoneCallback done ) { <nl> done ( errors : : Unimplemented ( " Unimplemented . " ) ) ; <nl> } <nl>
For a multi - device function , serialize remote inputs into RemoteTensorHandles when running each remote component function , instead of before running the multi - device function .
tensorflow/tensorflow
0804553314bb7574ac46fc20918d1398803dc4b3
2019-10-05T02:08:30Z
mmm a / filament / README . md <nl> ppp b / filament / README . md <nl> Copy your platform ' s Makefile below into a ` Makefile ` inside the same directory . <nl> # # # Linux <nl> <nl> ` ` ` <nl> - FILAMENT_LIBS = - lfilament - lbackend - lbluegl - lbluevk - lfilabridge - lfilaflat - lutils - lgeometry - lsmol - v <nl> + FILAMENT_LIBS = - lfilament - lbackend - lbluegl - lbluevk - lfilabridge - lfilaflat - lutils - lgeometry - lsmol - v - libl <nl> CC = clang + + <nl> <nl> main : main . o <nl> clean : <nl> # # # macOS <nl> <nl> ` ` ` <nl> - FILAMENT_LIBS = - lfilament - lbackend - lbluegl - lbluevk - lfilabridge - lfilaflat - lutils - lgeometry - lsmol - v <nl> + FILAMENT_LIBS = - lfilament - lbackend - lbluegl - lbluevk - lfilabridge - lfilaflat - lutils - lgeometry - lsmol - v - libl <nl> FRAMEWORKS = - framework Cocoa - framework Metal - framework CoreVideo <nl> CC = clang + + <nl> <nl> used to change the run - time library version . <nl> ` ` ` <nl> FILAMENT_LIBS = lib / x86_64 / mt / filament . lib lib / x86_64 / mt / backend . lib lib / x86_64 / mt / bluegl . lib \ <nl> lib / x86_64 / mt / filabridge . lib lib / x86_64 / mt / filaflat . lib lib / x86_64 / mt / utils . lib \ <nl> - lib / x86_64 / mt / geometry . lib lib / x86_64 / mt / smol - v . lib <nl> + lib / x86_64 / mt / geometry . lib lib / x86_64 / mt / smol - v . lib lib / x86_64 / mt / ibl . lib <nl> CC = clang - cl . exe <nl> <nl> main . exe : main . obj <nl> mmm a / ios / samples / app - template . yml <nl> ppp b / ios / samples / app - template . yml <nl> targetTemplates : <nl> settings : <nl> base : <nl> OTHER_LDFLAGS : [ " - lfilament " , " - lbackend " , " - lfilaflat " , <nl> - " - lfilabridge " , " - lutils " , " - lsmol - v " , " - lgeometry " ] <nl> + " - lfilabridge " , " - lutils " , " - lsmol - v " , " - lgeometry " , " - libl " ] <nl> ENABLE_BITCODE : NO <nl> configs : <nl> debug : <nl> mmm a / ios / samples / hello - ar / hello - ar . xcodeproj / project . pbxproj <nl> ppp b / ios / samples / hello - ar / hello - ar . xcodeproj / project . pbxproj <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> mmm a / ios / samples / hello - gltf / hello - gltf . xcodeproj / project . pbxproj <nl> ppp b / ios / samples / hello - gltf / hello - gltf . xcodeproj / project . pbxproj <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lgltfio_core " , <nl> " - lgltfio_resources " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lgltfio_core " , <nl> " - lgltfio_resources " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lgltfio_core " , <nl> " - lgltfio_resources " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lgltfio_core " , <nl> " - lgltfio_resources " , <nl> " - limage " , <nl> mmm a / ios / samples / hello - pbr / hello - pbr . xcodeproj / project . pbxproj <nl> ppp b / ios / samples / hello - pbr / hello - pbr . xcodeproj / project . pbxproj <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> " - lfilameshio " , <nl> " - lmeshoptimizer " , <nl> " - limage " , <nl> mmm a / ios / samples / hello - triangle / hello - triangle . xcodeproj / project . pbxproj <nl> ppp b / ios / samples / hello - triangle / hello - triangle . xcodeproj / project . pbxproj <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . hello - triangle " ; <nl> SDKROOT = iphoneos ; <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . hello - triangle " ; <nl> SDKROOT = iphoneos ; <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . hello - triangle " ; <nl> SDKROOT = iphoneos ; <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . hello - triangle " ; <nl> SDKROOT = iphoneos ; <nl> mmm a / ios / samples / transparent - rendering / transparent - rendering . xcodeproj / project . pbxproj <nl> ppp b / ios / samples / transparent - rendering / transparent - rendering . xcodeproj / project . pbxproj <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . transparent - rendering " ; <nl> SDKROOT = iphoneos ; <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . transparent - rendering " ; <nl> SDKROOT = iphoneos ; <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . transparent - rendering " ; <nl> SDKROOT = iphoneos ; <nl> <nl> " - lutils " , <nl> " - lsmol - v " , <nl> " - lgeometry " , <nl> + " - libl " , <nl> ) ; <nl> PRODUCT_BUNDLE_IDENTIFIER = " google . filament . transparent - rendering " ; <nl> SDKROOT = iphoneos ; <nl>
Link against IBL library in iOS projects , update README ( )
google/filament
5b2dc1d3debc718e35193337481d254453792b02
2019-07-02T17:43:54Z
mmm a / dbms / include / DB / AggregateFunctions / AggregateFunctionSequenceMatch . h <nl> ppp b / dbms / include / DB / AggregateFunctions / AggregateFunctionSequenceMatch . h <nl> struct AggregateFunctionSequenceMatchData final <nl> } <nl> } ; <nl> <nl> + <nl> + / / / Max number of iterations to match the pattern against a sequence , exception thrown when exceeded <nl> + constexpr auto sequence_match_max_iterations = 1000000 ; <nl> + <nl> class AggregateFunctionSequenceMatch final : public IAggregateFunctionHelper < AggregateFunctionSequenceMatchData > <nl> { <nl> public : <nl> class AggregateFunctionSequenceMatch final : public IAggregateFunctionHelper < Agg <nl> return false ; <nl> } ; <nl> <nl> + std : : size_t i = 0 ; <nl> while ( action_it ! = action_end & & events_it ! = events_end ) <nl> { <nl> / / std : : cout < < " start_timestamp " < < base_it - > first < < " ; " ; <nl> class AggregateFunctionSequenceMatch final : public IAggregateFunctionHelper < Agg <nl> " Unknown PatternActionType " , <nl> ErrorCodes : : LOGICAL_ERROR <nl> } ; <nl> + <nl> + if ( + + i > sequence_match_max_iterations ) <nl> + throw Exception { <nl> + " Pattern application proves too difficult , exceeding max iterations ( " + toString ( sequence_match_max_iterations ) + " ) " , <nl> + ErrorCodes : : TOO_SLOW <nl> + } ; <nl> } <nl> <nl> / / / if there are some actions remaining <nl> new file mode 100644 <nl> index 00000000000 . . 524d88f010f <nl> mmm / dev / null <nl> ppp b / dbms / include / DB / Common / Allocator . h <nl> <nl> + # pragma once <nl> + <nl> + # include < malloc . h > <nl> + # include < string . h > <nl> + # include < sys / mman . h > <nl> + <nl> + # include < DB / Common / MemoryTracker . h > <nl> + # include < DB / Core / Exception . h > <nl> + # include < DB / Core / ErrorCodes . h > <nl> + <nl> + <nl> + / * * Отвечает за выделение / освобождение памяти . Используется , например , в PODArray , Arena . <nl> + * Интерфейс отличается от std : : allocator <nl> + * - наличием метода realloc , который для больших кусков памяти использует mremap ; <nl> + * - передачей размера в метод free ; <nl> + * - наличием аргумента alignment ; <nl> + * / <nl> + class Allocator <nl> + { <nl> + private : <nl> + / * * См . комментарий в HashTableAllocator . h <nl> + * / <nl> + static constexpr size_t MMAP_THRESHOLD = 64 * ( 1 < < 20 ) ; <nl> + static constexpr size_t HUGE_PAGE_SIZE = 2 * ( 1 < < 20 ) ; <nl> + static constexpr size_t MMAP_MIN_ALIGNMENT = 4096 ; <nl> + static constexpr size_t MALLOC_MIN_ALIGNMENT = 8 ; <nl> + <nl> + public : <nl> + / / / Выделить кусок памяти . <nl> + void * alloc ( size_t size , size_t alignment = 0 ) <nl> + { <nl> + if ( current_memory_tracker ) <nl> + current_memory_tracker - > alloc ( size ) ; <nl> + <nl> + void * buf ; <nl> + <nl> + if ( size > = MMAP_THRESHOLD ) <nl> + { <nl> + if ( alignment > MMAP_MIN_ALIGNMENT ) <nl> + throw DB : : Exception ( " Too large alignment : more than page size . " , DB : : ErrorCodes : : BAD_ARGUMENTS ) ; <nl> + <nl> + buf = mmap ( NULL , size , PROT_READ | PROT_WRITE , MAP_PRIVATE | MAP_ANONYMOUS , - 1 , 0 ) ; <nl> + if ( MAP_FAILED = = buf ) <nl> + DB : : throwFromErrno ( " Allocator : Cannot mmap . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> + <nl> + / / / См . комментарий в HashTableAllocator . h <nl> + if ( size > = HUGE_PAGE_SIZE & & 0 ! = madvise ( buf , size , MADV_HUGEPAGE ) ) <nl> + DB : : throwFromErrno ( " HashTableAllocator : Cannot madvise with MADV_HUGEPAGE . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> + } <nl> + else <nl> + { <nl> + if ( alignment < = MALLOC_MIN_ALIGNMENT ) <nl> + { <nl> + buf = : : malloc ( size ) ; <nl> + <nl> + if ( nullptr = = buf ) <nl> + DB : : throwFromErrno ( " Allocator : Cannot malloc . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> + } <nl> + else <nl> + { <nl> + buf = nullptr ; <nl> + int res = posix_memalign ( & buf , alignment , size ) ; <nl> + <nl> + if ( 0 ! = res ) <nl> + DB : : throwFromErrno ( " Cannot allocate memory ( posix_memalign ) " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY , res ) ; <nl> + } <nl> + } <nl> + <nl> + return buf ; <nl> + } <nl> + <nl> + / / / Освободить память . <nl> + void free ( void * buf , size_t size ) <nl> + { <nl> + if ( size > = MMAP_THRESHOLD ) <nl> + { <nl> + if ( 0 ! = munmap ( buf , size ) ) <nl> + DB : : throwFromErrno ( " Allocator : Cannot munmap . " , DB : : ErrorCodes : : CANNOT_MUNMAP ) ; <nl> + } <nl> + else <nl> + { <nl> + : : free ( buf ) ; <nl> + } <nl> + <nl> + if ( current_memory_tracker ) <nl> + current_memory_tracker - > free ( size ) ; <nl> + } <nl> + <nl> + / * * Увеличить размер куска памяти . <nl> + * Содержимое старого куска памяти переезжает в начало нового . <nl> + * Положение куска памяти может измениться . <nl> + * / <nl> + void * realloc ( void * buf , size_t old_size , size_t new_size , size_t alignment = 0 ) <nl> + { <nl> + if ( old_size < MMAP_THRESHOLD & & new_size < MMAP_THRESHOLD & & alignment < = MALLOC_MIN_ALIGNMENT ) <nl> + { <nl> + if ( current_memory_tracker ) <nl> + current_memory_tracker - > realloc ( old_size , new_size ) ; <nl> + <nl> + buf = : : realloc ( buf , new_size ) ; <nl> + <nl> + if ( nullptr = = buf ) <nl> + DB : : throwFromErrno ( " Allocator : Cannot realloc . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> + } <nl> + else if ( old_size > = MMAP_THRESHOLD & & new_size > = MMAP_THRESHOLD ) <nl> + { <nl> + if ( current_memory_tracker ) <nl> + current_memory_tracker - > realloc ( old_size , new_size ) ; <nl> + <nl> + buf = mremap ( buf , old_size , new_size , MREMAP_MAYMOVE ) ; <nl> + if ( MAP_FAILED = = buf ) <nl> + DB : : throwFromErrno ( " Allocator : Cannot mremap . " , DB : : ErrorCodes : : CANNOT_MREMAP ) ; <nl> + } <nl> + else <nl> + { <nl> + void * new_buf = alloc ( new_size , alignment ) ; <nl> + memcpy ( new_buf , buf , old_size ) ; <nl> + free ( buf , old_size ) ; <nl> + buf = new_buf ; <nl> + } <nl> + <nl> + return buf ; <nl> + } <nl> + } ; <nl> mmm a / dbms / include / DB / Common / Arena . h <nl> ppp b / dbms / include / DB / Common / Arena . h <nl> <nl> # include < Poco / SharedPtr . h > <nl> # include < Yandex / likely . h > <nl> # include < DB / Common / ProfileEvents . h > <nl> - # include < DB / Common / MemoryTracker . h > <nl> + # include < DB / Common / Allocator . h > <nl> <nl> <nl> namespace DB <nl> class Arena <nl> { <nl> private : <nl> / / / Непрерывный кусок памяти и указатель на свободное место в нём . Односвязный список . <nl> - struct Chunk : private std : : allocator < char > / / / empty base optimization <nl> + struct Chunk : private Allocator / / / empty base optimization <nl> { <nl> char * begin ; <nl> char * pos ; <nl> class Arena <nl> ProfileEvents : : increment ( ProfileEvents : : ArenaAllocChunks ) ; <nl> ProfileEvents : : increment ( ProfileEvents : : ArenaAllocBytes , size_ ) ; <nl> <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > alloc ( size_ ) ; <nl> - <nl> - begin = allocate ( size_ ) ; <nl> + begin = reinterpret_cast < char * > ( Allocator : : alloc ( size_ ) ) ; <nl> pos = begin ; <nl> end = begin + size_ ; <nl> prev = prev_ ; <nl> class Arena <nl> <nl> ~ Chunk ( ) <nl> { <nl> - deallocate ( begin , size ( ) ) ; <nl> - <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > free ( size ( ) ) ; <nl> + Allocator : : free ( begin , size ( ) ) ; <nl> <nl> if ( prev ) <nl> delete prev ; <nl> mmm a / dbms / include / DB / Common / FileChecker . h <nl> ppp b / dbms / include / DB / Common / FileChecker . h <nl> namespace DB <nl> { <nl> <nl> / / / хранит размеры всех столбцов , и может проверять не побились ли столбцы <nl> - template < class Storage > <nl> class FileChecker <nl> { <nl> public : <nl> - FileChecker ( const std : : string & file_info_path_ , Storage & storage_ ) : <nl> - files_info_path ( file_info_path_ ) , files_info ( ) , storage ( storage_ ) , log ( & Logger : : get ( " FileChecker " ) ) <nl> + FileChecker ( const std : : string & file_info_path_ ) : <nl> + files_info_path ( file_info_path_ ) , files_info ( ) , log ( & Logger : : get ( " FileChecker " ) ) <nl> { <nl> Poco : : Path path ( files_info_path ) ; <nl> tmp_files_info_path = path . parent ( ) . toString ( ) + " tmp_ " + path . getFileName ( ) ; <nl> class FileChecker <nl> using PropertyTree = boost : : property_tree : : ptree ; <nl> PropertyTree files_info ; <nl> <nl> - Storage & storage ; <nl> Logger * log ; <nl> } ; <nl> } <nl> mmm a / dbms / include / DB / Common / HashTable / HashTableAllocator . h <nl> ppp b / dbms / include / DB / Common / HashTable / HashTableAllocator . h <nl> <nl> <nl> <nl> / * * Общая часть разных хэш - таблиц , отвечающая за выделение / освобождение памяти . <nl> + * Отличается от Allocator тем , что зануляет память . <nl> * Используется в качестве параметра шаблона ( есть несколько реализаций с таким же интерфейсом ) . <nl> * / <nl> class HashTableAllocator <nl> class HashTableAllocator <nl> * Рассчитываем , что набор операций mmap / что - то сделать / mremap может выполняться всего лишь около 1000 раз в секунду . <nl> * <nl> * PS . Также это требуется , потому что tcmalloc не может выделить кусок памяти больше 16 GB . <nl> - * NOTE Можно попробовать MAP_HUGETLB , но придётся самостоятельно управлять количеством доступных страниц . <nl> * / <nl> static constexpr size_t MMAP_THRESHOLD = 64 * ( 1 < < 20 ) ; <nl> + static constexpr size_t HUGE_PAGE_SIZE = 2 * ( 1 < < 20 ) ; <nl> <nl> public : <nl> / / / Выделить кусок памяти и заполнить его нулями . <nl> class HashTableAllocator <nl> if ( MAP_FAILED = = buf ) <nl> DB : : throwFromErrno ( " HashTableAllocator : Cannot mmap . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> <nl> + / * * Использование huge pages позволяет увеличить производительность более чем в три раза <nl> + * в запросе SELECT number % 1000000 AS k , count ( ) FROM system . numbers GROUP BY k , <nl> + * ( хэш - таблица на 1 000 000 элементов ) <nl> + * и примерно на 15 % в случае хэш - таблицы на 100 000 000 элементов . <nl> + * / <nl> + if ( size > = HUGE_PAGE_SIZE & & 0 ! = madvise ( buf , size , MADV_HUGEPAGE ) ) <nl> + DB : : throwFromErrno ( " HashTableAllocator : Cannot madvise with MADV_HUGEPAGE . " , DB : : ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> + <nl> / / / Заполнение нулями не нужно - mmap сам это делает . <nl> } <nl> else <nl> class HashTableAllocator <nl> if ( MAP_FAILED = = buf ) <nl> DB : : throwFromErrno ( " HashTableAllocator : Cannot mremap . " , DB : : ErrorCodes : : CANNOT_MREMAP ) ; <nl> <nl> + / * * Здесь не получается сделать madvise с MADV_HUGEPAGE . <nl> + * Похоже , что при mremap , huge pages сами расширяются на новую область . <nl> + * / <nl> + <nl> / / / Заполнение нулями не нужно . <nl> } <nl> else <nl> mmm a / dbms / include / DB / Common / PODArray . h <nl> ppp b / dbms / include / DB / Common / PODArray . h <nl> <nl> # pragma once <nl> <nl> # include < string . h > <nl> - # include < malloc . h > <nl> # include < cstddef > <nl> # include < algorithm > <nl> # include < memory > <nl> <nl> # include < Yandex / likely . h > <nl> # include < Yandex / strong_typedef . h > <nl> <nl> - # include < DB / Common / MemoryTracker . h > <nl> + # include < DB / Common / Allocator . h > <nl> # include < DB / Core / Exception . h > <nl> # include < DB / Core / ErrorCodes . h > <nl> <nl> namespace DB <nl> * Конструктор по - умолчанию создаёт пустой объект , который не выделяет память . <nl> * Затем выделяется память минимум под POD_ARRAY_INITIAL_SIZE элементов . <nl> * <nl> - * При первом выделении памяти использует std : : allocator . <nl> - * В реализации из libstdc + + он кэширует куски памяти несколько больше , чем обычный malloc . <nl> - * <nl> - * При изменении размера , использует realloc , который может ( но не обязан ) использовать mremap для больших кусков памяти . <nl> - * По факту , mremap используется при использовании аллокатора из glibc , но не используется , например , в tcmalloc . <nl> - * <nl> * Если вставлять элементы push_back - ом , не делая reserve , то PODArray примерно в 2 . 5 раза быстрее std : : vector . <nl> * / <nl> # define POD_ARRAY_INITIAL_SIZE 4096UL <nl> <nl> template < typename T > <nl> - class PODArray : private boost : : noncopyable , private std : : allocator < char > / / / empty base optimization <nl> + class PODArray : private boost : : noncopyable , private Allocator / / / empty base optimization <nl> { <nl> private : <nl> - typedef std : : allocator < char > Allocator ; <nl> - <nl> char * c_start ; <nl> char * c_end ; <nl> char * c_end_of_storage ; <nl> <nl> - bool use_libc_realloc = false ; <nl> - <nl> T * t_start ( ) { return reinterpret_cast < T * > ( c_start ) ; } <nl> T * t_end ( ) { return reinterpret_cast < T * > ( c_end ) ; } <nl> T * t_end_of_storage ( ) { return reinterpret_cast < T * > ( c_end_of_storage ) ; } <nl> class PODArray : private boost : : noncopyable , private std : : allocator < char > / / / em <nl> <nl> size_t bytes_to_alloc = to_size ( n ) ; <nl> <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > alloc ( bytes_to_alloc ) ; <nl> - <nl> - c_start = c_end = Allocator : : allocate ( bytes_to_alloc ) ; <nl> + c_start = c_end = reinterpret_cast < char * > ( Allocator : : alloc ( bytes_to_alloc ) ) ; <nl> c_end_of_storage = c_start + bytes_to_alloc ; <nl> } <nl> <nl> class PODArray : private boost : : noncopyable , private std : : allocator < char > / / / em <nl> if ( c_start = = nullptr ) <nl> return ; <nl> <nl> - if ( use_libc_realloc ) <nl> - : : free ( c_start ) ; <nl> - else <nl> - Allocator : : deallocate ( c_start , storage_size ( ) ) ; <nl> - <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > free ( storage_size ( ) ) ; <nl> + Allocator : : free ( c_start , storage_size ( ) ) ; <nl> } <nl> <nl> void realloc ( size_t n ) <nl> class PODArray : private boost : : noncopyable , private std : : allocator < char > / / / em <nl> ptrdiff_t end_diff = c_end - c_start ; <nl> size_t bytes_to_alloc = to_size ( n ) ; <nl> <nl> - char * old_c_start = c_start ; <nl> - char * old_c_end_of_storage = c_end_of_storage ; <nl> - <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > realloc ( storage_size ( ) , bytes_to_alloc ) ; <nl> - <nl> - if ( use_libc_realloc ) <nl> - { <nl> - auto new_c_start = reinterpret_cast < char * > ( : : realloc ( c_start , bytes_to_alloc ) ) ; <nl> - <nl> - if ( nullptr = = new_c_start ) <nl> - throwFromErrno ( " PODArray : cannot realloc " , ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - <nl> - c_start = new_c_start ; <nl> - } <nl> - else <nl> - { <nl> - auto new_c_start = reinterpret_cast < char * > ( malloc ( bytes_to_alloc ) ) ; <nl> - <nl> - if ( nullptr = = new_c_start ) <nl> - throwFromErrno ( " PODArray : cannot realloc " , ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - <nl> - c_start = new_c_start ; <nl> - <nl> - memcpy ( c_start , old_c_start , std : : min ( bytes_to_alloc , static_cast < size_t > ( end_diff ) ) ) ; <nl> - Allocator : : deallocate ( old_c_start , old_c_end_of_storage - old_c_start ) ; <nl> - } <nl> + c_start = reinterpret_cast < char * > ( Allocator : : realloc ( c_start , storage_size ( ) , bytes_to_alloc ) ) ; <nl> <nl> c_end = c_start + end_diff ; <nl> c_end_of_storage = c_start + bytes_to_alloc ; <nl> - <nl> - use_libc_realloc = true ; <nl> } <nl> <nl> public : <nl> class PODArray : private boost : : noncopyable , private std : : allocator < char > / / / em <nl> std : : swap ( c_start , other . c_start ) ; <nl> std : : swap ( c_end , other . c_end ) ; <nl> std : : swap ( c_end_of_storage , other . c_end_of_storage ) ; <nl> - std : : swap ( use_libc_realloc , other . use_libc_realloc ) ; <nl> <nl> return * this ; <nl> } <nl> mmm a / dbms / include / DB / Core / ErrorCodes . h <nl> ppp b / dbms / include / DB / Core / ErrorCodes . h <nl> namespace ErrorCodes <nl> ALL_CONNECTION_TRIES_FAILED = 279 , <nl> NO_AVAILABLE_DATA = 280 , <nl> DICTIONARY_IS_EMPTY = 281 , <nl> + INCORRECT_INDEX = 282 , <nl> <nl> KEEPER_EXCEPTION = 999 , <nl> POCO_EXCEPTION = 1000 , <nl> new file mode 100644 <nl> index 00000000000 . . ff21cbb8af4 <nl> mmm / dev / null <nl> ppp b / dbms / include / DB / DataStreams / MarkInCompressedFile . h <nl> <nl> + # pragma once <nl> + <nl> + # include < tuple > <nl> + <nl> + # include < DB / Core / Types . h > <nl> + # include < DB / IO / WriteHelpers . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + / * * Засечка - позиция в сжатом файле . Сжатый файл состоит из уложенных подряд сжатых блоков . <nl> + * Засечка представляют собой пару - смещение в файле до начала сжатого блока , смещение в разжатом блоке до начала данных . <nl> + * / <nl> + struct MarkInCompressedFile <nl> + { <nl> + size_t offset_in_compressed_file ; <nl> + size_t offset_in_decompressed_block ; <nl> + <nl> + bool operator = = ( const MarkInCompressedFile & rhs ) const <nl> + { <nl> + return std : : tie ( offset_in_compressed_file , offset_in_decompressed_block ) <nl> + = = std : : tie ( rhs . offset_in_compressed_file , rhs . offset_in_decompressed_block ) ; <nl> + } <nl> + bool operator ! = ( const MarkInCompressedFile & rhs ) const <nl> + { <nl> + return ! ( * this = = rhs ) ; <nl> + } <nl> + <nl> + String toString ( ) const <nl> + { <nl> + return " ( " + DB : : toString ( offset_in_compressed_file ) + " , " + DB : : toString ( offset_in_decompressed_block ) + " ) " ; <nl> + } <nl> + } ; <nl> + <nl> + using MarksInCompressedFile = std : : vector < MarkInCompressedFile > ; <nl> + <nl> + } <nl> mmm a / dbms / include / DB / DataStreams / NativeBlockInputStream . h <nl> ppp b / dbms / include / DB / DataStreams / NativeBlockInputStream . h <nl> <nl> # pragma once <nl> <nl> # include < DB / DataStreams / IProfilingBlockInputStream . h > <nl> + # include < DB / DataStreams / MarkInCompressedFile . h > <nl> <nl> <nl> namespace DB <nl> { <nl> <nl> + class CompressedReadBufferFromFile ; <nl> + <nl> + <nl> + / * * Формат Native может содержать отдельно расположенный индекс , <nl> + * который позволяет понять , где какой столбец расположен , <nl> + * и пропускать ненужные столбцы . <nl> + * / <nl> + <nl> + / * * Позиция одного кусочка одного столбца . * / <nl> + struct IndexOfOneColumnForNativeFormat <nl> + { <nl> + String name ; <nl> + String type ; <nl> + MarkInCompressedFile location ; <nl> + } ; <nl> + <nl> + / * * Индекс для блока данных . * / <nl> + struct IndexOfBlockForNativeFormat <nl> + { <nl> + using Columns = std : : vector < IndexOfOneColumnForNativeFormat > ; <nl> + <nl> + size_t num_columns ; <nl> + size_t num_rows ; <nl> + Columns columns ; <nl> + } ; <nl> + <nl> + / * * Весь индекс . * / <nl> + struct IndexForNativeFormat <nl> + { <nl> + using Blocks = std : : vector < IndexOfBlockForNativeFormat > ; <nl> + Blocks blocks ; <nl> + <nl> + IndexForNativeFormat ( ) { } <nl> + <nl> + IndexForNativeFormat ( ReadBuffer & istr , const NameSet & required_columns ) <nl> + { <nl> + read ( istr , required_columns ) ; <nl> + } <nl> + <nl> + / / / Прочитать индекс , только для нужных столбцов . <nl> + void read ( ReadBuffer & istr , const NameSet & required_columns ) ; <nl> + } ; <nl> + <nl> + <nl> / * * Десериализует поток блоков из родного бинарного формата ( с именами и типами столбцов ) . <nl> * Предназначено для взаимодействия между серверами . <nl> + * <nl> + * Также может использоваться для хранения данных на диске . <nl> + * В этом случае , может использовать индекс . <nl> * / <nl> class NativeBlockInputStream : public IProfilingBlockInputStream <nl> { <nl> public : <nl> / * * В случае указания ненулевой server_revision , может ожидаться и считываться дополнительная информация о блоке , <nl> * в зависимости от поддерживаемой для указанной ревизии . <nl> + * <nl> + * index - не обязательный параметр . Если задан , то будут читаться только указанные в индексе кусочки столбцов . <nl> * / <nl> - NativeBlockInputStream ( ReadBuffer & istr_ , UInt64 server_revision_ = 0 ) <nl> - : istr ( istr_ ) , server_revision ( server_revision_ ) { } <nl> + NativeBlockInputStream ( <nl> + ReadBuffer & istr_ , UInt64 server_revision_ = 0 , <nl> + bool use_index_ = false , <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_block_it_ = IndexForNativeFormat : : Blocks : : const_iterator { } , <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_block_end_ = IndexForNativeFormat : : Blocks : : const_iterator { } ) ; <nl> <nl> String getName ( ) const override { return " Native " ; } <nl> <nl> class NativeBlockInputStream : public IProfilingBlockInputStream <nl> private : <nl> ReadBuffer & istr ; <nl> UInt64 server_revision ; <nl> + <nl> + bool use_index ; <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_block_it ; <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_block_end ; <nl> + IndexOfBlockForNativeFormat : : Columns : : const_iterator index_column_it ; <nl> + <nl> + / / / Если задан индекс , то istr должен быть CompressedReadBufferFromFile . <nl> + CompressedReadBufferFromFile * istr_concrete ; <nl> } ; <nl> <nl> } <nl> mmm a / dbms / include / DB / DataStreams / NativeBlockOutputStream . h <nl> ppp b / dbms / include / DB / DataStreams / NativeBlockOutputStream . h <nl> <nl> namespace DB <nl> { <nl> <nl> + class WriteBuffer ; <nl> + class CompressedWriteBuffer ; <nl> + <nl> + <nl> / * * Сериализует поток блоков в родном бинарном формате ( с именами и типами столбцов ) . <nl> * Предназначено для взаимодействия между серверами . <nl> + * <nl> + * Может быть указан поток для записи индекса . Индекс содержит смещения до каждого кусочка каждого столбца . <nl> * / <nl> class NativeBlockOutputStream : public IBlockOutputStream <nl> { <nl> class NativeBlockOutputStream : public IBlockOutputStream <nl> / * * В случае указания ненулевой client_revision , может записываться дополнительная информация о блоке , <nl> * в зависимости от поддерживаемой для указанной ревизии . <nl> * / <nl> - NativeBlockOutputStream ( WriteBuffer & ostr_ , UInt64 client_revision_ = 0 ) <nl> - : ostr ( ostr_ ) , client_revision ( client_revision_ ) { } <nl> + NativeBlockOutputStream ( <nl> + WriteBuffer & ostr_ , UInt64 client_revision_ = 0 , <nl> + WriteBuffer * index_ostr_ = nullptr ) ; <nl> <nl> void write ( const Block & block ) override ; <nl> void flush ( ) override { ostr . next ( ) ; } <nl> class NativeBlockOutputStream : public IBlockOutputStream <nl> private : <nl> WriteBuffer & ostr ; <nl> UInt64 client_revision ; <nl> + <nl> + WriteBuffer * index_ostr ; <nl> + / / / Если требуется записывать индекс , то ostr обязан быть CompressedWriteBuffer . <nl> + CompressedWriteBuffer * ostr_concrete = nullptr ; <nl> } ; <nl> <nl> } <nl> mmm a / dbms / include / DB / Dictionaries / CacheDictionary . h <nl> ppp b / dbms / include / DB / Dictionaries / CacheDictionary . h <nl> class CacheDictionary final : public IDictionary <nl> { <nl> if ( ! this - > source_ptr - > supportsSelectiveLoad ( ) ) <nl> throw Exception { <nl> - " Source cannot be used with CacheDictionary " , <nl> + name + " : source cannot be used with CacheDictionary " , <nl> ErrorCodes : : UNSUPPORTED_METHOD <nl> } ; <nl> <nl> class CacheDictionary final : public IDictionary <nl> auto & attribute = getAttribute ( attribute_name ) ; \ <nl> if ( attribute . type ! = AttributeUnderlyingType : : TYPE ) \ <nl> throw Exception { \ <nl> - " Type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , \ <nl> + name + " : type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , \ <nl> ErrorCodes : : TYPE_MISMATCH \ <nl> } ; \ <nl> \ <nl> class CacheDictionary final : public IDictionary <nl> auto & attribute = getAttribute ( attribute_name ) ; <nl> if ( attribute . type ! = AttributeUnderlyingType : : String ) <nl> throw Exception { <nl> - " Type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , <nl> + name + " : type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> <nl> class CacheDictionary final : public IDictionary <nl> <nl> if ( hierarchical_attribute - > type ! = AttributeUnderlyingType : : UInt64 ) <nl> throw Exception { <nl> - " Hierarchical attribute must be UInt64 . " , <nl> + name + " : hierarchical attribute must be UInt64 . " , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> } <nl> class CacheDictionary final : public IDictionary <nl> const auto id_column = typeid_cast < const ColumnVector < UInt64 > * > ( block . getByPosition ( 0 ) . column . get ( ) ) ; <nl> if ( ! id_column ) <nl> throw Exception { <nl> - " Id column has type different from UInt64 . " , <nl> + name + " : id column has type different from UInt64 . " , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> <nl> class CacheDictionary final : public IDictionary <nl> const auto it = attribute_index_by_name . find ( attribute_name ) ; <nl> if ( it = = std : : end ( attribute_index_by_name ) ) <nl> throw Exception { <nl> - " No such attribute ' " + attribute_name + " ' " , <nl> + name + " : no such attribute ' " + attribute_name + " ' " , <nl> ErrorCodes : : BAD_ARGUMENTS <nl> } ; <nl> <nl> mmm a / dbms / include / DB / Dictionaries / DictionarySourceFactory . h <nl> ppp b / dbms / include / DB / Dictionaries / DictionarySourceFactory . h <nl> Block createSampleBlock ( const DictionaryStructure & dict_struct ) <nl> class DictionarySourceFactory : public Singleton < DictionarySourceFactory > <nl> { <nl> public : <nl> - DictionarySourcePtr create ( Poco : : Util : : AbstractConfiguration & config , <nl> - const std : : string & config_prefix , <nl> - const DictionaryStructure & dict_struct , <nl> - Context & context ) const <nl> + DictionarySourcePtr create ( <nl> + const std : : string & name , Poco : : Util : : AbstractConfiguration & config , const std : : string & config_prefix , <nl> + const DictionaryStructure & dict_struct , Context & context ) const <nl> { <nl> Poco : : Util : : AbstractConfiguration : : Keys keys ; <nl> config . keys ( config_prefix , keys ) ; <nl> if ( keys . size ( ) ! = 1 ) <nl> throw Exception { <nl> - " Element dictionary . source should have exactly one child element " , <nl> + name + " : element dictionary . source should have exactly one child element " , <nl> ErrorCodes : : EXCESSIVE_ELEMENT_IN_CONFIG <nl> } ; <nl> <nl> class DictionarySourceFactory : public Singleton < DictionarySourceFactory > <nl> } <nl> <nl> throw Exception { <nl> - " Unknown dictionary source type : " + source_type , <nl> + name + " : unknown dictionary source type : " + source_type , <nl> ErrorCodes : : UNKNOWN_ELEMENT_IN_CONFIG <nl> } ; <nl> } <nl> mmm a / dbms / include / DB / Dictionaries / FlatDictionary . h <nl> ppp b / dbms / include / DB / Dictionaries / FlatDictionary . h <nl> class FlatDictionary final : public IDictionary <nl> const auto & attribute = getAttribute ( attribute_name ) ; \ <nl> if ( attribute . type ! = AttributeUnderlyingType : : TYPE ) \ <nl> throw Exception { \ <nl> - " Type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , \ <nl> + name + " : type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , \ <nl> ErrorCodes : : TYPE_MISMATCH \ <nl> } ; \ <nl> \ <nl> class FlatDictionary final : public IDictionary <nl> const auto & attribute = getAttribute ( attribute_name ) ; <nl> if ( attribute . type ! = AttributeUnderlyingType : : String ) <nl> throw Exception { <nl> - " Type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , <nl> + name + " : type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> <nl> class FlatDictionary final : public IDictionary <nl> <nl> if ( hierarchical_attribute - > type ! = AttributeUnderlyingType : : UInt64 ) <nl> throw Exception { <nl> - " Hierarchical attribute must be UInt64 . " , <nl> + name + " : hierarchical attribute must be UInt64 . " , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> } <nl> class FlatDictionary final : public IDictionary <nl> stream - > readSuffix ( ) ; <nl> <nl> if ( require_nonempty & & 0 = = element_count ) <nl> - throw Exception ( " Dictionary source is empty and ' require_nonempty ' property is set . " , ErrorCodes : : DICTIONARY_IS_EMPTY ) ; <nl> + throw Exception { <nl> + name + " : dictionary source is empty and ' require_nonempty ' property is set . " , <nl> + ErrorCodes : : DICTIONARY_IS_EMPTY <nl> + } ; <nl> } <nl> <nl> template < typename T > <nl> class FlatDictionary final : public IDictionary <nl> { <nl> if ( id > = max_array_size ) <nl> throw Exception { <nl> - " Identifier should be less than " + toString ( max_array_size ) , <nl> + name + " : identifier should be less than " + toString ( max_array_size ) , <nl> ErrorCodes : : ARGUMENT_OUT_OF_BOUND <nl> } ; <nl> <nl> class FlatDictionary final : public IDictionary <nl> const auto it = attribute_index_by_name . find ( attribute_name ) ; <nl> if ( it = = std : : end ( attribute_index_by_name ) ) <nl> throw Exception { <nl> - " No such attribute ' " + attribute_name + " ' " , <nl> + name + " : no such attribute ' " + attribute_name + " ' " , <nl> ErrorCodes : : BAD_ARGUMENTS <nl> } ; <nl> <nl> mmm a / dbms / include / DB / Dictionaries / HashedDictionary . h <nl> ppp b / dbms / include / DB / Dictionaries / HashedDictionary . h <nl> class HashedDictionary final : public IDictionary <nl> const auto & attribute = getAttribute ( attribute_name ) ; \ <nl> if ( attribute . type ! = AttributeUnderlyingType : : TYPE ) \ <nl> throw Exception { \ <nl> - " Type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , \ <nl> + name + " : type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , \ <nl> ErrorCodes : : TYPE_MISMATCH \ <nl> } ; \ <nl> \ <nl> class HashedDictionary final : public IDictionary <nl> const auto & attribute = getAttribute ( attribute_name ) ; <nl> if ( attribute . type ! = AttributeUnderlyingType : : String ) <nl> throw Exception { <nl> - " Type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , <nl> + name + " : type mismatch : attribute " + attribute_name + " has type " + toString ( attribute . type ) , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> <nl> class HashedDictionary final : public IDictionary <nl> <nl> if ( hierarchical_attribute - > type ! = AttributeUnderlyingType : : UInt64 ) <nl> throw Exception { <nl> - " Hierarchical attribute must be UInt64 . " , <nl> + name + " : hierarchical attribute must be UInt64 . " , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> } <nl> class HashedDictionary final : public IDictionary <nl> stream - > readSuffix ( ) ; <nl> <nl> if ( require_nonempty & & 0 = = element_count ) <nl> - throw Exception ( " Dictionary source is empty and ' require_nonempty ' property is set . " , ErrorCodes : : DICTIONARY_IS_EMPTY ) ; <nl> + throw Exception { <nl> + name + " : dictionary source is empty and ' require_nonempty ' property is set . " , <nl> + ErrorCodes : : DICTIONARY_IS_EMPTY <nl> + } ; <nl> } <nl> <nl> template < typename T > <nl> class HashedDictionary final : public IDictionary <nl> const auto it = attribute_index_by_name . find ( attribute_name ) ; <nl> if ( it = = std : : end ( attribute_index_by_name ) ) <nl> throw Exception { <nl> - " No such attribute ' " + attribute_name + " ' " , <nl> + name + " : no such attribute ' " + attribute_name + " ' " , <nl> ErrorCodes : : BAD_ARGUMENTS <nl> } ; <nl> <nl> mmm a / dbms / include / DB / Dictionaries / RangeHashedDictionary . h <nl> ppp b / dbms / include / DB / Dictionaries / RangeHashedDictionary . h <nl> class RangeHashedDictionary final : public IDictionaryBase <nl> <nl> if ( attribute . hierarchical ) <nl> throw Exception { <nl> - " Hierarchical attributes not supported by " + getName ( ) + " dictionary . " , <nl> + name + " : hierarchical attributes not supported by " + getName ( ) + " dictionary . " , <nl> ErrorCodes : : BAD_ARGUMENTS <nl> } ; <nl> } <nl> class RangeHashedDictionary final : public IDictionaryBase <nl> stream - > readSuffix ( ) ; <nl> <nl> if ( require_nonempty & & 0 = = element_count ) <nl> - throw Exception ( " Dictionary source is empty and ' require_nonempty ' property is set . " , ErrorCodes : : DICTIONARY_IS_EMPTY ) ; <nl> + throw Exception { <nl> + name + " : dictionary source is empty and ' require_nonempty ' property is set . " , <nl> + ErrorCodes : : DICTIONARY_IS_EMPTY <nl> + } ; <nl> } <nl> <nl> template < typename T > <nl> class RangeHashedDictionary final : public IDictionaryBase <nl> const auto it = attribute_index_by_name . find ( attribute_name ) ; <nl> if ( it = = std : : end ( attribute_index_by_name ) ) <nl> throw Exception { <nl> - " No such attribute ' " + attribute_name + " ' " , <nl> + name + " : no such attribute ' " + attribute_name + " ' " , <nl> ErrorCodes : : BAD_ARGUMENTS <nl> } ; <nl> <nl> class RangeHashedDictionary final : public IDictionaryBase <nl> const auto & attribute = getAttribute ( name ) ; <nl> if ( attribute . type ! = type ) <nl> throw Exception { <nl> - " Type mismatch : attribute " + name + " has type " + toString ( attribute . type ) , <nl> + name + " : type mismatch : attribute " + name + " has type " + toString ( attribute . type ) , <nl> ErrorCodes : : TYPE_MISMATCH <nl> } ; <nl> <nl> mmm a / dbms / include / DB / IO / BufferWithOwnMemory . h <nl> ppp b / dbms / include / DB / IO / BufferWithOwnMemory . h <nl> <nl> # include < boost / noncopyable . hpp > <nl> <nl> # include < DB / Common / ProfileEvents . h > <nl> - # include < DB / Common / MemoryTracker . h > <nl> + # include < DB / Common / Allocator . h > <nl> <nl> # include < DB / Core / Exception . h > <nl> # include < DB / Core / ErrorCodes . h > <nl> namespace DB <nl> * Отличается тем , что не делает лишний memset . ( И почти ничего не делает . ) <nl> * Также можно попросить выделять выровненный кусок памяти . <nl> * / <nl> - struct Memory : boost : : noncopyable <nl> + struct Memory : boost : : noncopyable , Allocator <nl> { <nl> size_t m_capacity = 0 ; <nl> size_t m_size = 0 ; <nl> struct Memory : boost : : noncopyable <nl> } <nl> else <nl> { <nl> - dealloc ( ) ; <nl> - <nl> + new_size = align ( new_size ) ; <nl> + m_data = reinterpret_cast < char * > ( Allocator : : realloc ( m_data , m_capacity , new_size , alignment ) ) ; <nl> m_capacity = new_size ; <nl> m_size = m_capacity ; <nl> - <nl> - alloc ( ) ; <nl> } <nl> } <nl> <nl> private : <nl> + size_t align ( size_t value ) const <nl> + { <nl> + if ( ! alignment ) <nl> + return value ; <nl> + <nl> + return ( value + alignment - 1 ) / alignment * alignment ; <nl> + } <nl> + <nl> void alloc ( ) <nl> { <nl> if ( ! m_capacity ) <nl> struct Memory : boost : : noncopyable <nl> ProfileEvents : : increment ( ProfileEvents : : IOBufferAllocs ) ; <nl> ProfileEvents : : increment ( ProfileEvents : : IOBufferAllocBytes , m_capacity ) ; <nl> <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > alloc ( m_capacity ) ; <nl> - <nl> - char * new_m_data = nullptr ; <nl> - <nl> - if ( ! alignment ) <nl> - { <nl> - new_m_data = reinterpret_cast < char * > ( malloc ( m_capacity ) ) ; <nl> - <nl> - if ( ! new_m_data ) <nl> - throw Exception ( " Cannot allocate memory ( malloc ) " , ErrorCodes : : CANNOT_ALLOCATE_MEMORY ) ; <nl> - <nl> - m_data = new_m_data ; <nl> - <nl> - return ; <nl> - } <nl> - <nl> - size_t aligned_capacity = ( m_capacity + alignment - 1 ) / alignment * alignment ; <nl> - m_capacity = aligned_capacity ; <nl> + size_t new_capacity = align ( m_capacity ) ; <nl> + m_data = reinterpret_cast < char * > ( Allocator : : alloc ( new_capacity , alignment ) ) ; <nl> + m_capacity = new_capacity ; <nl> m_size = m_capacity ; <nl> - <nl> - int res = posix_memalign ( reinterpret_cast < void * * > ( & new_m_data ) , alignment , m_capacity ) ; <nl> - <nl> - if ( 0 ! = res ) <nl> - DB : : throwFromErrno ( " Cannot allocate memory ( posix_memalign ) " , ErrorCodes : : CANNOT_ALLOCATE_MEMORY , res ) ; <nl> - <nl> - m_data = new_m_data ; <nl> } <nl> <nl> void dealloc ( ) <nl> struct Memory : boost : : noncopyable <nl> if ( ! m_data ) <nl> return ; <nl> <nl> - free ( reinterpret_cast < void * > ( m_data ) ) ; <nl> + Allocator : : free ( reinterpret_cast < void * > ( m_data ) , m_capacity ) ; <nl> m_data = nullptr ; / / / Чтобы избежать double free , если последующий вызов alloc кинет исключение . <nl> - <nl> - if ( current_memory_tracker ) <nl> - current_memory_tracker - > free ( m_capacity ) ; <nl> } <nl> } ; <nl> <nl> mmm a / dbms / include / DB / IO / HashingWriteBuffer . h <nl> ppp b / dbms / include / DB / IO / HashingWriteBuffer . h <nl> template < class Buffer > <nl> class IHashingBuffer : public BufferWithOwnMemory < Buffer > <nl> { <nl> public : <nl> - IHashingBuffer < Buffer > ( size_t block_size_ = DBMS_DEFAULT_HASHING_BLOCK_SIZE ) : <nl> - block_pos ( 0 ) , block_size ( block_size_ ) , state ( 0 , 0 ) <nl> + IHashingBuffer < Buffer > ( size_t block_size_ = DBMS_DEFAULT_HASHING_BLOCK_SIZE ) <nl> + : BufferWithOwnMemory < Buffer > ( block_size_ ) , block_pos ( 0 ) , block_size ( block_size_ ) , state ( 0 , 0 ) <nl> { <nl> } <nl> <nl> mmm a / dbms / include / DB / Interpreters / sortBlock . h <nl> ppp b / dbms / include / DB / Interpreters / sortBlock . h <nl> void sortBlock ( Block & block , const SortDescription & description , size_t limit <nl> * / <nl> void stableSortBlock ( Block & block , const SortDescription & description ) ; <nl> <nl> + / * * То же , что и stableSortBlock , но не сортировать блок , а только рассчитать перестановку значений , <nl> + * чтобы потом можно было переставить значения столбцов самостоятельно . <nl> + * / <nl> + void stableGetPermutation ( const Block & block , const SortDescription & description , IColumn : : Permutation & out_permutation ) ; <nl> + <nl> } <nl> mmm a / dbms / include / DB / Parsers / ASTJoin . h <nl> ppp b / dbms / include / DB / Parsers / ASTJoin . h <nl> class ASTJoin : public IAST <nl> settings . ostr < < ( strictness = = ASTJoin : : Any ? " ANY " : " ALL " ) ; <nl> <nl> settings . ostr < < ( kind = = ASTJoin : : Inner ? " INNER " <nl> - : ( kind = = ASTJoin : : Left ? " LEFT " <nl> - : ( kind = = ASTJoin : : Right ? " RIGHT " <nl> - : ( kind = = ASTJoin : : Cross ? " CROSS " <nl> - : " FULL OUTER " ) ) ) ) ; <nl> + : ( kind = = ASTJoin : : Left ? " LEFT " <nl> + : ( kind = = ASTJoin : : Right ? " RIGHT " <nl> + : ( kind = = ASTJoin : : Cross ? " CROSS " <nl> + : " FULL OUTER " ) ) ) ) ; <nl> <nl> settings . ostr < < " JOIN " <nl> - < < ( settings . hilite ? hilite_none : " " ) ; <nl> + < < ( settings . hilite ? hilite_none : " " ) ; <nl> <nl> - FormatStateStacked frame_with_indent = frame ; <nl> - + + frame_with_indent . indent ; <nl> - table - > formatImpl ( settings , state , frame_with_indent ) ; <nl> + table - > formatImpl ( settings , state , frame ) ; <nl> <nl> if ( kind ! = ASTJoin : : Cross ) <nl> { <nl> mmm a / dbms / include / DB / Storages / MarkCache . h <nl> ppp b / dbms / include / DB / Storages / MarkCache . h <nl> <nl> # include < DB / Common / ProfileEvents . h > <nl> # include < DB / Common / SipHash . h > <nl> # include < DB / Interpreters / AggregationCommon . h > <nl> + # include < DB / DataStreams / MarkInCompressedFile . h > <nl> <nl> <nl> - namespace DB <nl> - { <nl> <nl> - struct MarkInCompressedFile <nl> + namespace DB <nl> { <nl> - size_t offset_in_compressed_file ; <nl> - size_t offset_in_decompressed_block ; <nl> - <nl> - bool operator = = ( const MarkInCompressedFile & rhs ) const <nl> - { <nl> - return std : : forward_as_tuple ( offset_in_compressed_file , offset_in_decompressed_block ) = = <nl> - std : : forward_as_tuple ( rhs . offset_in_compressed_file , rhs . offset_in_decompressed_block ) ; <nl> - } <nl> - bool operator ! = ( const MarkInCompressedFile & rhs ) const <nl> - { <nl> - return ! ( * this = = rhs ) ; <nl> - } <nl> - <nl> - String toString ( ) const <nl> - { <nl> - return " ( " + DB : : toString ( offset_in_compressed_file ) + " , " + DB : : toString ( offset_in_decompressed_block ) + " ) " ; <nl> - } <nl> - } ; <nl> - <nl> - typedef std : : vector < MarkInCompressedFile > MarksInCompressedFile ; <nl> <nl> / / / Оценка количества байтов , занимаемых засечками в кеше . <nl> struct MarksWeightFunction <nl> mmm a / dbms / include / DB / Storages / MergeTree / ActiveDataPartSet . h <nl> ppp b / dbms / include / DB / Storages / MergeTree / ActiveDataPartSet . h <nl> class ActiveDataPartSet <nl> { <nl> DayNum_t left_date ; <nl> DayNum_t right_date ; <nl> - UInt64 left ; <nl> - UInt64 right ; <nl> + Int64 left ; <nl> + Int64 right ; <nl> UInt32 level ; <nl> std : : string name ; <nl> - DayNum_t left_month ; <nl> - DayNum_t right_month ; <nl> + DayNum_t month ; <nl> <nl> bool operator < ( const Part & rhs ) const <nl> { <nl> - if ( left_month ! = rhs . left_month ) <nl> - return left_month < rhs . left_month ; <nl> - if ( right_month ! = rhs . right_month ) <nl> - return right_month < rhs . right_month ; <nl> + if ( month ! = rhs . month ) <nl> + return month < rhs . month ; <nl> <nl> if ( left ! = rhs . left ) <nl> return left < rhs . left ; <nl> class ActiveDataPartSet <nl> / / / Содержит другой кусок ( получен после объединения другого куска с каким - то ещё ) <nl> bool contains ( const Part & rhs ) const <nl> { <nl> - return left_month = = rhs . left_month / / / Куски за разные месяцы не объединяются <nl> - & & right_month = = rhs . right_month <nl> + return month = = rhs . month / / / Куски за разные месяцы не объединяются <nl> & & left_date < = rhs . left_date <nl> & & right_date > = rhs . right_date <nl> & & left < = rhs . left <nl> class ActiveDataPartSet <nl> <nl> size_t size ( ) const ; <nl> <nl> - static String getPartName ( DayNum_t left_date , DayNum_t right_date , UInt64 left_id , UInt64 right_id , UInt64 level ) ; <nl> + static String getPartName ( DayNum_t left_date , DayNum_t right_date , Int64 left_id , Int64 right_id , UInt64 level ) ; <nl> <nl> / / / Возвращает true если имя директории совпадает с форматом имени директории кусочков <nl> static bool isPartDirectory ( const String & dir_name , Poco : : RegularExpression : : MatchVec * out_matches = nullptr ) ; <nl> mmm a / dbms / include / DB / Storages / MergeTree / MergeTreeBlockOutputStream . h <nl> ppp b / dbms / include / DB / Storages / MergeTree / MergeTreeBlockOutputStream . h <nl> class MergeTreeBlockOutputStream : public IBlockOutputStream <nl> auto part_blocks = storage . writer . splitBlockIntoParts ( block ) ; <nl> for ( auto & current_block : part_blocks ) <nl> { <nl> - UInt64 temp_index = storage . increment . get ( ) ; <nl> + Int64 temp_index = storage . increment . get ( ) ; <nl> MergeTreeData : : MutableDataPartPtr part = storage . writer . writeTempPart ( current_block , temp_index ) ; <nl> storage . data . renameTempPartAndAdd ( part , & storage . increment ) ; <nl> <nl> mmm a / dbms / include / DB / Storages / MergeTree / MergeTreeData . h <nl> ppp b / dbms / include / DB / Storages / MergeTree / MergeTreeData . h <nl> class MergeTreeData : public ITableDeclaration <nl> | | mode = = Mode : : Aggregating ; <nl> } <nl> <nl> - UInt64 getMaxDataPartIndex ( ) ; <nl> + Int64 getMaxDataPartIndex ( ) ; <nl> <nl> std : : string getTableName ( ) const override <nl> { <nl> mmm a / dbms / include / DB / Storages / MergeTree / MergeTreeDataWriter . h <nl> ppp b / dbms / include / DB / Storages / MergeTree / MergeTreeDataWriter . h <nl> class MergeTreeDataWriter <nl> * temp_index - значение left и right для нового куска . Можно будет изменить при переименовании . <nl> * Возвращает кусок с именем , начинающимся с tmp_ , еще не добавленный в MergeTreeData . <nl> * / <nl> - MergeTreeData : : MutableDataPartPtr writeTempPart ( BlockWithDateInterval & block , UInt64 temp_index ) ; <nl> + MergeTreeData : : MutableDataPartPtr writeTempPart ( BlockWithDateInterval & block , Int64 temp_index ) ; <nl> <nl> private : <nl> MergeTreeData & data ; <nl> mmm a / dbms / include / DB / Storages / MergeTree / MergedBlockOutputStream . h <nl> ppp b / dbms / include / DB / Storages / MergeTree / MergedBlockOutputStream . h <nl> <nl> <nl> namespace DB <nl> { <nl> + <nl> + <nl> class IMergedBlockOutputStream : public IBlockOutputStream <nl> { <nl> public : <nl> class IMergedBlockOutputStream : public IBlockOutputStream <nl> CompressionMethod compression_method ; <nl> } ; <nl> <nl> - / * * Для записи одного куска . Данные уже отсортированы , относятся к одному месяцу , и пишутся в один кускок . <nl> + <nl> + / * * Для записи одного куска . <nl> + * Данные относятся к одному месяцу , и пишутся в один кускок . <nl> * / <nl> class MergedBlockOutputStream : public IMergedBlockOutputStream <nl> { <nl> class MergedBlockOutputStream : public IMergedBlockOutputStream <nl> } <nl> } <nl> <nl> + / / / Если данные заранее отсортированы . <nl> void write ( const Block & block ) override <nl> { <nl> - size_t rows = block . rows ( ) ; <nl> - <nl> - / / / Сначала пишем индекс . Индекс содержит значение Primary Key для каждой index_granularity строки . <nl> - typedef std : : vector < const ColumnWithTypeAndName * > PrimaryColumns ; <nl> - PrimaryColumns primary_columns ; <nl> - <nl> - for ( const auto & descr : storage . getSortDescription ( ) ) <nl> - primary_columns . push_back ( <nl> - ! descr . column_name . empty ( ) <nl> - ? & block . getByName ( descr . column_name ) <nl> - : & block . getByPosition ( descr . column_number ) ) ; <nl> - <nl> - for ( size_t i = index_offset ; i < rows ; i + = storage . index_granularity ) <nl> - { <nl> - for ( PrimaryColumns : : const_iterator it = primary_columns . begin ( ) ; it ! = primary_columns . end ( ) ; + + it ) <nl> - { <nl> - if ( storage . mode ! = MergeTreeData : : Unsorted ) <nl> - index_vec . push_back ( ( * ( * it ) - > column ) [ i ] ) ; <nl> - <nl> - ( * it ) - > type - > serializeBinary ( index_vec . back ( ) , * index_stream ) ; <nl> - } <nl> - <nl> - + + marks_count ; <nl> - } <nl> - <nl> - / / / Множество записанных столбцов со смещениями , чтобы не писать общие для вложенных структур столбцы несколько раз <nl> - OffsetColumns offset_columns ; <nl> - <nl> - / / / Теперь пишем данные . <nl> - for ( const auto & it : columns_list ) <nl> - { <nl> - const ColumnWithTypeAndName & column = block . getByName ( it . name ) ; <nl> - writeData ( column . name , * column . type , * column . column , offset_columns ) ; <nl> - } <nl> + writeImpl ( block , nullptr ) ; <nl> + } <nl> <nl> - size_t written_for_last_mark = ( storage . index_granularity - index_offset + rows ) % storage . index_granularity ; <nl> - index_offset = ( storage . index_granularity - written_for_last_mark ) % storage . index_granularity ; <nl> + / * * Если данные не отсортированы , но мы заранее вычислили перестановку , после которой они станут сортированными . <nl> + * Этот метод используется для экономии оперативки , так как не нужно держать одновременно два блока - исходный и отсортированный . <nl> + * / <nl> + void writeWithPermutation ( const Block & block , const IColumn : : Permutation * permutation ) <nl> + { <nl> + writeImpl ( block , permutation ) ; <nl> } <nl> <nl> void writeSuffix ( ) override <nl> class MergedBlockOutputStream : public IMergedBlockOutputStream <nl> } <nl> } <nl> <nl> + / * * Если задана permutation , то переставляет значения в столбцах при записи . <nl> + * Это нужно , чтобы не держать целый блок в оперативке для его сортировки . <nl> + * / <nl> + void writeImpl ( const Block & block , const IColumn : : Permutation * permutation ) <nl> + { <nl> + size_t rows = block . rows ( ) ; <nl> + <nl> + / / / Множество записанных столбцов со смещениями , чтобы не писать общие для вложенных структур столбцы несколько раз <nl> + OffsetColumns offset_columns ; <nl> + <nl> + auto sort_description = storage . getSortDescription ( ) ; <nl> + <nl> + / / / Сюда будем складывать столбцы , относящиеся к Primary Key , чтобы потом записать индекс . <nl> + std : : vector < ColumnWithTypeAndName > primary_columns ( sort_description . size ( ) ) ; <nl> + std : : map < String , size_t > primary_columns_name_to_position ; <nl> + <nl> + for ( size_t i = 0 , size = sort_description . size ( ) ; i < size ; + + i ) <nl> + { <nl> + const auto & descr = sort_description [ i ] ; <nl> + <nl> + String name = ! descr . column_name . empty ( ) <nl> + ? descr . column_name <nl> + : block . getByPosition ( descr . column_number ) . name ; <nl> + <nl> + if ( ! primary_columns_name_to_position . emplace ( name , i ) . second ) <nl> + throw Exception ( " Primary key contains duplicate columns " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> + <nl> + primary_columns [ i ] = ! descr . column_name . empty ( ) <nl> + ? block . getByName ( descr . column_name ) <nl> + : block . getByPosition ( descr . column_number ) ; <nl> + <nl> + / / / Столбцы первичного ключа переупорядочиваем заранее и складываем в primary_columns . <nl> + if ( permutation ) <nl> + primary_columns [ i ] . column = primary_columns [ i ] . column - > permute ( * permutation , 0 ) ; <nl> + } <nl> + <nl> + / / / Теперь пишем данные . <nl> + for ( const auto & it : columns_list ) <nl> + { <nl> + const ColumnWithTypeAndName & column = block . getByName ( it . name ) ; <nl> + <nl> + if ( permutation ) <nl> + { <nl> + auto primary_column_it = primary_columns_name_to_position . find ( it . name ) ; <nl> + if ( primary_columns_name_to_position . end ( ) ! = primary_column_it ) <nl> + { <nl> + writeData ( column . name , * column . type , * primary_columns [ primary_column_it - > second ] . column , offset_columns ) ; <nl> + } <nl> + else <nl> + { <nl> + / / / Столбцы , не входящие в первичный ключ , переупорядочиваем здесь ; затем результат освобождается - для экономии оперативки . <nl> + ColumnPtr permutted_column = column . column - > permute ( * permutation , 0 ) ; <nl> + writeData ( column . name , * column . type , * permutted_column , offset_columns ) ; <nl> + } <nl> + } <nl> + else <nl> + { <nl> + writeData ( column . name , * column . type , * column . column , offset_columns ) ; <nl> + } <nl> + } <nl> + <nl> + / / / Пишем индекс . Индекс содержит значение Primary Key для каждой index_granularity строки . <nl> + for ( size_t i = index_offset ; i < rows ; i + = storage . index_granularity ) <nl> + { <nl> + if ( storage . mode ! = MergeTreeData : : Unsorted ) <nl> + { <nl> + for ( const auto & primary_column : primary_columns ) <nl> + { <nl> + index_vec . push_back ( ( * primary_column . column ) [ i ] ) ; <nl> + primary_column . type - > serializeBinary ( index_vec . back ( ) , * index_stream ) ; <nl> + } <nl> + } <nl> + <nl> + + + marks_count ; <nl> + } <nl> + <nl> + size_t written_for_last_mark = ( storage . index_granularity - index_offset + rows ) % storage . index_granularity ; <nl> + index_offset = ( storage . index_granularity - written_for_last_mark ) % storage . index_granularity ; <nl> + } <nl> + <nl> private : <nl> NamesAndTypesList columns_list ; <nl> String part_path ; <nl> mmm a / dbms / include / DB / Storages / MergeTree / ReplicatedMergeTreeBlockOutputStream . h <nl> ppp b / dbms / include / DB / Storages / MergeTree / ReplicatedMergeTreeBlockOutputStream . h <nl> class ReplicatedMergeTreeBlockOutputStream : public IBlockOutputStream <nl> <nl> AbandonableLockInZooKeeper block_number_lock = storage . allocateBlockNumber ( month_name ) ; <nl> <nl> - UInt64 part_number = block_number_lock . getNumber ( ) ; <nl> + Int64 part_number = block_number_lock . getNumber ( ) ; <nl> <nl> MergeTreeData : : MutableDataPartPtr part = storage . writer . writeTempPart ( current_block , part_number ) ; <nl> String part_name = ActiveDataPartSet : : getPartName ( part - > left_date , part - > right_date , part - > left , part - > right , part - > level ) ; <nl> mmm a / dbms / include / DB / Storages / StorageLog . h <nl> ppp b / dbms / include / DB / Storages / StorageLog . h <nl> friend class LogBlockOutputStream ; <nl> } ; <nl> typedef std : : map < String , ColumnData > Files_t ; <nl> <nl> - Files_t & getFiles ( ) { return files ; } <nl> - <nl> bool checkData ( ) const override ; <nl> <nl> protected : <nl> friend class LogBlockOutputStream ; <nl> size_t max_compress_block_size ; <nl> <nl> protected : <nl> - FileChecker < StorageLog > file_checker ; <nl> + FileChecker file_checker ; <nl> <nl> private : <nl> / * * Для обычных столбцов , в засечках указано количество строчек в блоке . <nl> mmm a / dbms / include / DB / Storages / StorageReplicatedMergeTree . h <nl> ppp b / dbms / include / DB / Storages / StorageReplicatedMergeTree . h <nl> class StorageReplicatedMergeTree : public IStorage <nl> * / <nl> void waitForReplicaToProcessLogEntry ( const String & replica_name , const LogEntry & entry ) ; <nl> <nl> - / / / Преобразовать число в строку формате суффиксов автоинкрементных нод в ZooKeeper . <nl> - static String padIndex ( UInt64 index ) <nl> + / * * Преобразовать число в строку формате суффиксов автоинкрементных нод в ZooKeeper . <nl> + * Поддерживаются также отрицательные числа - для них имя ноды выглядит несколько глупо <nl> + * и не соответствует никакой автоинкрементной ноде в ZK . <nl> + * / <nl> + static String padIndex ( Int64 index ) <nl> { <nl> String index_str = toString ( index ) ; <nl> return std : : string ( 10 - index_str . size ( ) , ' 0 ' ) + index_str ; <nl> new file mode 100644 <nl> index 00000000000 . . d12642e0963 <nl> mmm / dev / null <nl> ppp b / dbms / include / DB / Storages / StorageStripeLog . h <nl> <nl> + # pragma once <nl> + <nl> + # include < map > <nl> + # include < Poco / File . h > <nl> + <nl> + # include < DB / Storages / IStorage . h > <nl> + # include < DB / Common / FileChecker . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + / * * Реализует хранилище , подходящее для маленьких кусочков лога . <nl> + * При этом , хранит все столбцы в одном файле формата Native , с расположенным рядом индексом . <nl> + * / <nl> + class StorageStripeLog : public IStorage <nl> + { <nl> + friend class StripeLogBlockInputStream ; <nl> + friend class StripeLogBlockOutputStream ; <nl> + <nl> + public : <nl> + / * * Подцепить таблицу с соответствующим именем , по соответствующему пути ( с / на конце ) , <nl> + * ( корректность имён и путей не проверяется ) <nl> + * состоящую из указанных столбцов . <nl> + * Если не указано attach - создать директорию , если её нет . <nl> + * / <nl> + static StoragePtr create ( <nl> + const std : : string & path_ , <nl> + const std : : string & name_ , <nl> + NamesAndTypesListPtr columns_ , <nl> + const NamesAndTypesList & materialized_columns_ , <nl> + const NamesAndTypesList & alias_columns_ , <nl> + const ColumnDefaults & column_defaults_ , <nl> + bool attach , <nl> + size_t max_compress_block_size_ = DEFAULT_MAX_COMPRESS_BLOCK_SIZE ) ; <nl> + <nl> + std : : string getName ( ) const override { return " StripeLog " ; } <nl> + std : : string getTableName ( ) const override { return name ; } <nl> + <nl> + const NamesAndTypesList & getColumnsListImpl ( ) const override { return * columns ; } <nl> + <nl> + BlockInputStreams read ( <nl> + const Names & column_names , <nl> + ASTPtr query , <nl> + const Context & context , <nl> + const Settings & settings , <nl> + QueryProcessingStage : : Enum & processed_stage , <nl> + size_t max_block_size = DEFAULT_BLOCK_SIZE , <nl> + unsigned threads = 1 ) override ; <nl> + <nl> + BlockOutputStreamPtr write ( ASTPtr query ) override ; <nl> + <nl> + void rename ( const String & new_path_to_db , const String & new_database_name , const String & new_table_name ) override ; <nl> + <nl> + bool checkData ( ) const override ; <nl> + <nl> + / / / Данные файла . <nl> + struct ColumnData <nl> + { <nl> + Poco : : File data_file ; <nl> + } ; <nl> + typedef std : : map < String , ColumnData > Files_t ; <nl> + <nl> + std : : string full_path ( ) { return path + escapeForFileName ( name ) + ' / ' ; } <nl> + <nl> + private : <nl> + String path ; <nl> + String name ; <nl> + NamesAndTypesListPtr columns ; <nl> + <nl> + size_t max_compress_block_size ; <nl> + <nl> + FileChecker file_checker ; <nl> + Poco : : RWLock rwlock ; <nl> + <nl> + Logger * log ; <nl> + <nl> + StorageStripeLog ( <nl> + const std : : string & path_ , <nl> + const std : : string & name_ , <nl> + NamesAndTypesListPtr columns_ , <nl> + const NamesAndTypesList & materialized_columns_ , <nl> + const NamesAndTypesList & alias_columns_ , <nl> + const ColumnDefaults & column_defaults_ , <nl> + bool attach , <nl> + size_t max_compress_block_size_ ) ; <nl> + } ; <nl> + <nl> + } <nl> mmm a / dbms / include / DB / Storages / StorageTinyLog . h <nl> ppp b / dbms / include / DB / Storages / StorageTinyLog . h <nl> friend class TinyLogBlockOutputStream ; <nl> } ; <nl> typedef std : : map < String , ColumnData > Files_t ; <nl> <nl> - Files_t & getFiles ( ) ; <nl> - <nl> std : : string full_path ( ) { return path + escapeForFileName ( name ) + ' / ' ; } <nl> <nl> private : <nl> friend class TinyLogBlockOutputStream ; <nl> <nl> Files_t files ; <nl> <nl> - FileChecker < StorageTinyLog > file_checker ; <nl> + FileChecker file_checker ; <nl> <nl> Logger * log ; <nl> <nl> mmm a / dbms / src / DataStreams / NativeBlockInputStream . cpp <nl> ppp b / dbms / src / DataStreams / NativeBlockInputStream . cpp <nl> <nl> <nl> # include < DB / IO / ReadHelpers . h > <nl> # include < DB / IO / VarInt . h > <nl> + # include < DB / IO / CompressedReadBufferFromFile . h > <nl> <nl> # include < DB / Columns / ColumnArray . h > <nl> # include < DB / DataTypes / DataTypeArray . h > <nl> namespace DB <nl> { <nl> <nl> <nl> + NativeBlockInputStream : : NativeBlockInputStream ( <nl> + ReadBuffer & istr_ , UInt64 server_revision_ , <nl> + bool use_index_ , <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_block_it_ , <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_block_end_ ) <nl> + : istr ( istr_ ) , server_revision ( server_revision_ ) , <nl> + use_index ( use_index_ ) , index_block_it ( index_block_it_ ) , index_block_end ( index_block_end_ ) <nl> + { <nl> + if ( use_index ) <nl> + { <nl> + istr_concrete = typeid_cast < CompressedReadBufferFromFile * > ( & istr ) ; <nl> + if ( ! istr_concrete ) <nl> + throw Exception ( " When need to use index for NativeBlockInputStream , istr must be CompressedReadBufferFromFile . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + <nl> + index_column_it = index_block_it - > columns . begin ( ) ; <nl> + } <nl> + } <nl> + <nl> + <nl> void NativeBlockInputStream : : readData ( const IDataType & type , IColumn & column , ReadBuffer & istr , size_t rows ) <nl> { <nl> / * * Для массивов требуется сначала десериализовать смещения , а потом значения . <nl> Block NativeBlockInputStream : : readImpl ( ) <nl> <nl> const DataTypeFactory & data_type_factory = DataTypeFactory : : instance ( ) ; <nl> <nl> + if ( use_index & & index_block_it = = index_block_end ) <nl> + return res ; <nl> + <nl> if ( istr . eof ( ) ) <nl> + { <nl> + if ( use_index ) <nl> + throw Exception ( " Input doesn ' t contain all data for index . " , ErrorCodes : : CANNOT_READ_ALL_DATA ) ; <nl> + <nl> return res ; <nl> + } <nl> <nl> / / / Дополнительная информация о блоке . <nl> if ( server_revision > = DBMS_MIN_REVISION_WITH_BLOCK_INFO ) <nl> Block NativeBlockInputStream : : readImpl ( ) <nl> / / / Размеры <nl> size_t columns = 0 ; <nl> size_t rows = 0 ; <nl> - readVarUInt ( columns , istr ) ; <nl> - readVarUInt ( rows , istr ) ; <nl> + <nl> + if ( ! use_index ) <nl> + { <nl> + readVarUInt ( columns , istr ) ; <nl> + readVarUInt ( rows , istr ) ; <nl> + } <nl> + else <nl> + { <nl> + columns = index_block_it - > num_columns ; <nl> + rows = index_block_it - > num_rows ; <nl> + } <nl> <nl> for ( size_t i = 0 ; i < columns ; + + i ) <nl> { <nl> + if ( use_index ) <nl> + { <nl> + / / / Если текущая позиция и так какая требуется , то реального seek - а не происходит . <nl> + istr_concrete - > seek ( index_column_it - > location . offset_in_compressed_file , index_column_it - > location . offset_in_decompressed_block ) ; <nl> + } <nl> + <nl> ColumnWithTypeAndName column ; <nl> <nl> / / / Имя <nl> - readStringBinary ( column . name , istr ) ; <nl> + readBinary ( column . name , istr ) ; <nl> <nl> / / / Тип <nl> String type_name ; <nl> - readStringBinary ( type_name , istr ) ; <nl> + readBinary ( type_name , istr ) ; <nl> column . type = data_type_factory . get ( type_name ) ; <nl> <nl> + if ( use_index ) <nl> + { <nl> + / / / Индекс позволяет сделать проверки . <nl> + if ( index_column_it - > name ! = column . name ) <nl> + throw Exception ( " Index points to column with wrong name : corrupted index or data " , ErrorCodes : : INCORRECT_INDEX ) ; <nl> + if ( index_column_it - > type ! = type_name ) <nl> + throw Exception ( " Index points to column with wrong type : corrupted index or data " , ErrorCodes : : INCORRECT_INDEX ) ; <nl> + } <nl> + <nl> / / / Данные <nl> column . column = column . type - > createColumn ( ) ; <nl> readData ( * column . type , * column . column , istr , rows ) ; <nl> <nl> res . insert ( column ) ; <nl> + <nl> + if ( use_index ) <nl> + + + index_column_it ; <nl> + } <nl> + <nl> + if ( use_index ) <nl> + { <nl> + if ( index_column_it ! = index_block_it - > columns . end ( ) ) <nl> + throw Exception ( " Inconsistent index : not all columns were read " , ErrorCodes : : INCORRECT_INDEX ) ; <nl> + <nl> + + + index_block_it ; <nl> + if ( index_block_it ! = index_block_end ) <nl> + index_column_it = index_block_it - > columns . begin ( ) ; <nl> } <nl> <nl> return res ; <nl> } <nl> <nl> + <nl> + void IndexForNativeFormat : : read ( ReadBuffer & istr , const NameSet & required_columns ) <nl> + { <nl> + while ( ! istr . eof ( ) ) <nl> + { <nl> + blocks . emplace_back ( ) ; <nl> + IndexOfBlockForNativeFormat & block = blocks . back ( ) ; <nl> + <nl> + readVarUInt ( block . num_columns , istr ) ; <nl> + readVarUInt ( block . num_rows , istr ) ; <nl> + <nl> + if ( block . num_columns < required_columns . size ( ) ) <nl> + throw Exception ( " Index contain less than required columns " , ErrorCodes : : INCORRECT_INDEX ) ; <nl> + <nl> + for ( size_t i = 0 ; i < block . num_columns ; + + i ) <nl> + { <nl> + IndexOfOneColumnForNativeFormat column_index ; <nl> + <nl> + readBinary ( column_index . name , istr ) ; <nl> + readBinary ( column_index . type , istr ) ; <nl> + readBinary ( column_index . location . offset_in_compressed_file , istr ) ; <nl> + readBinary ( column_index . location . offset_in_decompressed_block , istr ) ; <nl> + <nl> + if ( required_columns . count ( column_index . name ) ) <nl> + block . columns . push_back ( std : : move ( column_index ) ) ; <nl> + } <nl> + <nl> + if ( block . columns . size ( ) < required_columns . size ( ) ) <nl> + throw Exception ( " Index contain less than required columns " , ErrorCodes : : INCORRECT_INDEX ) ; <nl> + if ( block . columns . size ( ) > required_columns . size ( ) ) <nl> + throw Exception ( " Index contain duplicate columns " , ErrorCodes : : INCORRECT_INDEX ) ; <nl> + <nl> + block . num_columns = block . columns . size ( ) ; <nl> + } <nl> + } <nl> + <nl> + <nl> } <nl> mmm a / dbms / src / DataStreams / NativeBlockOutputStream . cpp <nl> ppp b / dbms / src / DataStreams / NativeBlockOutputStream . cpp <nl> <nl> <nl> # include < DB / IO / WriteHelpers . h > <nl> # include < DB / IO / VarInt . h > <nl> + # include < DB / IO / CompressedWriteBuffer . h > <nl> <nl> # include < DB / Columns / ColumnConst . h > <nl> # include < DB / Columns / ColumnArray . h > <nl> <nl> # include < DB / DataTypes / DataTypeArray . h > <nl> <nl> + # include < DB / DataStreams / MarkInCompressedFile . h > <nl> # include < DB / DataStreams / NativeBlockOutputStream . h > <nl> <nl> <nl> namespace DB <nl> { <nl> <nl> <nl> + NativeBlockOutputStream : : NativeBlockOutputStream ( <nl> + WriteBuffer & ostr_ , UInt64 client_revision_ , <nl> + WriteBuffer * index_ostr_ ) <nl> + : ostr ( ostr_ ) , client_revision ( client_revision_ ) , <nl> + index_ostr ( index_ostr_ ) <nl> + { <nl> + if ( index_ostr ) <nl> + { <nl> + ostr_concrete = typeid_cast < CompressedWriteBuffer * > ( & ostr ) ; <nl> + if ( ! ostr_concrete ) <nl> + throw Exception ( " When need to write index for NativeBlockOutputStream , ostr must be CompressedWriteBuffer . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + } <nl> + } <nl> + <nl> + <nl> void NativeBlockOutputStream : : writeData ( const IDataType & type , const ColumnPtr & column , WriteBuffer & ostr , size_t offset , size_t limit ) <nl> { <nl> / * * Если есть столбцы - константы - то материализуем их . <nl> void NativeBlockOutputStream : : write ( const Block & block ) <nl> / / / Размеры <nl> size_t columns = block . columns ( ) ; <nl> size_t rows = block . rows ( ) ; <nl> + <nl> writeVarUInt ( columns , ostr ) ; <nl> writeVarUInt ( rows , ostr ) ; <nl> <nl> + / * * Индекс имеет ту же структуру , что и поток с данными . <nl> + * Но вместо значений столбца он содержит засечку , ссылающуюся на место в файле с данными , где находится этот кусочек столбца . <nl> + * / <nl> + if ( index_ostr ) <nl> + { <nl> + writeVarUInt ( columns , * index_ostr ) ; <nl> + writeVarUInt ( rows , * index_ostr ) ; <nl> + } <nl> + <nl> for ( size_t i = 0 ; i < columns ; + + i ) <nl> { <nl> + / / / Для индекса . <nl> + MarkInCompressedFile mark ; <nl> + <nl> + if ( index_ostr ) <nl> + { <nl> + ostr_concrete - > next ( ) ; / / / Заканчиваем сжатый блок . <nl> + mark . offset_in_compressed_file = ostr_concrete - > getCompressedBytes ( ) ; <nl> + mark . offset_in_decompressed_block = ostr_concrete - > getRemainingBytes ( ) ; <nl> + } <nl> + <nl> const ColumnWithTypeAndName & column = block . getByPosition ( i ) ; <nl> <nl> / / / Имя <nl> void NativeBlockOutputStream : : write ( const Block & block ) <nl> <nl> / / / Данные <nl> writeData ( * column . type , column . column , ostr , 0 , 0 ) ; <nl> + <nl> + if ( index_ostr ) <nl> + { <nl> + writeStringBinary ( column . name , * index_ostr ) ; <nl> + writeStringBinary ( column . type - > getName ( ) , * index_ostr ) ; <nl> + <nl> + writeBinary ( mark . offset_in_compressed_file , * index_ostr ) ; <nl> + writeBinary ( mark . offset_in_decompressed_block , * index_ostr ) ; <nl> + } <nl> } <nl> } <nl> <nl> mmm a / dbms / src / DataTypes / DataTypeString . cpp <nl> ppp b / dbms / src / DataTypes / DataTypeString . cpp <nl> void DataTypeString : : deserializeBinary ( IColumn & column , ReadBuffer & istr , size <nl> ColumnString : : Chars_t & data = column_string . getChars ( ) ; <nl> ColumnString : : Offsets_t & offsets = column_string . getOffsets ( ) ; <nl> <nl> - / / / Выбрано наугад . <nl> - constexpr auto avg_value_size_hint_reserve_multiplier = 1 . 2 ; <nl> + double avg_chars_size ; <nl> <nl> - double avg_chars_size = ( avg_value_size_hint & & avg_value_size_hint > sizeof ( offsets [ 0 ] ) <nl> - ? ( avg_value_size_hint - sizeof ( offsets [ 0 ] ) ) * avg_value_size_hint_reserve_multiplier <nl> - : DBMS_APPROX_STRING_SIZE ) ; <nl> + if ( avg_value_size_hint & & avg_value_size_hint > sizeof ( offsets [ 0 ] ) ) <nl> + { <nl> + / / / Выбрано наугад . <nl> + constexpr auto avg_value_size_hint_reserve_multiplier = 1 . 2 ; <nl> + <nl> + avg_chars_size = ( avg_value_size_hint - sizeof ( offsets [ 0 ] ) ) * avg_value_size_hint_reserve_multiplier ; <nl> + } <nl> + else <nl> + { <nl> + / * * Небольшая эвристика для оценки того , что в столбце много пустых строк . <nl> + * В этом случае , для экономии оперативки , будем говорить , что средний размер значения маленький . <nl> + * / <nl> + if ( istr . position ( ) + sizeof ( UInt32 ) < = istr . buffer ( ) . end ( ) <nl> + & & * reinterpret_cast < const UInt32 * > ( istr . position ( ) ) = = 0 ) / / / Первые 4 строки находятся в буфере и являются пустыми . <nl> + { <nl> + avg_chars_size = 1 ; <nl> + } <nl> + else <nl> + avg_chars_size = DBMS_APPROX_STRING_SIZE ; <nl> + } <nl> <nl> data . reserve ( data . size ( ) + std : : ceil ( limit * avg_chars_size ) ) ; <nl> <nl> mmm a / dbms / src / Interpreters / DictionaryFactory . cpp <nl> ppp b / dbms / src / Interpreters / DictionaryFactory . cpp <nl> DictionaryPtr DictionaryFactory : : create ( const std : : string & name , Poco : : Util : : Ab <nl> config . keys ( layout_prefix , keys ) ; <nl> if ( keys . size ( ) ! = 1 ) <nl> throw Exception { <nl> - " Element dictionary . layout should have exactly one child element " , <nl> + name + " : element dictionary . layout should have exactly one child element " , <nl> ErrorCodes : : EXCESSIVE_ELEMENT_IN_CONFIG <nl> } ; <nl> <nl> const DictionaryStructure dict_struct { config , config_prefix + " . structure " } ; <nl> <nl> auto source_ptr = DictionarySourceFactory : : instance ( ) . create ( <nl> - config , config_prefix + " . source " , dict_struct , context ) ; <nl> + name , config , config_prefix + " . source " , dict_struct , context ) ; <nl> <nl> const DictionaryLifetime dict_lifetime { config , config_prefix + " . lifetime " } ; <nl> <nl> DictionaryPtr DictionaryFactory : : create ( const std : : string & name , Poco : : Util : : Ab <nl> { <nl> if ( dict_struct . range_min . empty ( ) | | dict_struct . range_min . empty ( ) ) <nl> throw Exception { <nl> - " Dictionary of layout ' range_hashed ' requires . structure . range_min and . structure . range_max " , <nl> + name + " : dictionary of layout ' range_hashed ' requires . structure . range_min and . structure . range_max " , <nl> ErrorCodes : : BAD_ARGUMENTS <nl> } ; <nl> <nl> DictionaryPtr DictionaryFactory : : create ( const std : : string & name , Poco : : Util : : Ab <nl> { <nl> if ( ! dict_struct . range_min . empty ( ) | | ! dict_struct . range_min . empty ( ) ) <nl> throw Exception { <nl> - " Elements . structure . range_min and . structure . range_max should be defined only " <nl> + name + " : elements . structure . range_min and . structure . range_max should be defined only " <nl> " for a dictionary of layout ' range_hashed ' " , <nl> - ErrorCodes : : BAD_ARGUMENTS } ; <nl> + ErrorCodes : : BAD_ARGUMENTS <nl> + } ; <nl> <nl> if ( " flat " = = layout_type ) <nl> { <nl> DictionaryPtr DictionaryFactory : : create ( const std : : string & name , Poco : : Util : : Ab <nl> const auto size = config . getInt ( layout_prefix + " . cache . size_in_cells " ) ; <nl> if ( size = = 0 ) <nl> throw Exception { <nl> - " Dictionary of layout ' cache ' cannot have 0 cells " , <nl> - ErrorCodes : : TOO_SMALL_BUFFER_SIZE } ; <nl> + name + " : dictionary of layout ' cache ' cannot have 0 cells " , <nl> + ErrorCodes : : TOO_SMALL_BUFFER_SIZE <nl> + } ; <nl> <nl> if ( require_nonempty ) <nl> throw Exception { <nl> - " Dictionary of layout ' cache ' cannot have ' require_nonempty ' attribute set " , <nl> - ErrorCodes : : BAD_ARGUMENTS } ; <nl> + name + " : dictionary of layout ' cache ' cannot have ' require_nonempty ' attribute set " , <nl> + ErrorCodes : : BAD_ARGUMENTS <nl> + } ; <nl> <nl> return std : : make_unique < CacheDictionary > ( name , dict_struct , std : : move ( source_ptr ) , dict_lifetime , size ) ; <nl> } <nl> } <nl> <nl> throw Exception { <nl> - " Unknown dictionary layout type : " + layout_type , <nl> + name + " : unknown dictionary layout type : " + layout_type , <nl> ErrorCodes : : UNKNOWN_ELEMENT_IN_CONFIG <nl> } ; <nl> } ; <nl> mmm a / dbms / src / Interpreters / ExpressionAnalyzer . cpp <nl> ppp b / dbms / src / Interpreters / ExpressionAnalyzer . cpp <nl> void ExpressionAnalyzer : : analyzeAggregation ( ) <nl> <nl> void ExpressionAnalyzer : : initGlobalSubqueriesAndExternalTables ( ) <nl> { <nl> + / / / Преобразует GLOBAL - подзапросы во внешние таблицы ; кладёт их в словарь external_tables : name - > StoragePtr . <nl> initGlobalSubqueries ( ast ) ; <nl> <nl> - / / / Создаёт словарь external_tables : name - > StoragePtr . <nl> + / / / Добавляет уже существующие внешние таблицы ( не подзапросы ) в словарь external_tables . <nl> findExternalTables ( ast ) ; <nl> } <nl> <nl> static SharedPtr < InterpreterSelectQuery > interpretSubquery ( <nl> <nl> void ExpressionAnalyzer : : addExternalStorage ( ASTPtr & subquery_or_table_name ) <nl> { <nl> - / / / Сгенерируем имя для внешней таблицы . <nl> - while ( context . tryGetExternalTable ( " _data " + toString ( external_table_id ) ) ) <nl> - + + external_table_id ; <nl> - <nl> if ( const ASTIdentifier * table = typeid_cast < const ASTIdentifier * > ( & * subquery_or_table_name ) ) <nl> { <nl> / / / Если это уже внешняя таблица , ничего заполять не нужно . Просто запоминаем ее наличие . <nl> void ExpressionAnalyzer : : addExternalStorage ( ASTPtr & subquery_or_table_name ) <nl> } <nl> } <nl> <nl> + / / / Сгенерируем имя для внешней таблицы . <nl> + String external_table_name = " _data " + toString ( external_table_id ) ; <nl> + while ( context . tryGetExternalTable ( external_table_name ) <nl> + | | external_tables . count ( external_table_name ) ) <nl> + { <nl> + + + external_table_id ; <nl> + external_table_name = " _data " + toString ( external_table_id ) ; <nl> + } <nl> + <nl> SharedPtr < InterpreterSelectQuery > interpreter = interpretSubquery ( subquery_or_table_name , context , subquery_depth + 1 ) ; <nl> <nl> Block sample = interpreter - > getSampleBlock ( ) ; <nl> NamesAndTypesListPtr columns = new NamesAndTypesList ( sample . getColumnsList ( ) ) ; <nl> <nl> - String external_table_name = " _data " + toString ( external_table_id ) ; <nl> - <nl> / * * Заменяем подзапрос на имя временной таблицы . <nl> * Именно в таком виде , запрос отправится на удалённый сервер . <nl> * На удалённый сервер отправится эта временная таблица , и на его стороне , <nl> mmm a / dbms / src / Interpreters / loadMetadata . cpp <nl> ppp b / dbms / src / Interpreters / loadMetadata . cpp <nl> static void executeCreateQuery ( const String & query , Context & context , const St <nl> { <nl> if ( const auto id = dynamic_cast < const ASTFunction * > ( ast_create_query . storage . get ( ) ) ) <nl> { <nl> - if ( id - > name = = " TinyLog " ) <nl> + if ( id - > name = = " TinyLog " | | id - > name = = " StripeLog " ) <nl> { <nl> tryLogCurrentException ( __PRETTY_FUNCTION__ ) ; <nl> return ; <nl> mmm a / dbms / src / Interpreters / sortBlock . cpp <nl> ppp b / dbms / src / Interpreters / sortBlock . cpp <nl> void sortBlock ( Block & block , const SortDescription & description , size_t limit ) <nl> } <nl> <nl> <nl> - void stableSortBlock ( Block & block , const SortDescription & description ) <nl> + void stableGetPermutation ( const Block & block , const SortDescription & description , IColumn : : Permutation & out_permutation ) <nl> { <nl> if ( ! block ) <nl> return ; <nl> <nl> size_t size = block . rows ( ) ; <nl> - IColumn : : Permutation perm ( size ) ; <nl> + out_permutation . resize ( size ) ; <nl> for ( size_t i = 0 ; i < size ; + + i ) <nl> - perm [ i ] = i ; <nl> + out_permutation [ i ] = i ; <nl> <nl> ColumnsWithSortDescriptions columns_with_sort_desc ; <nl> <nl> for ( size_t i = 0 , size = description . size ( ) ; i < size ; + + i ) <nl> { <nl> - IColumn * column = ! description [ i ] . column_name . empty ( ) <nl> + const IColumn * column = ! description [ i ] . column_name . empty ( ) <nl> ? block . getByName ( description [ i ] . column_name ) . column <nl> : block . getByPosition ( description [ i ] . column_number ) . column ; <nl> <nl> columns_with_sort_desc . push_back ( std : : make_pair ( column , description [ i ] ) ) ; <nl> } <nl> <nl> - std : : stable_sort ( perm . begin ( ) , perm . end ( ) , PartialSortingLess ( columns_with_sort_desc ) ) ; <nl> + std : : stable_sort ( out_permutation . begin ( ) , out_permutation . end ( ) , PartialSortingLess ( columns_with_sort_desc ) ) ; <nl> + } <nl> + <nl> + <nl> + void stableSortBlock ( Block & block , const SortDescription & description ) <nl> + { <nl> + if ( ! block ) <nl> + return ; <nl> + <nl> + IColumn : : Permutation perm ; <nl> + stableGetPermutation ( block , description , perm ) ; <nl> <nl> size_t columns = block . columns ( ) ; <nl> for ( size_t i = 0 ; i < columns ; + + i ) <nl> mmm a / dbms / src / Storages / MergeTree / ActiveDataPartSet . cpp <nl> ppp b / dbms / src / Storages / MergeTree / ActiveDataPartSet . cpp <nl> size_t ActiveDataPartSet : : size ( ) const <nl> } <nl> <nl> <nl> - String ActiveDataPartSet : : getPartName ( DayNum_t left_date , DayNum_t right_date , UInt64 left_id , UInt64 right_id , UInt64 level ) <nl> + String ActiveDataPartSet : : getPartName ( DayNum_t left_date , DayNum_t right_date , Int64 left_id , Int64 right_id , UInt64 level ) <nl> { <nl> const auto & date_lut = DateLUT : : instance ( ) ; <nl> <nl> String ActiveDataPartSet : : getPartName ( DayNum_t left_date , DayNum_t right_date , U <nl> bool ActiveDataPartSet : : isPartDirectory ( const String & dir_name , Poco : : RegularExpression : : MatchVec * out_matches ) <nl> { <nl> Poco : : RegularExpression : : MatchVec matches ; <nl> - static Poco : : RegularExpression file_name_regexp ( " ^ ( \ \ d { 8 } ) _ ( \ \ d { 8 } ) _ ( \ \ d + ) _ ( \ \ d + ) _ ( \ \ d + ) " ) ; <nl> + static Poco : : RegularExpression file_name_regexp ( " ^ ( \ \ d { 8 } ) _ ( \ \ d { 8 } ) _ ( - ? \ \ d + ) _ ( - ? \ \ d + ) _ ( \ \ d + ) " ) ; <nl> bool res = ( file_name_regexp . match ( dir_name , 0 , matches ) & & 6 = = matches . size ( ) ) ; <nl> if ( out_matches ) <nl> * out_matches = matches ; <nl> void ActiveDataPartSet : : parsePartName ( const String & file_name , Part & part , con <nl> <nl> part . left_date = date_lut . YYYYMMDDToDayNum ( parse < UInt32 > ( file_name . substr ( matches [ 1 ] . offset , matches [ 1 ] . length ) ) ) ; <nl> part . right_date = date_lut . YYYYMMDDToDayNum ( parse < UInt32 > ( file_name . substr ( matches [ 2 ] . offset , matches [ 2 ] . length ) ) ) ; <nl> - part . left = parse < UInt64 > ( file_name . substr ( matches [ 3 ] . offset , matches [ 3 ] . length ) ) ; <nl> - part . right = parse < UInt64 > ( file_name . substr ( matches [ 4 ] . offset , matches [ 4 ] . length ) ) ; <nl> + part . left = parse < Int64 > ( file_name . substr ( matches [ 3 ] . offset , matches [ 3 ] . length ) ) ; <nl> + part . right = parse < Int64 > ( file_name . substr ( matches [ 4 ] . offset , matches [ 4 ] . length ) ) ; <nl> part . level = parse < UInt32 > ( file_name . substr ( matches [ 5 ] . offset , matches [ 5 ] . length ) ) ; <nl> <nl> - part . left_month = date_lut . toFirstDayNumOfMonth ( part . left_date ) ; <nl> - part . right_month = date_lut . toFirstDayNumOfMonth ( part . right_date ) ; <nl> + DayNum_t left_month = date_lut . toFirstDayNumOfMonth ( part . left_date ) ; <nl> + DayNum_t right_month = date_lut . toFirstDayNumOfMonth ( part . right_date ) ; <nl> + <nl> + if ( left_month ! = right_month ) <nl> + throw Exception ( " Part name " + file_name + " contains different months " , ErrorCodes : : BAD_DATA_PART_NAME ) ; <nl> + <nl> + part . month = left_month ; <nl> } <nl> <nl> <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeData . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeData . cpp <nl> MergeTreeData : : MergeTreeData ( <nl> throw Exception ( " Primary key could be empty only for UnsortedMergeTree " , ErrorCodes : : BAD_ARGUMENTS ) ; <nl> } <nl> <nl> - UInt64 MergeTreeData : : getMaxDataPartIndex ( ) <nl> + Int64 MergeTreeData : : getMaxDataPartIndex ( ) <nl> { <nl> - UInt64 max_part_id = 0 ; <nl> + Int64 max_part_id = 0 ; <nl> for ( const auto & part : data_parts ) <nl> max_part_id = std : : max ( max_part_id , part - > right ) ; <nl> <nl> void MergeTreeData : : loadDataParts ( bool skip_sanity_checks ) <nl> while ( curr_jt ! = data_parts . end ( ) ) <nl> { <nl> / / / Куски данных за разные месяцы рассматривать не будем <nl> - if ( ( * curr_jt ) - > left_month ! = ( * curr_jt ) - > right_month <nl> - | | ( * curr_jt ) - > right_month ! = ( * prev_jt ) - > left_month <nl> - | | ( * prev_jt ) - > left_month ! = ( * prev_jt ) - > right_month ) <nl> + if ( ( * curr_jt ) - > month ! = ( * prev_jt ) - > month ) <nl> { <nl> + + prev_jt ; <nl> + + curr_jt ; <nl> MergeTreeData : : DataPartsVector MergeTreeData : : renameTempPartAndReplace ( <nl> <nl> bool obsolete = false ; / / / Покрыт ли part каким - нибудь куском . <nl> DataPartsVector res ; <nl> + <nl> / / / Куски , содержащиеся в part , идут в data_parts подряд , задевая место , куда вставился бы сам part . <nl> DataParts : : iterator it = data_parts . lower_bound ( part ) ; <nl> / / / Пойдем влево . <nl> void MergeTreeData : : renameAndDetachPart ( const DataPartPtr & part , const String & <nl> Strings restored ; <nl> bool error = false ; <nl> <nl> - UInt64 pos = part - > left ; <nl> + Int64 pos = part - > left ; <nl> <nl> if ( it ! = all_data_parts . begin ( ) ) <nl> { <nl> size_t MergeTreeData : : getMaxPartsCountForMonth ( ) <nl> <nl> for ( const auto & part : data_parts ) <nl> { <nl> - if ( part - > left_month = = cur_month ) <nl> + if ( part - > month = = cur_month ) <nl> { <nl> + + cur_count ; <nl> } <nl> else <nl> { <nl> - cur_month = part - > left_month ; <nl> + cur_month = part - > month ; <nl> cur_count = 1 ; <nl> } <nl> <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeDataMerger . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeDataMerger . cpp <nl> bool MergeTreeDataMerger : : selectPartsToMerge ( MergeTreeData : : DataPartsVector & pa <nl> continue ; <nl> } <nl> <nl> - / / / Кусок в одном месяце . <nl> - if ( first_part - > left_month ! = first_part - > right_month ) <nl> - { <nl> - LOG_WARNING ( log , " Part " < < first_part - > name < < " spans more than one month " ) ; <nl> - continue ; <nl> - } <nl> - <nl> / / / Самый длинный валидный отрезок , начинающийся здесь . <nl> size_t cur_longest_max = - 1U ; <nl> size_t cur_longest_min = - 1U ; <nl> bool MergeTreeDataMerger : : selectPartsToMerge ( MergeTreeData : : DataPartsVector & pa <nl> size_t cur_sum = first_part - > size_in_bytes ; <nl> int cur_len = 1 ; <nl> <nl> - DayNum_t month = first_part - > left_month ; <nl> - UInt64 cur_id = first_part - > right ; <nl> + DayNum_t month = first_part - > month ; <nl> + Int64 cur_id = first_part - > right ; <nl> <nl> / / / Этот месяц кончился хотя бы день назад . <nl> bool is_old_month = now_day - now_month > = 1 & & now_month > month ; <nl> bool MergeTreeDataMerger : : selectPartsToMerge ( MergeTreeData : : DataPartsVector & pa <nl> const MergeTreeData : : DataPartPtr & last_part = * jt ; <nl> <nl> / / / Кусок разрешено сливать с предыдущим , и в одном правильном месяце . <nl> - if ( last_part - > left_month ! = last_part - > right_month | | <nl> - last_part - > left_month ! = month | | <nl> - ! can_merge ( prev_part , last_part ) ) <nl> + if ( last_part - > month ! = month <nl> + | | ! can_merge ( prev_part , last_part ) ) <nl> { <nl> break ; <nl> } <nl> mmm a / dbms / src / Storages / MergeTree / MergeTreeDataWriter . cpp <nl> ppp b / dbms / src / Storages / MergeTree / MergeTreeDataWriter . cpp <nl> BlocksWithDateIntervals MergeTreeDataWriter : : splitBlockIntoParts ( const Block & b <nl> return res ; <nl> } <nl> <nl> - MergeTreeData : : MutableDataPartPtr MergeTreeDataWriter : : writeTempPart ( BlockWithDateInterval & block_with_dates , UInt64 temp_index ) <nl> + MergeTreeData : : MutableDataPartPtr MergeTreeDataWriter : : writeTempPart ( BlockWithDateInterval & block_with_dates , Int64 temp_index ) <nl> { <nl> Block & block = block_with_dates . block ; <nl> UInt16 min_date = block_with_dates . min_date ; <nl> MergeTreeData : : MutableDataPartPtr MergeTreeDataWriter : : writeTempPart ( BlockWithDa <nl> <nl> const auto & date_lut = DateLUT : : instance ( ) ; <nl> <nl> + DayNum_t min_month = date_lut . toFirstDayNumOfMonth ( DayNum_t ( min_date ) ) ; <nl> + DayNum_t max_month = date_lut . toFirstDayNumOfMonth ( DayNum_t ( max_date ) ) ; <nl> + <nl> + if ( min_month ! = max_month ) <nl> + throw Exception ( " Logical error : part spans more than one month . " ) ; <nl> + <nl> size_t part_size = ( block . rows ( ) + data . index_granularity - 1 ) / data . index_granularity ; <nl> <nl> String tmp_part_name = " tmp_ " + ActiveDataPartSet : : getPartName ( <nl> MergeTreeData : : MutableDataPartPtr MergeTreeDataWriter : : writeTempPart ( BlockWithDa <nl> SortDescription sort_descr = data . getSortDescription ( ) ; <nl> <nl> / / / Сортируем . <nl> + IColumn : : Permutation * perm_ptr = nullptr ; <nl> + IColumn : : Permutation perm ; <nl> if ( data . mode ! = MergeTreeData : : Unsorted ) <nl> - stableSortBlock ( block , sort_descr ) ; <nl> + { <nl> + stableGetPermutation ( block , sort_descr , perm ) ; <nl> + perm_ptr = & perm ; <nl> + } <nl> <nl> NamesAndTypesList columns = data . getColumnsList ( ) . filter ( block . getColumnsList ( ) . getNames ( ) ) ; <nl> MergedBlockOutputStream out ( data , part_tmp_path , columns , CompressionMethod : : LZ4 ) ; <nl> MergeTreeData : : MutableDataPartPtr MergeTreeDataWriter : : writeTempPart ( BlockWithDa <nl> out . getIndex ( ) . reserve ( part_size * sort_descr . size ( ) ) ; <nl> <nl> out . writePrefix ( ) ; <nl> - out . write ( block ) ; <nl> + out . writeWithPermutation ( block , perm_ptr ) ; <nl> MergeTreeData : : DataPart : : Checksums checksums = out . writeSuffixAndGetChecksums ( ) ; <nl> <nl> new_data_part - > left_date = DayNum_t ( min_date ) ; <nl> MergeTreeData : : MutableDataPartPtr MergeTreeDataWriter : : writeTempPart ( BlockWithDa <nl> new_data_part - > level = 0 ; <nl> new_data_part - > size = part_size ; <nl> new_data_part - > modification_time = time ( 0 ) ; <nl> - new_data_part - > left_month = date_lut . toFirstDayNumOfMonth ( new_data_part - > left_date ) ; <nl> - new_data_part - > right_month = date_lut . toFirstDayNumOfMonth ( new_data_part - > right_date ) ; <nl> + new_data_part - > month = min_month ; <nl> new_data_part - > columns = columns ; <nl> new_data_part - > checksums = checksums ; <nl> new_data_part - > index . swap ( out . getIndex ( ) ) ; <nl> mmm a / dbms / src / Storages / StorageFactory . cpp <nl> ppp b / dbms / src / Storages / StorageFactory . cpp <nl> <nl> <nl> # include < DB / Storages / StorageLog . h > <nl> # include < DB / Storages / StorageTinyLog . h > <nl> + # include < DB / Storages / StorageStripeLog . h > <nl> # include < DB / Storages / StorageMemory . h > <nl> # include < DB / Storages / StorageBuffer . h > <nl> # include < DB / Storages / StorageNull . h > <nl> StoragePtr StorageFactory : : get ( <nl> materialized_columns , alias_columns , column_defaults , <nl> attach , context . getSettings ( ) . max_compress_block_size ) ; <nl> } <nl> + else if ( name = = " StripeLog " ) <nl> + { <nl> + return StorageStripeLog : : create ( <nl> + data_path , table_name , columns , <nl> + materialized_columns , alias_columns , column_defaults , <nl> + attach , context . getSettings ( ) . max_compress_block_size ) ; <nl> + } <nl> else if ( name = = " Set " ) <nl> { <nl> return StorageSet : : create ( <nl> mmm a / dbms / src / Storages / StorageLog . cpp <nl> ppp b / dbms / src / Storages / StorageLog . cpp <nl> class LogBlockOutputStream : public IBlockOutputStream <nl> { <nl> Stream ( const std : : string & data_path , size_t max_compress_block_size ) : <nl> plain ( data_path , max_compress_block_size , O_APPEND | O_CREAT | O_WRONLY ) , <nl> - compressed ( plain ) <nl> + compressed ( plain , CompressionMethod : : LZ4 , max_compress_block_size ) <nl> { <nl> plain_offset = Poco : : File ( data_path ) . getSize ( ) ; <nl> } <nl> StorageLog : : StorageLog ( <nl> : IStorage { materialized_columns_ , alias_columns_ , column_defaults_ } , <nl> path ( path_ ) , name ( name_ ) , columns ( columns_ ) , <nl> loaded_marks ( false ) , max_compress_block_size ( max_compress_block_size_ ) , <nl> - file_checker ( path + escapeForFileName ( name ) + ' / ' + " sizes . json " , * this ) <nl> + file_checker ( path + escapeForFileName ( name ) + ' / ' + " sizes . json " ) <nl> { <nl> if ( columns - > empty ( ) ) <nl> throw Exception ( " Empty list of columns passed to StorageLog constructor " , ErrorCodes : : EMPTY_LIST_OF_COLUMNS_PASSED ) ; <nl> mmm a / dbms / src / Storages / StorageMergeTree . cpp <nl> ppp b / dbms / src / Storages / StorageMergeTree . cpp <nl> void StorageMergeTree : : dropPartition ( const Field & partition , bool detach , bool <nl> <nl> for ( const auto & part : parts ) <nl> { <nl> - if ( ! ( part - > left_month = = part - > right_month & & part - > left_month = = month ) ) <nl> + if ( part - > month ! = month ) <nl> continue ; <nl> <nl> LOG_DEBUG ( log , " Removing part " < < part - > name ) ; <nl> mmm a / dbms / src / Storages / StorageReplicatedMergeTree . cpp <nl> ppp b / dbms / src / Storages / StorageReplicatedMergeTree . cpp <nl> namespace DB <nl> const auto ERROR_SLEEP_MS = 1000 ; <nl> const auto MERGE_SELECTING_SLEEP_MS = 5 * 1000 ; <nl> <nl> - const auto RESERVED_BLOCK_NUMBERS = 200 ; <nl> + const Int64 RESERVED_BLOCK_NUMBERS = 200 ; <nl> <nl> <nl> StorageReplicatedMergeTree : : StorageReplicatedMergeTree ( <nl> void StorageReplicatedMergeTree : : mergeSelectingThread ( ) <nl> auto zookeeper = getZooKeeper ( ) ; <nl> <nl> / / / Можно слить куски , если все номера между ними заброшены - не соответствуют никаким блокам . <nl> - for ( UInt64 number = left - > right + 1 ; number < = right - > left - 1 ; + + number ) / / / Номера блоков больше нуля . <nl> + / / / Номера до RESERVED_BLOCK_NUMBERS всегда не соответствуют никаким блокам . <nl> + for ( Int64 number = std : : max ( RESERVED_BLOCK_NUMBERS , left - > right + 1 ) ; number < = right - > left - 1 ; + + number ) <nl> { <nl> String path1 = zookeeper_path + " / block_numbers / " + month_name + " / block - " + padIndex ( number ) ; <nl> String path2 = zookeeper_path + " / nonincrement_block_numbers / " + month_name + " / block - " + padIndex ( number ) ; <nl> void StorageReplicatedMergeTree : : mergeSelectingThread ( ) <nl> for ( size_t i = 0 ; i + 1 < parts . size ( ) ; + + i ) <nl> { <nl> / / / Уберем больше не нужные отметки о несуществующих блоках . <nl> - for ( UInt64 number = parts [ i ] - > right + 1 ; number < = parts [ i + 1 ] - > left - 1 ; + + number ) <nl> + for ( Int64 number = std : : max ( RESERVED_BLOCK_NUMBERS , parts [ i ] - > right + 1 ) ; number < = parts [ i + 1 ] - > left - 1 ; + + number ) <nl> { <nl> zookeeper - > tryRemove ( zookeeper_path + " / block_numbers / " + month_name + " / block - " + padIndex ( number ) ) ; <nl> zookeeper - > tryRemove ( zookeeper_path + " / nonincrement_block_numbers / " + month_name + " / block - " + padIndex ( number ) ) ; <nl> void StorageReplicatedMergeTree : : dropUnreplicatedPartition ( const Field & partiti <nl> <nl> for ( const auto & part : parts ) <nl> { <nl> - if ( ! ( part - > left_month = = part - > right_month & & part - > left_month = = month ) ) <nl> + if ( part - > month ! = month ) <nl> continue ; <nl> <nl> LOG_DEBUG ( log , " Removing unreplicated part " < < part - > name ) ; <nl> void StorageReplicatedMergeTree : : dropPartition ( const Field & field , bool detach , <nl> * NOTE : Если понадобится аналогично поддержать запрос DROP PART , для него придется придумать какой - нибудь новый механизм , <nl> * чтобы гарантировать этот инвариант . <nl> * / <nl> - UInt64 right ; <nl> + Int64 right ; <nl> <nl> { <nl> AbandonableLockInZooKeeper block_number_lock = allocateBlockNumber ( month_name ) ; <nl> void StorageReplicatedMergeTree : : attachPartition ( const Field & field , bool unrep <nl> String partition ; <nl> <nl> if ( attach_part ) <nl> - partition = field . getType ( ) = = Field : : Types : : UInt64 ? toString ( field . get < UInt64 > ( ) ) : field . safeGet < String > ( ) ; <nl> + partition = field . safeGet < String > ( ) ; <nl> else <nl> partition = MergeTreeData : : getMonthName ( field ) ; <nl> <nl> void StorageReplicatedMergeTree : : attachPartition ( const Field & field , bool unrep <nl> <nl> / / / Выделим добавляемым кускам максимальные свободные номера , меньшие RESERVED_BLOCK_NUMBERS . <nl> / / / NOTE : Проверка свободности номеров никак не синхронизируется . Выполнять несколько запросов ATTACH / DETACH / DROP одновременно нельзя . <nl> - UInt64 min_used_number = RESERVED_BLOCK_NUMBERS ; <nl> + Int64 min_used_number = RESERVED_BLOCK_NUMBERS ; <nl> + DayNum_t month = DateLUT : : instance ( ) . makeDayNum ( parse < UInt16 > ( partition . substr ( 0 , 4 ) ) , parse < UInt8 > ( partition . substr ( 4 , 2 ) ) , 0 ) ; <nl> <nl> { <nl> - / / / TODO Это необходимо лишь в пределах одного месяца . <nl> auto existing_parts = data . getDataParts ( ) ; <nl> for ( const auto & part : existing_parts ) <nl> - min_used_number = std : : min ( min_used_number , part - > left ) ; <nl> + if ( part - > month = = month ) <nl> + min_used_number = std : : min ( min_used_number , part - > left ) ; <nl> } <nl> <nl> - if ( parts . size ( ) > min_used_number ) <nl> - throw Exception ( " Not enough free small block numbers for attaching parts : " <nl> - + toString ( parts . size ( ) ) + " needed , " + toString ( min_used_number ) + " available " , ErrorCodes : : NOT_ENOUGH_BLOCK_NUMBERS ) ; <nl> - <nl> / / / Добавим записи в лог . <nl> std : : reverse ( parts . begin ( ) , parts . end ( ) ) ; <nl> std : : list < LogEntry > entries ; <nl> new file mode 100644 <nl> index 00000000000 . . 3659b987fd7 <nl> mmm / dev / null <nl> ppp b / dbms / src / Storages / StorageStripeLog . cpp <nl> <nl> + # include < map > <nl> + <nl> + # include < Poco / Path . h > <nl> + # include < Poco / Util / XMLConfiguration . h > <nl> + <nl> + # include < DB / Common / escapeForFileName . h > <nl> + <nl> + # include < DB / Core / Exception . h > <nl> + # include < DB / Core / ErrorCodes . h > <nl> + <nl> + # include < DB / IO / ReadBufferFromFile . h > <nl> + # include < DB / IO / WriteBufferFromFile . h > <nl> + # include < DB / IO / CompressedReadBufferFromFile . h > <nl> + # include < DB / IO / CompressedWriteBuffer . h > <nl> + # include < DB / IO / ReadHelpers . h > <nl> + # include < DB / IO / WriteHelpers . h > <nl> + <nl> + # include < DB / DataTypes / DataTypeArray . h > <nl> + # include < DB / DataTypes / DataTypeNested . h > <nl> + <nl> + # include < DB / DataStreams / IProfilingBlockInputStream . h > <nl> + # include < DB / DataStreams / IBlockOutputStream . h > <nl> + # include < DB / DataStreams / NativeBlockInputStream . h > <nl> + # include < DB / DataStreams / NativeBlockOutputStream . h > <nl> + <nl> + # include < DB / Columns / ColumnArray . h > <nl> + # include < DB / Columns / ColumnNested . h > <nl> + <nl> + # include < DB / Storages / StorageStripeLog . h > <nl> + # include < Poco / DirectoryIterator . h > <nl> + <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + # define INDEX_BUFFER_SIZE 4096 <nl> + <nl> + <nl> + class StripeLogBlockInputStream : public IProfilingBlockInputStream <nl> + { <nl> + public : <nl> + StripeLogBlockInputStream ( const NameSet & column_names_ , StorageStripeLog & storage_ , size_t max_read_buffer_size_ , <nl> + const Poco : : SharedPtr < IndexForNativeFormat > & index_ , <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_begin_ , <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_end_ ) <nl> + : column_names ( column_names_ . begin ( ) , column_names_ . end ( ) ) , storage ( storage_ ) , <nl> + index ( index_ ) , index_begin ( index_begin_ ) , index_end ( index_end_ ) , <nl> + data_in ( storage . full_path ( ) + " data . bin " , 0 , 0 , max_read_buffer_size_ ) , <nl> + block_in ( data_in , 0 , true , index_begin , index_end ) <nl> + { <nl> + } <nl> + <nl> + String getName ( ) const override { return " StripeLog " ; } <nl> + <nl> + String getID ( ) const override <nl> + { <nl> + std : : stringstream s ; <nl> + s < < " StripeLog " ; <nl> + for ( const auto & name : column_names ) <nl> + s < < " , " < < name ; / / / NOTE Отсутствует эскейпинг . <nl> + return s . str ( ) ; <nl> + } <nl> + <nl> + protected : <nl> + Block readImpl ( ) override <nl> + { <nl> + return block_in . read ( ) ; <nl> + } <nl> + <nl> + private : <nl> + NameSet column_names ; <nl> + StorageStripeLog & storage ; <nl> + <nl> + const Poco : : SharedPtr < IndexForNativeFormat > index ; <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_begin ; <nl> + IndexForNativeFormat : : Blocks : : const_iterator index_end ; <nl> + <nl> + CompressedReadBufferFromFile data_in ; <nl> + NativeBlockInputStream block_in ; <nl> + } ; <nl> + <nl> + <nl> + class StripeLogBlockOutputStream : public IBlockOutputStream <nl> + { <nl> + public : <nl> + StripeLogBlockOutputStream ( StorageStripeLog & storage_ ) <nl> + : storage ( storage_ ) , lock ( storage . rwlock ) , <nl> + data_out_compressed ( storage . full_path ( ) + " data . bin " ) , <nl> + data_out ( data_out_compressed , CompressionMethod : : LZ4 , storage . max_compress_block_size ) , <nl> + index_out_compressed ( storage . full_path ( ) + " index . mrk " , INDEX_BUFFER_SIZE ) , <nl> + index_out ( index_out_compressed ) , <nl> + block_out ( data_out , 0 , & index_out ) <nl> + { <nl> + } <nl> + <nl> + ~ StripeLogBlockOutputStream ( ) <nl> + { <nl> + try <nl> + { <nl> + writeSuffix ( ) ; <nl> + } <nl> + catch ( . . . ) <nl> + { <nl> + tryLogCurrentException ( __PRETTY_FUNCTION__ ) ; <nl> + } <nl> + } <nl> + <nl> + void write ( const Block & block ) override <nl> + { <nl> + block_out . write ( block ) ; <nl> + } <nl> + <nl> + void writeSuffix ( ) override <nl> + { <nl> + if ( done ) <nl> + return ; <nl> + <nl> + block_out . writeSuffix ( ) ; <nl> + data_out . next ( ) ; <nl> + data_out_compressed . next ( ) ; <nl> + index_out . next ( ) ; <nl> + index_out_compressed . next ( ) ; <nl> + <nl> + FileChecker : : Files files { data_out_compressed . getFileName ( ) , index_out_compressed . getFileName ( ) } ; <nl> + storage . file_checker . update ( files . begin ( ) , files . end ( ) ) ; <nl> + <nl> + done = true ; <nl> + } <nl> + <nl> + private : <nl> + StorageStripeLog & storage ; <nl> + Poco : : ScopedWriteRWLock lock ; <nl> + <nl> + WriteBufferFromFile data_out_compressed ; <nl> + CompressedWriteBuffer data_out ; <nl> + WriteBufferFromFile index_out_compressed ; <nl> + CompressedWriteBuffer index_out ; <nl> + NativeBlockOutputStream block_out ; <nl> + <nl> + bool done = false ; <nl> + } ; <nl> + <nl> + <nl> + StorageStripeLog : : StorageStripeLog ( <nl> + const std : : string & path_ , <nl> + const std : : string & name_ , <nl> + NamesAndTypesListPtr columns_ , <nl> + const NamesAndTypesList & materialized_columns_ , <nl> + const NamesAndTypesList & alias_columns_ , <nl> + const ColumnDefaults & column_defaults_ , <nl> + bool attach , <nl> + size_t max_compress_block_size_ ) <nl> + : IStorage { materialized_columns_ , alias_columns_ , column_defaults_ } , <nl> + path ( path_ ) , name ( name_ ) , columns ( columns_ ) , <nl> + max_compress_block_size ( max_compress_block_size_ ) , <nl> + file_checker ( path + escapeForFileName ( name ) + ' / ' + " sizes . json " ) , <nl> + log ( & Logger : : get ( " StorageStripeLog " ) ) <nl> + { <nl> + if ( columns - > empty ( ) ) <nl> + throw Exception ( " Empty list of columns passed to StorageStripeLog constructor " , ErrorCodes : : EMPTY_LIST_OF_COLUMNS_PASSED ) ; <nl> + <nl> + String full_path = path + escapeForFileName ( name ) + ' / ' ; <nl> + if ( ! attach ) <nl> + { <nl> + / / / создаём файлы , если их нет <nl> + if ( 0 ! = mkdir ( full_path . c_str ( ) , S_IRWXU | S_IRWXG | S_IRWXO ) & & errno ! = EEXIST ) <nl> + throwFromErrno ( " Cannot create directory " + full_path , ErrorCodes : : CANNOT_CREATE_DIRECTORY ) ; <nl> + } <nl> + } <nl> + <nl> + StoragePtr StorageStripeLog : : create ( <nl> + const std : : string & path_ , <nl> + const std : : string & name_ , <nl> + NamesAndTypesListPtr columns_ , <nl> + const NamesAndTypesList & materialized_columns_ , <nl> + const NamesAndTypesList & alias_columns_ , <nl> + const ColumnDefaults & column_defaults_ , <nl> + bool attach , <nl> + size_t max_compress_block_size_ ) <nl> + { <nl> + return ( new StorageStripeLog { <nl> + path_ , name_ , columns_ , <nl> + materialized_columns_ , alias_columns_ , column_defaults_ , <nl> + attach , max_compress_block_size_ <nl> + } ) - > thisPtr ( ) ; <nl> + } <nl> + <nl> + <nl> + void StorageStripeLog : : rename ( const String & new_path_to_db , const String & new_database_name , const String & new_table_name ) <nl> + { <nl> + Poco : : ScopedWriteRWLock lock ( rwlock ) ; <nl> + <nl> + / / / Переименовываем директорию с данными . <nl> + Poco : : File ( path + escapeForFileName ( name ) ) . renameTo ( new_path_to_db + escapeForFileName ( new_table_name ) ) ; <nl> + <nl> + path = new_path_to_db ; <nl> + name = new_table_name ; <nl> + file_checker . setPath ( path + escapeForFileName ( name ) + " / " + " sizes . json " ) ; <nl> + } <nl> + <nl> + <nl> + BlockInputStreams StorageStripeLog : : read ( <nl> + const Names & column_names , <nl> + ASTPtr query , <nl> + const Context & context , <nl> + const Settings & settings , <nl> + QueryProcessingStage : : Enum & processed_stage , <nl> + const size_t max_block_size , <nl> + unsigned threads ) <nl> + { <nl> + Poco : : ScopedReadRWLock lock ( rwlock ) ; <nl> + <nl> + check ( column_names ) ; <nl> + processed_stage = QueryProcessingStage : : FetchColumns ; <nl> + <nl> + NameSet column_names_set ( column_names . begin ( ) , column_names . end ( ) ) ; <nl> + <nl> + CompressedReadBufferFromFile index_in ( full_path ( ) + " index . mrk " , 0 , 0 , INDEX_BUFFER_SIZE ) ; <nl> + Poco : : SharedPtr < IndexForNativeFormat > index = new IndexForNativeFormat ( index_in , column_names_set ) ; <nl> + <nl> + BlockInputStreams res ; <nl> + <nl> + size_t size = index - > blocks . size ( ) ; <nl> + if ( threads > size ) <nl> + threads = size ; <nl> + <nl> + for ( size_t thread = 0 ; thread < threads ; + + thread ) <nl> + { <nl> + IndexForNativeFormat : : Blocks : : const_iterator begin = index - > blocks . begin ( ) ; <nl> + IndexForNativeFormat : : Blocks : : const_iterator end = index - > blocks . begin ( ) ; <nl> + <nl> + std : : advance ( begin , thread * size / threads ) ; <nl> + std : : advance ( end , ( thread + 1 ) * size / threads ) ; <nl> + <nl> + res . emplace_back ( new StripeLogBlockInputStream ( column_names_set , * this , settings . max_read_buffer_size , index , begin , end ) ) ; <nl> + } <nl> + <nl> + / / / Непосредственно во время чтения не держим read lock , потому что мы читаем диапазоны данных , которые не меняются . <nl> + <nl> + return res ; <nl> + } <nl> + <nl> + <nl> + BlockOutputStreamPtr StorageStripeLog : : write ( <nl> + ASTPtr query ) <nl> + { <nl> + return new StripeLogBlockOutputStream ( * this ) ; <nl> + } <nl> + <nl> + <nl> + bool StorageStripeLog : : checkData ( ) const <nl> + { <nl> + Poco : : ScopedReadRWLock lock ( const_cast < Poco : : RWLock & > ( rwlock ) ) ; <nl> + return file_checker . check ( ) ; <nl> + } <nl> + <nl> + } <nl> mmm a / dbms / src / Storages / StorageSystemDictionaries . cpp <nl> ppp b / dbms / src / Storages / StorageSystemDictionaries . cpp <nl> BlockInputStreams StorageSystemDictionaries : : read ( <nl> } <nl> catch ( const Exception & e ) <nl> { <nl> - col_last_exception . column - > insert ( " DB : : Exception . Code " + toString ( e . code ( ) ) + " . " + e . message ( ) ) ; <nl> + col_last_exception . column - > insert ( " DB : : Exception . Code " + toString ( e . code ( ) ) + " . " + <nl> + std : : string { e . displayText ( ) } ) ; <nl> } <nl> catch ( const Poco : : Exception & e ) <nl> { <nl> - col_last_exception . column - > insert ( " Poco : : Exception . " + e . message ( ) ) ; <nl> + col_last_exception . column - > insert ( " Poco : : Exception . " + std : : string { e . displayText ( ) } ) ; <nl> } <nl> catch ( const std : : exception & e ) <nl> { <nl> mmm a / dbms / src / Storages / StorageSystemParts . cpp <nl> ppp b / dbms / src / Storages / StorageSystemParts . cpp <nl> StorageSystemParts : : StorageSystemParts ( const std : : string & name_ ) <nl> { " refcount " , new DataTypeUInt32 } , <nl> { " min_date " , new DataTypeDate } , <nl> { " max_date " , new DataTypeDate } , <nl> - { " min_block_number " , new DataTypeUInt64 } , <nl> - { " max_block_number " , new DataTypeUInt64 } , <nl> + { " min_block_number " , new DataTypeInt64 } , <nl> + { " max_block_number " , new DataTypeInt64 } , <nl> { " level " , new DataTypeUInt32 } , <nl> <nl> { " database " , new DataTypeString } , <nl> BlockInputStreams StorageSystemParts : : read ( <nl> ColumnPtr refcount_column = new ColumnUInt32 ; <nl> ColumnPtr min_date_column = new ColumnUInt16 ; <nl> ColumnPtr max_date_column = new ColumnUInt16 ; <nl> - ColumnPtr min_block_number_column = new ColumnUInt64 ; <nl> - ColumnPtr max_block_number_column = new ColumnUInt64 ; <nl> + ColumnPtr min_block_number_column = new ColumnInt64 ; <nl> + ColumnPtr max_block_number_column = new ColumnInt64 ; <nl> ColumnPtr level_column = new ColumnUInt32 ; <nl> <nl> for ( size_t i = 0 ; i < filtered_database_column - > size ( ) ; ) <nl> BlockInputStreams StorageSystemParts : : read ( <nl> table_column - > insert ( table ) ; <nl> engine_column - > insert ( engine ) ; <nl> <nl> - mysqlxx : : Date partition_date { part - > left_month } ; <nl> + mysqlxx : : Date partition_date { part - > month } ; <nl> String partition = toString ( partition_date . year ( ) ) + ( partition_date . month ( ) < 10 ? " 0 " : " " ) + toString ( partition_date . month ( ) ) ; <nl> partition_column - > insert ( partition ) ; <nl> <nl> BlockInputStreams StorageSystemParts : : read ( <nl> block . insert ( ColumnWithTypeAndName ( refcount_column , new DataTypeUInt32 , " refcount " ) ) ; <nl> block . insert ( ColumnWithTypeAndName ( min_date_column , new DataTypeDate , " min_date " ) ) ; <nl> block . insert ( ColumnWithTypeAndName ( max_date_column , new DataTypeDate , " max_date " ) ) ; <nl> - block . insert ( ColumnWithTypeAndName ( min_block_number_column , new DataTypeUInt64 , " min_block_number " ) ) ; <nl> - block . insert ( ColumnWithTypeAndName ( max_block_number_column , new DataTypeUInt64 , " max_block_number " ) ) ; <nl> + block . insert ( ColumnWithTypeAndName ( min_block_number_column , new DataTypeInt64 , " min_block_number " ) ) ; <nl> + block . insert ( ColumnWithTypeAndName ( max_block_number_column , new DataTypeInt64 , " max_block_number " ) ) ; <nl> block . insert ( ColumnWithTypeAndName ( level_column , new DataTypeUInt32 , " level " ) ) ; <nl> block . insert ( ColumnWithTypeAndName ( database_column , new DataTypeString , " database " ) ) ; <nl> block . insert ( ColumnWithTypeAndName ( table_column , new DataTypeString , " table " ) ) ; <nl> mmm a / dbms / src / Storages / StorageTinyLog . cpp <nl> ppp b / dbms / src / Storages / StorageTinyLog . cpp <nl> class TinyLogBlockOutputStream : public IBlockOutputStream <nl> { <nl> Stream ( const std : : string & data_path , size_t max_compress_block_size ) : <nl> plain ( data_path , max_compress_block_size , O_APPEND | O_CREAT | O_WRONLY ) , <nl> - compressed ( plain ) <nl> + compressed ( plain , CompressionMethod : : LZ4 , max_compress_block_size ) <nl> { <nl> } <nl> <nl> StorageTinyLog : : StorageTinyLog ( <nl> : IStorage { materialized_columns_ , alias_columns_ , column_defaults_ } , <nl> path ( path_ ) , name ( name_ ) , columns ( columns_ ) , <nl> max_compress_block_size ( max_compress_block_size_ ) , <nl> - file_checker ( path + escapeForFileName ( name ) + ' / ' + " sizes . json " , * this ) , <nl> + file_checker ( path + escapeForFileName ( name ) + ' / ' + " sizes . json " ) , <nl> log ( & Logger : : get ( " StorageTinyLog " ) ) <nl> { <nl> if ( columns - > empty ( ) ) <nl> bool StorageTinyLog : : checkData ( ) const <nl> return file_checker . check ( ) ; <nl> } <nl> <nl> - StorageTinyLog : : Files_t & StorageTinyLog : : getFiles ( ) <nl> - { <nl> - return files ; <nl> - } <nl> - <nl> } <nl> new file mode 100644 <nl> index 00000000000 . . 9972842f982 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00213_multiple_global_in . reference <nl> @ @ - 0 , 0 + 1 @ @ <nl> + 1 1 <nl> new file mode 100644 <nl> index 00000000000 . . b93c2bec722 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00213_multiple_global_in . sql <nl> @ @ - 0 , 0 + 1 @ @ <nl> + SELECT 1 GLOBAL IN ( SELECT 1 ) , 2 GLOBAL IN ( SELECT 2 ) FROM remote ( ' 127 . 0 . 0 . 2 ' , system . one ) ; <nl> new file mode 100644 <nl> index 00000000000 . . f9a71b1af97 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00214_primary_key_order . reference <nl> <nl> + 1 <nl> + 2 <nl> + 3 <nl> + b - 3 <nl> + c - 3 <nl> + c - 2 <nl> + d - 3 <nl> + d - 2 <nl> + d - 1 <nl> new file mode 100644 <nl> index 00000000000 . . b2c00fb1f63 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00214_primary_key_order . sql <nl> <nl> + DROP TABLE IF EXISTS test . primary_key ; <nl> + CREATE TABLE test . primary_key ( d Date DEFAULT today ( ) , x Int8 ) ENGINE = MergeTree ( d , - x , 1 ) ; <nl> + <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> + <nl> + SELECT x FROM test . primary_key ORDER BY x ; <nl> + <nl> + SELECT ' a ' , - x FROM test . primary_key WHERE - x < - 3 ; <nl> + SELECT ' b ' , - x FROM test . primary_key WHERE - x < - 2 ; <nl> + SELECT ' c ' , - x FROM test . primary_key WHERE - x < - 1 ; <nl> + SELECT ' d ' , - x FROM test . primary_key WHERE - x < toInt8 ( 0 ) ; <nl> + <nl> + DROP TABLE test . primary_key ; <nl> new file mode 100644 <nl> index 00000000000 . . 7f43a43f889 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00215_primary_key_order_zookeeper . reference <nl> <nl> + 1 <nl> + 2 <nl> + 3 <nl> + 2 <nl> + 3 <nl> new file mode 100644 <nl> index 00000000000 . . cd86bc7aa15 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00215_primary_key_order_zookeeper . sql <nl> <nl> + DROP TABLE IF EXISTS test . primary_key ; <nl> + CREATE TABLE test . primary_key ( d Date DEFAULT today ( ) , x Int8 ) ENGINE = ReplicatedMergeTree ( ' / clickhouse / tables / test / primary_key ' , ' r1 ' , d , - x , 1 ) ; <nl> + <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 1 ) , ( 2 ) , ( 3 ) ; <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 1 ) , ( 3 ) , ( 2 ) ; <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 2 ) , ( 1 ) , ( 3 ) ; <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 2 ) , ( 3 ) , ( 1 ) ; <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 3 ) , ( 1 ) , ( 2 ) ; <nl> + INSERT INTO test . primary_key ( x ) VALUES ( 3 ) , ( 2 ) , ( 1 ) ; <nl> + <nl> + SELECT x FROM test . primary_key ORDER BY x ; <nl> + SELECT x FROM test . primary_key WHERE - x < - 1 ORDER BY x ; <nl> + <nl> + DROP TABLE test . primary_key ; <nl>
Merge
ClickHouse/ClickHouse
c628ded8b1ec3f4fadf5521df4ea64845f03409f
2015-08-19T15:59:41Z
mmm a / guilib / GUIBaseContainer . cpp <nl> ppp b / guilib / GUIBaseContainer . cpp <nl> <nl> <nl> # include " GUIBaseContainer . h " <nl> # include " GUIControlFactory . h " <nl> + # include " GUIWindowManager . h " <nl> # include " utils / CharsetConverter . h " <nl> # include " utils / GUIInfoManager . h " <nl> # include " utils / TimeUtils . h " <nl> bool CGUIBaseContainer : : OnClick ( int actionID ) <nl> action . Replace ( " , , " , " , " ) ; <nl> CGUIMessage message ( GUI_MSG_EXECUTE , GetID ( ) , GetParentID ( ) ) ; <nl> message . SetStringParam ( action ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> } <nl> return true ; <nl> mmm a / guilib / GUIButtonControl . cpp <nl> ppp b / guilib / GUIButtonControl . cpp <nl> void CGUIButtonControl : : OnClick ( ) <nl> { <nl> CGUIMessage message ( GUI_MSG_EXECUTE , controlID , parentID ) ; <nl> message . SetAction ( clickActions [ i ] ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> } <nl> <nl> mmm a / guilib / GUIButtonScroller . cpp <nl> ppp b / guilib / GUIButtonScroller . cpp <nl> bool CGUIButtonScroller : : OnAction ( const CAction & action ) <nl> CGUIMessage message ( GUI_MSG_EXECUTE , GetID ( ) , GetParentID ( ) ) ; <nl> / / find our currently highlighted item <nl> message . SetAction ( actions [ i ] ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> return true ; <nl> } <nl> mmm a / guilib / GUIControl . cpp <nl> ppp b / guilib / GUIControl . cpp <nl> bool CGUIControl : : SendWindowMessage ( CGUIMessage & message ) <nl> CGUIWindow * pWindow = m_gWindowManager . GetWindow ( GetParentID ( ) ) ; <nl> if ( pWindow ) <nl> return pWindow - > OnMessage ( message ) ; <nl> - return g_graphicsContext . SendMessage ( message ) ; <nl> + return m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> <nl> int CGUIControl : : GetID ( void ) const <nl> void CGUIControl : : ExecuteActions ( const vector < CGUIActionDescriptor > & actions ) <nl> { <nl> CGUIMessage message ( GUI_MSG_EXECUTE , savedID , savedParent ) ; <nl> message . SetAction ( savedActions [ i ] ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> } <nl> <nl> mmm a / guilib / GUIEditControl . cpp <nl> ppp b / guilib / GUIEditControl . cpp <nl> <nl> * / <nl> <nl> # include " GUIEditControl . h " <nl> + # include " GUIWindowManager . h " <nl> # include " utils / CharsetConverter . h " <nl> # include " GUIDialogKeyboard . h " <nl> # include " GUIDialogNumeric . h " <nl> void CGUIEditControl : : OnTextChanged ( ) <nl> { <nl> CGUIMessage message ( GUI_MSG_EXECUTE , GetID ( ) , GetParentID ( ) ) ; <nl> message . SetAction ( textChangeActions [ i ] ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> <nl> SetInvalid ( ) ; <nl> mmm a / guilib / GUIFontManager . cpp <nl> ppp b / guilib / GUIFontManager . cpp <nl> <nl> <nl> # include " GUIFontManager . h " <nl> # include " GraphicContext . h " <nl> + # include " GUIWindowManager . h " <nl> # include " SkinInfo . h " <nl> # include " GUIFontTTF . h " <nl> # include " GUIFont . h " <nl> void GUIFontManager : : ReloadTTFFonts ( void ) <nl> <nl> m_bFontsNeedReloading = false ; <nl> / / send a message to our controls telling them they need to refresh . <nl> - g_graphicsContext . SendMessage ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_INVALIDATE ) ; <nl> + m_gWindowManager . SendMessage ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_INVALIDATE ) ; <nl> } <nl> <nl> void GUIFontManager : : Unload ( const CStdString & strFontName ) <nl> mmm a / guilib / GUIMultiSelectText . cpp <nl> ppp b / guilib / GUIMultiSelectText . cpp <nl> <nl> * / <nl> <nl> # include " GUIMultiSelectText . h " <nl> + # include " GUIWindowManager . h " <nl> # include " Key . h " <nl> # include " MouseStat . h " <nl> # include " utils / log . h " <nl> bool CGUIMultiSelectTextControl : : OnAction ( const CAction & action ) <nl> { / / have a click action - > perform it <nl> CGUIMessage message ( GUI_MSG_EXECUTE , m_controlID , m_parentID ) ; <nl> message . SetStringParam ( clickAction ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else <nl> { / / no click action , just send a message to the window <nl> mmm a / guilib / GUIVideoControl . cpp <nl> ppp b / guilib / GUIVideoControl . cpp <nl> bool CGUIVideoControl : : OnMouseClick ( int button , const CPoint & point ) <nl> if ( button = = MOUSE_LEFT_BUTTON ) <nl> { <nl> CGUIMessage message ( GUI_MSG_FULLSCREEN , GetID ( ) , GetParentID ( ) ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> return true ; <nl> } <nl> if ( button = = MOUSE_RIGHT_BUTTON ) <nl> mmm a / guilib / GUIVisualisationControl . cpp <nl> ppp b / guilib / GUIVisualisationControl . cpp <nl> <nl> # include " GUIVisualisationControl . h " <nl> + # include " GUIWindowManager . h " <nl> # include " GUIUserMessages . h " <nl> # include " Application . h " <nl> # include " visualizations / Visualisation . h " <nl> void CGUIVisualisationControl : : FreeVisualisation ( ) <nl> m_bInitialized = false ; <nl> / / tell our app that we ' re going <nl> CGUIMessage msg ( GUI_MSG_VISUALISATION_UNLOADING , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> CSingleLock lock ( m_critSection ) ; <nl> <nl> void CGUIVisualisationControl : : LoadVisualisation ( ) <nl> <nl> / / tell our app that we ' re back <nl> CGUIMessage msg ( GUI_MSG_VISUALISATION_LOADED , 0 , 0 , 0 , 0 , m_pVisualisation ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> void CGUIVisualisationControl : : UpdateVisibility ( const CGUIListItem * item ) <nl> mmm a / guilib / GUIWindow . cpp <nl> ppp b / guilib / GUIWindow . cpp <nl> void CGUIWindow : : RunActions ( std : : vector < CGUIActionDescriptor > & actions ) <nl> { <nl> CGUIMessage message ( GUI_MSG_EXECUTE , 0 , GetID ( ) ) ; <nl> message . SetAction ( tempActions [ i ] ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> } <nl> <nl> mmm a / guilib / GUIWindowManager . cpp <nl> ppp b / guilib / GUIWindowManager . cpp <nl> CGUIWindowManager : : ~ CGUIWindowManager ( void ) <nl> <nl> void CGUIWindowManager : : Initialize ( ) <nl> { <nl> - g_graphicsContext . setMessageSender ( this ) ; <nl> LoadNotOnDemandWindows ( ) ; <nl> } <nl> <nl> + bool CGUIWindowManager : : SendMessage ( int message , int senderID , int destID , int param1 , int param2 ) <nl> + { <nl> + CGUIMessage msg ( message , senderID , destID , param1 , param2 ) ; <nl> + return SendMessage ( msg ) ; <nl> + } <nl> + <nl> bool CGUIWindowManager : : SendMessage ( CGUIMessage & message ) <nl> { <nl> bool handled = false ; <nl> mmm a / guilib / GUIWindowManager . h <nl> ppp b / guilib / GUIWindowManager . h <nl> <nl> * / <nl> <nl> # include " GUIWindow . h " <nl> - # include " IMsgSenderCallback . h " <nl> # include " IWindowManagerCallback . h " <nl> # include " IMsgTargetCallback . h " <nl> <nl> class CGUIDialog ; <nl> \ ingroup winman <nl> \ brief <nl> * / <nl> - class CGUIWindowManager : public IMsgSenderCallback <nl> + class CGUIWindowManager <nl> { <nl> public : <nl> CGUIWindowManager ( void ) ; <nl> virtual ~ CGUIWindowManager ( void ) ; <nl> bool SendMessage ( CGUIMessage & message ) ; <nl> + bool SendMessage ( int message , int senderID , int destID , int param1 = 0 , int param2 = 0 ) ; <nl> bool SendMessage ( CGUIMessage & message , int window ) ; <nl> void Initialize ( ) ; <nl> void Add ( CGUIWindow * pWindow ) ; <nl> mmm a / guilib / GraphicContext . cpp <nl> ppp b / guilib / GraphicContext . cpp <nl> <nl> # include " system . h " <nl> # include " GraphicContext . h " <nl> # include " GUIFontManager . h " <nl> - # include " GUIMessage . h " <nl> - # include " IMsgSenderCallback . h " <nl> # include " utils / SingleLock . h " <nl> # include " Application . h " <nl> # include " GUISettings . h " <nl> CGraphicContext : : CGraphicContext ( void ) <nl> m_strMediaDir = " " ; <nl> m_bCalibrating = false ; <nl> m_Resolution = RES_INVALID ; <nl> - m_pCallback = NULL ; <nl> m_guiScaleX = m_guiScaleY = 1 . 0f ; <nl> m_windowResolution = RES_INVALID ; <nl> m_bFullScreenRoot = false ; <nl> CGraphicContext : : ~ CGraphicContext ( void ) <nl> { <nl> } <nl> <nl> - bool CGraphicContext : : SendMessage ( int message , int senderID , int destID , int param1 , int param2 ) <nl> - { <nl> - if ( ! m_pCallback ) return false ; <nl> - CGUIMessage msg ( message , senderID , destID , param1 , param2 ) ; <nl> - return m_pCallback - > SendMessage ( msg ) ; <nl> - } <nl> - <nl> - bool CGraphicContext : : SendMessage ( CGUIMessage & message ) <nl> - { <nl> - if ( ! m_pCallback ) return false ; <nl> - return m_pCallback - > SendMessage ( message ) ; <nl> - } <nl> - <nl> - void CGraphicContext : : setMessageSender ( IMsgSenderCallback * pCallback ) <nl> - { <nl> - m_pCallback = pCallback ; <nl> - } <nl> - <nl> void CGraphicContext : : SetOrigin ( float x , float y ) <nl> { <nl> if ( m_origins . size ( ) ) <nl> mmm a / guilib / GraphicContext . h <nl> ppp b / guilib / GraphicContext . h <nl> <nl> # include " StdString . h " <nl> # include " Resolution . h " <nl> <nl> - / / forward definitions <nl> - class IMsgSenderCallback ; <nl> - class CGUIMessage ; <nl> - <nl> enum VIEW_TYPE { VIEW_TYPE_NONE = 0 , <nl> VIEW_TYPE_LIST , <nl> VIEW_TYPE_ICON , <nl> class CGraphicContext : public CCriticalSection <nl> int GetWidth ( ) const { return m_iScreenWidth ; } <nl> int GetHeight ( ) const { return m_iScreenHeight ; } <nl> float GetFPS ( ) const ; <nl> - bool SendMessage ( CGUIMessage & message ) ; <nl> - bool SendMessage ( int message , int senderID , int destID , int param1 = 0 , int param2 = 0 ) ; <nl> - void setMessageSender ( IMsgSenderCallback * pCallback ) ; <nl> const CStdString & GetMediaDir ( ) const { return m_strMediaDir ; } <nl> void SetMediaDir ( const CStdString & strMediaDir ) ; <nl> bool IsWidescreen ( ) const { return m_bWidescreen ; } <nl> class CGraphicContext : public CCriticalSection <nl> protected : <nl> void SetFullScreenViewWindow ( RESOLUTION & res ) ; <nl> <nl> - IMsgSenderCallback * m_pCallback ; <nl> std : : stack < CRect > m_viewStack ; <nl> <nl> int m_iScreenHeight ; <nl> deleted file mode 100644 <nl> index 3f825d44699a . . 000000000000 <nl> mmm a / guilib / IMsgSenderCallback . h <nl> ppp / dev / null <nl> <nl> - / * ! <nl> - \ file IMsgSenderCallback . h <nl> - \ brief <nl> - * / <nl> - <nl> - # ifndef GUILIB_IMSGSENDERCALLBACK <nl> - # define GUILIB_IMSGSENDERCALLBACK <nl> - <nl> - # pragma once <nl> - <nl> - / * <nl> - * Copyright ( C ) 2005 - 2008 Team XBMC <nl> - * http : / / www . xbmc . org <nl> - * <nl> - * This Program is free software ; you can redistribute it and / or modify <nl> - * it under the terms of the GNU General Public License as published by <nl> - * the Free Software Foundation ; either version 2 , or ( at your option ) <nl> - * any later version . <nl> - * <nl> - * This Program is distributed in the hope that it will be useful , <nl> - * but WITHOUT ANY WARRANTY ; without even the implied warranty of <nl> - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the <nl> - * GNU General Public License for more details . <nl> - * <nl> - * You should have received a copy of the GNU General Public License <nl> - * along with XBMC ; see the file COPYING . If not , write to <nl> - * the Free Software Foundation , 675 Mass Ave , Cambridge , MA 02139 , USA . <nl> - * http : / / www . gnu . org / copyleft / gpl . html <nl> - * <nl> - * / <nl> - <nl> - # include " GUIMessage . h " <nl> - <nl> - / * ! <nl> - \ ingroup winman <nl> - \ brief <nl> - * / <nl> - class IMsgSenderCallback <nl> - { <nl> - public : <nl> - virtual bool SendMessage ( CGUIMessage & message ) = 0 ; <nl> - virtual ~ IMsgSenderCallback ( ) { } <nl> - } ; <nl> - <nl> - # endif <nl> mmm a / project / VS2008Express / guilib . vcproj <nl> ppp b / project / VS2008Express / guilib . vcproj <nl> <nl> < ? xml version = " 1 . 0 " encoding = " Windows - 1252 " ? > <nl> < VisualStudioProject <nl> ProjectType = " Visual C + + " <nl> - Version = " 9 , 00 " <nl> + Version = " 9 . 00 " <nl> Name = " guilib " <nl> ProjectGUID = " { 510441AC - B9E1 - 4B31 - 9C0C - EB3AD39D90C4 } " <nl> RootNamespace = " guilib " <nl> <nl> RelativePath = " . . \ . . \ guilib \ IAudioDeviceChangedCallback . h " <nl> > <nl> < / File > <nl> - < File <nl> - RelativePath = " . . \ . . \ guilib \ IMsgSenderCallback . h " <nl> - > <nl> - < / File > <nl> < File <nl> RelativePath = " . . \ . . \ guilib \ IMsgTargetCallback . h " <nl> > <nl> mmm a / xbmc / Application . cpp <nl> ppp b / xbmc / Application . cpp <nl> void CApplication : : CancelDelayLoadSkin ( ) <nl> void CApplication : : ReloadSkin ( ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_LOAD_SKIN , - 1 , m_gWindowManager . GetActiveWindow ( ) ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> / / Reload the skin , restoring the previously focused control . We need this as <nl> / / the window unload will reset all control states . <nl> CGUIWindow * pWindow = m_gWindowManager . GetWindow ( m_gWindowManager . GetActiveWindow ( ) ) ; <nl> bool CApplication : : OnAction ( CAction & action ) <nl> } <nl> / / send a message to all windows to tell them to update the fileitem ( eg playlistplayer , media windows ) <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_UPDATE_ITEM , 0 , m_itemCurrentFile ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> } <nl> return true ; <nl> void CApplication : : SaveFileState ( ) <nl> videodatabase . MarkAsWatched ( * m_progressTrackingItem ) ; <nl> CUtil : : DeleteVideoDatabaseDirectoryCache ( ) ; <nl> CGUIMessage message ( GUI_MSG_NOTIFY_ALL , m_gWindowManager . GetActiveWindow ( ) , 0 , GUI_MSG_UPDATE , 0 ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> <nl> if ( g_stSettings . m_currentVideoSettings ! = g_stSettings . m_defaultVideoSettings ) <nl> mmm a / xbmc / GUIDialogContentSettings . cpp <nl> ppp b / xbmc / GUIDialogContentSettings . cpp <nl> void CGUIDialogContentSettings : : SetupPage ( ) <nl> CGUIDialogSettings : : SetupPage ( ) ; <nl> <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , GetID ( ) , CONTROL_CONTENT_TYPE ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> CGUIMessage msg2 ( GUI_MSG_LABEL_ADD , GetID ( ) , CONTROL_CONTENT_TYPE ) ; <nl> <nl> if ( ! m_info . strContent . Equals ( " albums " ) ) / / none does not apply to music <nl> { <nl> msg2 . SetLabel ( " < " + g_localizeStrings . Get ( 231 ) + " > " ) ; <nl> msg2 . SetParam1 ( 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> <nl> if ( m_scrapers . find ( " movies " ) ! = m_scrapers . end ( ) ) <nl> { <nl> msg2 . SetLabel ( g_localizeStrings . Get ( 20342 ) ) ; <nl> msg2 . SetParam1 ( 1 ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> if ( m_info . strContent . Equals ( " movies " ) ) <nl> { <nl> SET_CONTROL_LABEL ( CONTROL_CONTENT_TYPE , g_localizeStrings . Get ( 20342 ) ) ; <nl> void CGUIDialogContentSettings : : SetupPage ( ) <nl> { <nl> msg2 . SetLabel ( g_localizeStrings . Get ( 20343 ) ) ; <nl> msg2 . SetParam1 ( 2 ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> if ( m_info . strContent . Equals ( " tvshows " ) ) <nl> { <nl> CONTROL_SELECT_ITEM ( CONTROL_CONTENT_TYPE , 2 ) ; <nl> void CGUIDialogContentSettings : : SetupPage ( ) <nl> { <nl> msg2 . SetLabel ( g_localizeStrings . Get ( 20389 ) ) ; <nl> msg2 . SetParam1 ( 3 ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> if ( m_info . strContent . Equals ( " musicvideos " ) ) <nl> { <nl> SET_CONTROL_LABEL ( CONTROL_CONTENT_TYPE , g_localizeStrings . Get ( 20389 ) ) ; <nl> void CGUIDialogContentSettings : : SetupPage ( ) <nl> { <nl> msg2 . SetLabel ( m_strContentType ) ; <nl> msg2 . SetParam1 ( 4 ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> if ( m_info . strContent . Equals ( " albums " ) ) <nl> { <nl> SET_CONTROL_LABEL ( CONTROL_CONTENT_TYPE , m_strContentType ) ; <nl> mmm a / xbmc / GUIDialogFavourites . cpp <nl> ppp b / xbmc / GUIDialogFavourites . cpp <nl> void CGUIDialogFavourites : : OnClick ( int item ) <nl> <nl> CGUIMessage message ( GUI_MSG_EXECUTE , 0 , GetID ( ) ) ; <nl> message . SetStringParam ( execute ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> <nl> void CGUIDialogFavourites : : OnPopupMenu ( int item ) <nl> mmm a / xbmc / GUIDialogKeyboard . cpp <nl> ppp b / xbmc / GUIDialogKeyboard . cpp <nl> void CGUIDialogKeyboard : : UpdateLabel ( ) / / FIXME seems to be called twice for one <nl> { / / send our filter message <nl> CGUIMessage message ( GUI_MSG_NOTIFY_ALL , GetID ( ) , 0 , GUI_MSG_FILTER_ITEMS ) ; <nl> message . SetStringParam ( utf8Edit ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> <nl> if ( m_filtering = = FILTERING_SEARCH ) <nl> mmm a / xbmc / GUIDialogMusicOSD . cpp <nl> ppp b / xbmc / GUIDialogMusicOSD . cpp <nl> bool CGUIDialogMusicOSD : : OnMessage ( CGUIMessage & message ) <nl> else if ( iControl = = CONTROL_LOCK_BUTTON ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_VISUALISATION_ACTION , 0 , 0 , ACTION_VIS_PRESET_LOCK ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> return true ; <nl> } <nl> mmm a / xbmc / GUIDialogSelect . cpp <nl> ppp b / xbmc / GUIDialogSelect . cpp <nl> <nl> * / <nl> <nl> # include " GUIDialogSelect . h " <nl> + # include " GUIWindowManager . h " <nl> # include " FileItem . h " <nl> # include " LocalizeStrings . h " <nl> <nl> bool CGUIDialogSelect : : OnMessage ( CGUIMessage & message ) <nl> CGUIDialog : : OnMessage ( message ) ; <nl> m_iSelected = - 1 ; <nl> CGUIMessage msg ( GUI_MSG_LABEL_BIND , GetID ( ) , CONTROL_LIST , 0 , 0 , m_vecList ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> CStdString items ; <nl> items . Format ( " % i % s " , m_vecList - > Size ( ) , g_localizeStrings . Get ( 127 ) . c_str ( ) ) ; <nl> bool CGUIDialogSelect : : OnMessage ( CGUIMessage & message ) <nl> if ( m_bButtonEnabled ) <nl> { <nl> CGUIMessage msg2 ( GUI_MSG_VISIBLE , GetID ( ) , CONTROL_BUTTON ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> else <nl> { <nl> CGUIMessage msg2 ( GUI_MSG_HIDDEN , GetID ( ) , CONTROL_BUTTON ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> return true ; <nl> } <nl> bool CGUIDialogSelect : : OnMessage ( CGUIMessage & message ) <nl> if ( ACTION_SELECT_ITEM = = iAction | | ACTION_MOUSE_LEFT_CLICK = = iAction ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , iControl ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> m_iSelected = msg . GetParam1 ( ) ; <nl> if ( m_iSelected > = 0 & & m_iSelected < ( int ) m_vecList - > Size ( ) ) <nl> { <nl> mmm a / xbmc / GUIDialogSongInfo . cpp <nl> ppp b / xbmc / GUIDialogSongInfo . cpp <nl> void CGUIDialogSongInfo : : SetRating ( char rating ) <nl> m_song - > GetMusicInfoTag ( ) - > SetRating ( rating ) ; <nl> / / send a message to all windows to tell them to update the fileitem ( eg playlistplayer , media windows ) <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_UPDATE_ITEM , 0 , m_song ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> void CGUIDialogSongInfo : : SetSong ( CFileItem * item ) <nl> void CGUIDialogSongInfo : : OnGetThumb ( ) <nl> / / tell our GUI to completely reload all controls ( as some of them <nl> / / are likely to have had this image in use so will need refreshing ) <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_REFRESH_THUMBS ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> / / m_hasUpdatedThumb = true ; <nl> } <nl> mmm a / xbmc / GUIDialogVisualisationPresetList . cpp <nl> ppp b / xbmc / GUIDialogVisualisationPresetList . cpp <nl> <nl> * / <nl> <nl> # include " GUIDialogVisualisationPresetList . h " <nl> + # include " GUIWindowManager . h " <nl> # include " GUIListContainer . h " <nl> # include " GUISettings . h " <nl> # include " GUIUserMessages . h " <nl> bool CGUIDialogVisualisationPresetList : : OnMessage ( CGUIMessage & message ) <nl> CGUIDialog : : OnMessage ( message ) ; <nl> <nl> CGUIMessage msg ( GUI_MSG_GET_VISUALISATION , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> SetVisualisation ( ( CVisualisation * ) msg . GetPointer ( ) ) ; <nl> return true ; <nl> } <nl> mmm a / xbmc / GUIDialogVisualisationSettings . cpp <nl> ppp b / xbmc / GUIDialogVisualisationSettings . cpp <nl> <nl> * / <nl> <nl> # include " GUIDialogVisualisationSettings . h " <nl> + # include " GUIWindowManager . h " <nl> # include " GUIWindowSettingsCategory . h " <nl> # include " GUISpinControlEx . h " <nl> # include " GUIRadioButtonControl . h " <nl> void CGUIDialogVisualisationSettings : : OnInitWindow ( ) <nl> { <nl> / / set our visualisation <nl> CGUIMessage msg ( GUI_MSG_GET_VISUALISATION , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> SetVisualisation ( ( CVisualisation * ) msg . GetPointer ( ) ) ; <nl> <nl> SetupPage ( ) ; <nl> mmm a / xbmc / GUIMediaWindow . cpp <nl> ppp b / xbmc / GUIMediaWindow . cpp <nl> void CGUIMediaWindow : : UpdateButtons ( ) <nl> if ( m_guiState - > GetDisplaySortOrder ( ) = = SORT_ORDER_ASC ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_DESELECTED , GetID ( ) , CONTROL_BTNSORTASC ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> else <nl> { <nl> CGUIMessage msg ( GUI_MSG_SELECTED , GetID ( ) , CONTROL_BTNSORTASC ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> } <nl> <nl> mmm a / xbmc / GUIViewControl . cpp <nl> ppp b / xbmc / GUIViewControl . cpp <nl> <nl> * / <nl> <nl> # include " GUIViewControl . h " <nl> + # include " GUIWindowManager . h " <nl> # include " Util . h " <nl> # include " FileItem . h " <nl> # include " LocalizeStrings . h " <nl> void CGUIViewControl : : SetCurrentView ( int viewMode ) <nl> if ( hasFocus ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_SETFOCUS , m_parentWindow , pNewView - > GetID ( ) , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> / / Update it with the contents <nl> void CGUIViewControl : : UpdateContents ( const CGUIControl * control , int currentItem <nl> { <nl> if ( ! control | | ! m_fileItems ) return ; <nl> CGUIMessage msg ( GUI_MSG_LABEL_BIND , m_parentWindow , control - > GetID ( ) , currentItem , 0 , m_fileItems ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> void CGUIViewControl : : UpdateView ( ) <nl> int CGUIViewControl : : GetSelectedItem ( const CGUIControl * control ) const <nl> { <nl> if ( ! control | | ! m_fileItems ) return - 1 ; <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , m_parentWindow , control - > GetID ( ) ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> int iItem = msg . GetParam1 ( ) ; <nl> if ( iItem > = m_fileItems - > Size ( ) ) <nl> void CGUIViewControl : : SetSelectedItem ( int item ) <nl> return ; / / no valid current view ! <nl> <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECT , m_parentWindow , m_visibleViews [ m_currentView ] - > GetID ( ) , item ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> void CGUIViewControl : : SetSelectedItem ( const CStdString & itemPath ) <nl> void CGUIViewControl : : SetFocused ( ) <nl> return ; / / no valid current view ! <nl> <nl> CGUIMessage msg ( GUI_MSG_SETFOCUS , m_parentWindow , m_visibleViews [ m_currentView ] - > GetID ( ) , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> bool CGUIViewControl : : HasControl ( int viewControlID ) const <nl> void CGUIViewControl : : Clear ( ) <nl> return ; / / no valid current view ! <nl> <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , m_parentWindow , m_visibleViews [ m_currentView ] - > GetID ( ) , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> int CGUIViewControl : : GetView ( VIEW_TYPE type , int id ) const <nl> void CGUIViewControl : : UpdateViewAsControl ( const CStdString & viewLabel ) <nl> { <nl> / / the view as control could be a select / spin / dropdown button <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , m_parentWindow , m_viewAsControl ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> for ( unsigned int i = 0 ; i < m_visibleViews . size ( ) ; i + + ) <nl> { <nl> CGUIBaseContainer * view = ( CGUIBaseContainer * ) m_visibleViews [ i ] ; <nl> void CGUIViewControl : : UpdateViewAsControl ( const CStdString & viewLabel ) <nl> CStdString label ; <nl> label . Format ( g_localizeStrings . Get ( 534 ) . c_str ( ) , view - > GetLabel ( ) . c_str ( ) ) ; / / View : % s <nl> msg . SetLabel ( label ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> CGUIMessage msgSelect ( GUI_MSG_ITEM_SELECT , m_parentWindow , m_viewAsControl , m_currentView ) ; <nl> - g_graphicsContext . SendMessage ( msgSelect ) ; <nl> + m_gWindowManager . SendMessage ( msgSelect ) ; <nl> <nl> / / otherwise it ' s just a normal button <nl> CStdString label ; <nl> label . Format ( g_localizeStrings . Get ( 534 ) . c_str ( ) , viewLabel . c_str ( ) ) ; / / View : % s <nl> CGUIMessage msgSet ( GUI_MSG_LABEL_SET , m_parentWindow , m_viewAsControl ) ; <nl> msgSet . SetLabel ( label ) ; <nl> - g_graphicsContext . SendMessage ( msgSet ) ; <nl> + m_gWindowManager . SendMessage ( msgSet ) ; <nl> } <nl> <nl> void CGUIViewControl : : UpdateViewVisibility ( ) <nl> mmm a / xbmc / GUIWindowFileManager . cpp <nl> ppp b / xbmc / GUIWindowFileManager . cpp <nl> bool CGUIWindowFileManager : : OnMessage ( CGUIMessage & message ) <nl> { <nl> / / move to next item <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECT , GetID ( ) , iControl , iItem + 1 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> } <nl> else if ( iAction = = ACTION_SELECT_ITEM | | iAction = = ACTION_MOUSE_LEFT_DOUBLE_CLICK ) <nl> void CGUIWindowFileManager : : OnSort ( int iList ) <nl> void CGUIWindowFileManager : : ClearFileItems ( int iList ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , GetID ( ) , iList + CONTROL_LEFT_LIST ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> m_vecItems [ iList ] - > Clear ( ) ; / / will clean up everything <nl> } <nl> void CGUIWindowFileManager : : UpdateButtons ( ) <nl> if ( bSortOrder ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_DESELECTED , GetID ( ) , CONTROL_BTNSORTASC ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> else <nl> { <nl> CGUIMessage msg ( GUI_MSG_SELECTED , GetID ( ) , CONTROL_BTNSORTASC ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> * / <nl> bool CGUIWindowFileManager : : HaveDiscOrConnection ( CStdString & strPath , int iDriv <nl> void CGUIWindowFileManager : : UpdateControl ( int iList , int item ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_LABEL_BIND , GetID ( ) , iList + CONTROL_LEFT_LIST , item , 0 , m_vecItems [ iList ] ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> <nl> void CGUIWindowFileManager : : OnMark ( int iList , int iItem ) <nl> mmm a / xbmc / GUIWindowMusicBase . cpp <nl> ppp b / xbmc / GUIWindowMusicBase . cpp <nl> bool CGUIWindowMusicBase : : OnMessage ( CGUIMessage & message ) <nl> m_gWindowManager . ChangeActiveWindow ( nWindow ) ; <nl> <nl> CGUIMessage msg2 ( GUI_MSG_SETFOCUS , g_stSettings . m_iMyMusicStartWindow , CONTROL_BTNTYPE ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> <nl> return true ; <nl> } <nl> void CGUIWindowMusicBase : : UpdateButtons ( ) <nl> <nl> / / Remove labels from the window selection <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , GetID ( ) , CONTROL_BTNTYPE ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> / / Add labels to the window selection <nl> CGUIMessage msg2 ( GUI_MSG_LABEL_ADD , GetID ( ) , CONTROL_BTNTYPE ) ; <nl> msg2 . SetLabel ( g_localizeStrings . Get ( 744 ) ) ; / / Files <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> <nl> msg2 . SetLabel ( g_localizeStrings . Get ( 15100 ) ) ; / / Library <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> <nl> / / Select the current window as default item <nl> CONTROL_SELECT_ITEM ( CONTROL_BTNTYPE , g_stSettings . m_iMyMusicStartWindow - WINDOW_MUSIC_FILES ) ; <nl> mmm a / xbmc / GUIWindowMusicInfo . cpp <nl> ppp b / xbmc / GUIWindowMusicInfo . cpp <nl> <nl> * / <nl> <nl> # include " GUIWindowMusicInfo . h " <nl> + # include " GUIWindowManager . h " <nl> # include " Util . h " <nl> # include " GUIImage . h " <nl> # include " Picture . h " <nl> bool CGUIWindowMusicInfo : : OnMessage ( CGUIMessage & message ) <nl> if ( m_bArtistInfo & & ( ACTION_SELECT_ITEM = = iAction | | ACTION_MOUSE_LEFT_CLICK = = iAction ) ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , iControl ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> int iItem = msg . GetParam1 ( ) ; <nl> if ( iItem < 0 | | iItem > = ( int ) m_albumSongs - > Size ( ) ) <nl> break ; <nl> void CGUIWindowMusicInfo : : OnGetThumb ( ) <nl> / / tell our GUI to completely reload all controls ( as some of them <nl> / / are likely to have had this image in use so will need refreshing ) <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_REFRESH_THUMBS ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> / / Update our screen <nl> Update ( ) ; <nl> } <nl> void CGUIWindowMusicInfo : : OnGetFanart ( ) <nl> / / tell our GUI to completely reload all controls ( as some of them <nl> / / are likely to have had this image in use so will need refreshing ) <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_REFRESH_THUMBS ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> / / Update our screen <nl> Update ( ) ; <nl> } <nl> mmm a / xbmc / GUIWindowMusicNav . cpp <nl> ppp b / xbmc / GUIWindowMusicNav . cpp <nl> void CGUIWindowMusicNav : : SetThumb ( int iItem , CONTEXT_BUTTON button ) <nl> CMusicDatabaseDirectory dir ; <nl> dir . ClearDirectoryCache ( m_vecItems - > m_strPath ) ; <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_REFRESH_THUMBS ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> Update ( m_vecItems - > m_strPath ) ; <nl> } <nl> else <nl> mmm a / xbmc / GUIWindowMusicOverlay . cpp <nl> ppp b / xbmc / GUIWindowMusicOverlay . cpp <nl> bool CGUIWindowMusicOverlay : : OnMessage ( CGUIMessage & message ) <nl> if ( message . GetParam1 ( ) = = ACTION_SELECT_ITEM ) <nl> { / / switch to fullscreen visualisation mode . . . <nl> CGUIMessage msg ( GUI_MSG_FULLSCREEN , 0 , GetID ( ) ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> } <nl> } <nl> bool CGUIWindowMusicOverlay : : OnMouse ( const CPoint & point ) <nl> if ( g_Mouse . bClick [ MOUSE_LEFT_BUTTON ] ) <nl> { / / send mouse message <nl> CGUIMessage message ( GUI_MSG_FULLSCREEN , CONTROL_LOGO_PIC , GetID ( ) ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> / / reset the mouse button <nl> g_Mouse . bClick [ MOUSE_LEFT_BUTTON ] = false ; <nl> } <nl> mmm a / xbmc / GUIWindowPictures . cpp <nl> ppp b / xbmc / GUIWindowPictures . cpp <nl> void CGUIWindowPictures : : UpdateButtons ( ) <nl> if ( g_guiSettings . GetBool ( " slideshow . shuffle " ) ) <nl> { <nl> CGUIMessage msg2 ( GUI_MSG_SELECTED , GetID ( ) , CONTROL_SHUFFLE ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> else <nl> { <nl> CGUIMessage msg2 ( GUI_MSG_DESELECTED , GetID ( ) , CONTROL_SHUFFLE ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> <nl> / / check we can slideshow or recursive slideshow <nl> mmm a / xbmc / GUIWindowSettingsCategory . cpp <nl> ppp b / xbmc / GUIWindowSettingsCategory . cpp <nl> void CGUIWindowSettingsCategory : : OnSettingChanged ( CBaseSettingControl * pSettingC <nl> { / / new resolution choosen . . . - update if necessary <nl> int iControlID = pSettingControl - > GetID ( ) ; <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , iControlID ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> m_NewResolution = ( RESOLUTION ) msg . GetParam1 ( ) ; <nl> / / reset our skin if necessary <nl> / / delay change of resolution <nl> void CGUIWindowSettingsCategory : : OnSettingChanged ( CBaseSettingControl * pSettingC <nl> { <nl> int iControlID = pSettingControl - > GetID ( ) ; <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , iControlID ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> / / DXMERGE : This may be useful <nl> / / g_videoConfig . SetVSyncMode ( ( VSYNC ) msg . GetParam1 ( ) ) ; <nl> } <nl> void CGUIWindowSettingsCategory : : OnSettingChanged ( CBaseSettingControl * pSettingC <nl> CSettingInt * pSettingInt = ( CSettingInt * ) pSettingControl - > GetSetting ( ) ; <nl> int iControlID = pSettingControl - > GetID ( ) ; <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , iControlID ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> pSettingInt - > SetData ( msg . GetParam1 ( ) ) ; <nl> } <nl> else if ( strSetting . Equals ( " videoscreen . flickerfilter " ) | | strSetting . Equals ( " videoscreen . soften " ) ) <nl> void CGUIWindowSettingsCategory : : FillInVisualisations ( CSetting * pSetting , int iC <nl> int iWinID = m_gWindowManager . GetActiveWindow ( ) ; <nl> { <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , iWinID , iControlID ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> vector < CStdString > vecVis ; <nl> / / find visz . . . . <nl> void CGUIWindowSettingsCategory : : FillInVisualisations ( CSetting * pSetting , int iC <nl> { <nl> CGUIMessage msg ( GUI_MSG_LABEL_ADD , iWinID , iControlID , iVis + + ) ; <nl> msg . SetLabel ( 231 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> for ( int i = 0 ; i < ( int ) vecVis . size ( ) ; + + i ) <nl> { <nl> void CGUIWindowSettingsCategory : : FillInVisualisations ( CSetting * pSetting , int iC <nl> { <nl> CGUIMessage msg ( GUI_MSG_LABEL_ADD , iWinID , iControlID , iVis + + ) ; <nl> msg . SetLabel ( strVis ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> } <nl> { <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECT , iWinID , iControlID , iCurrentVis ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> } <nl> <nl> mmm a / xbmc / GUIWindowSettingsProfile . cpp <nl> ppp b / xbmc / GUIWindowSettingsProfile . cpp <nl> bool CGUIWindowSettingsProfile : : OnAction ( const CAction & action ) <nl> int CGUIWindowSettingsProfile : : GetSelectedItem ( ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , CONTROL_PROFILES ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> return msg . GetParam1 ( ) ; <nl> } <nl> void CGUIWindowSettingsProfile : : OnPopupMenu ( int iItem ) <nl> unsigned iCtrlID = GetFocusedControlID ( ) ; <nl> g_application . StopPlaying ( ) ; <nl> CGUIMessage msg2 ( GUI_MSG_ITEM_SELECTED , m_gWindowManager . GetActiveWindow ( ) , iCtrlID ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> g_application . getNetwork ( ) . NetworkMessage ( CNetwork : : SERVICES_DOWN , 1 ) ; <nl> bool bOldMaster = g_passwordManager . bMasterUser ; <nl> g_passwordManager . bMasterUser = true ; <nl> bool CGUIWindowSettingsProfile : : OnMessage ( CGUIMessage & message ) <nl> ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_ITEM_SELECTED , GetID ( ) , CONTROL_PROFILES ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> int iItem = msg . GetParam1 ( ) ; <nl> if ( iAction = = ACTION_CONTEXT_MENU | | iAction = = ACTION_MOUSE_RIGHT_CLICK ) <nl> { <nl> void CGUIWindowSettingsProfile : : LoadList ( ) <nl> item - > SetThumbnailImage ( profile . getThumb ( ) ) ; <nl> item - > SetOverlayImage ( profile . getLockMode ( ) = = LOCK_MODE_EVERYONE ? CGUIListItem : : ICON_OVERLAY_NONE : CGUIListItem : : ICON_OVERLAY_LOCKED ) ; <nl> CGUIMessage msg ( GUI_MSG_LABEL_ADD , GetID ( ) , CONTROL_PROFILES , 0 , 0 , item ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> m_vecListItems . push_back ( item ) ; <nl> } <nl> { <nl> CFileItemPtr item ( new CFileItem ( g_localizeStrings . Get ( 20058 ) ) ) ; <nl> CGUIMessage msg ( GUI_MSG_LABEL_ADD , GetID ( ) , CONTROL_PROFILES , 0 , 0 , item ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> item - > m_strPath . Empty ( ) ; <nl> m_vecListItems . push_back ( item ) ; <nl> } <nl> void CGUIWindowSettingsProfile : : LoadList ( ) <nl> void CGUIWindowSettingsProfile : : ClearListItems ( ) <nl> { <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , GetID ( ) , CONTROL_PROFILES ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> m_vecListItems . erase ( m_vecListItems . begin ( ) , m_vecListItems . end ( ) ) ; <nl> } <nl> mmm a / xbmc / GUIWindowVideoBase . cpp <nl> ppp b / xbmc / GUIWindowVideoBase . cpp <nl> bool CGUIWindowVideoBase : : OnMessage ( CGUIMessage & message ) <nl> g_settings . Save ( ) ; <nl> m_gWindowManager . ChangeActiveWindow ( nNewWindow ) ; <nl> CGUIMessage msg2 ( GUI_MSG_SETFOCUS , nNewWindow , CONTROL_BTNTYPE ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> <nl> return true ; <nl> void CGUIWindowVideoBase : : UpdateButtons ( ) <nl> { <nl> / / Remove labels from the window selection <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , GetID ( ) , CONTROL_BTNTYPE ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> <nl> / / Add labels to the window selection <nl> CStdString strItem = g_localizeStrings . Get ( 744 ) ; / / Files <nl> CGUIMessage msg2 ( GUI_MSG_LABEL_ADD , GetID ( ) , CONTROL_BTNTYPE ) ; <nl> msg2 . SetLabel ( strItem ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> <nl> strItem = g_localizeStrings . Get ( 14022 ) ; / / Library <nl> msg2 . SetLabel ( strItem ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> <nl> / / Select the current window as default item <nl> int nWindow = g_stSettings . m_iVideoStartWindow - WINDOW_VIDEO_FILES ; <nl> mmm a / xbmc / GUIWindowVideoInfo . cpp <nl> ppp b / xbmc / GUIWindowVideoInfo . cpp <nl> void CGUIWindowVideoInfo : : Update ( ) <nl> if ( m_hasUpdatedThumb ) <nl> { <nl> CGUIMessage reload ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_REFRESH_THUMBS ) ; <nl> - g_graphicsContext . SendMessage ( reload ) ; <nl> + m_gWindowManager . SendMessage ( reload ) ; <nl> } <nl> } <nl> <nl> mmm a / xbmc / GUIWindowVideoNav . cpp <nl> ppp b / xbmc / GUIWindowVideoNav . cpp <nl> bool CGUIWindowVideoNav : : OnContextButton ( int itemNumber , CONTEXT_BUTTON button ) <nl> <nl> CUtil : : DeleteVideoDatabaseDirectoryCache ( ) ; <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_REFRESH_THUMBS ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> Update ( m_vecItems - > m_strPath ) ; <nl> <nl> return true ; <nl> mmm a / xbmc / GUIWindowVisualisation . cpp <nl> ppp b / xbmc / GUIWindowVisualisation . cpp <nl> bool CGUIWindowVisualisation : : OnAction ( const CAction & action ) <nl> case ACTION_VIS_PRESET_LOCK : <nl> { / / show the locked icon + fall through so that the vis handles the locking <nl> CGUIMessage msg ( GUI_MSG_GET_VISUALISATION , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> if ( msg . GetPointer ( ) ) <nl> { <nl> CVisualisation * pVis = ( CVisualisation * ) msg . GetPointer ( ) ; <nl> mmm a / xbmc / GUIWindowWeather . cpp <nl> ppp b / xbmc / GUIWindowWeather . cpp <nl> void CGUIWindowWeather : : UpdateLocations ( ) <nl> if ( ! IsActive ( ) ) return ; <nl> <nl> CGUIMessage msg ( GUI_MSG_LABEL_RESET , GetID ( ) , CONTROL_SELECTLOCATION ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> CGUIMessage msg2 ( GUI_MSG_LABEL_ADD , GetID ( ) , CONTROL_SELECTLOCATION ) ; <nl> <nl> for ( unsigned int i = 0 ; i < MAX_LOCATION ; i + + ) <nl> void CGUIWindowWeather : : UpdateLocations ( ) <nl> } <nl> msg2 . SetParam1 ( i ) ; <nl> msg2 . SetLabel ( strLabel ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> else <nl> { <nl> void CGUIWindowWeather : : UpdateLocations ( ) <nl> <nl> msg2 . SetLabel ( strLabel ) ; <nl> msg2 . SetParam1 ( i ) ; <nl> - g_graphicsContext . SendMessage ( msg2 ) ; <nl> + m_gWindowManager . SendMessage ( msg2 ) ; <nl> } <nl> if ( i = = m_iCurWeather ) <nl> SET_CONTROL_LABEL ( CONTROL_SELECTLOCATION , strLabel ) ; <nl> mmm a / xbmc / cores / dvdplayer / DVDPlayer . cpp <nl> ppp b / xbmc / cores / dvdplayer / DVDPlayer . cpp <nl> <nl> <nl> # include " Util . h " <nl> # include " utils / GUIInfoManager . h " <nl> + # include " GUIWindowManager . h " <nl> # include " Application . h " <nl> # include " DVDPerformanceCounter . h " <nl> # include " FileSystem / cdioSupport . h " <nl> bool CDVDPlayer : : OnAction ( const CAction & action ) <nl> pStream - > OnMenu ( ) ; <nl> / / send a message to everyone that we ' ve gone to the menu <nl> CGUIMessage msg ( GUI_MSG_VIDEO_MENU_STARTED , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> return true ; <nl> } <nl> break ; <nl> mmm a / xbmc / lib / libPython / XBPython . cpp <nl> ppp b / xbmc / lib / libPython / XBPython . cpp <nl> XBPython : : ~ XBPython ( ) <nl> CloseHandle ( m_globalEvent ) ; <nl> } <nl> <nl> - bool XBPython : : SendMessage ( CGUIMessage & message ) <nl> - { <nl> - return ( evalFile ( message . GetStringParam ( ) . c_str ( ) ) ! = - 1 ) ; <nl> - } <nl> - <nl> / / message all registered callbacks that xbmc stopped playing <nl> void XBPython : : OnPlayBackEnded ( ) <nl> { <nl> mmm a / xbmc / lib / libPython / XBPython . h <nl> ppp b / xbmc / lib / libPython / XBPython . h <nl> <nl> * / <nl> <nl> # include " XBPyThread . h " <nl> - # include " IMsgSenderCallback . h " <nl> # include " cores / IPlayer . h " <nl> # include " utils / CriticalSection . h " <nl> <nl> typedef std : : vector < PyElem > PyList ; <nl> typedef std : : vector < PVOID > PlayerCallbackList ; <nl> typedef std : : vector < LibraryLoader * > PythonExtensionLibraries ; <nl> <nl> - class XBPython : public IMsgSenderCallback , public IPlayerCallback <nl> + class XBPython : public IPlayerCallback <nl> { <nl> public : <nl> XBPython ( ) ; <nl> virtual ~ XBPython ( ) ; <nl> - virtual bool SendMessage ( CGUIMessage & message ) ; <nl> virtual void OnPlayBackEnded ( ) ; <nl> virtual void OnPlayBackStarted ( ) ; <nl> virtual void OnPlayBackStopped ( ) ; <nl> mmm a / xbmc / utils / Builtins . cpp <nl> ppp b / xbmc / utils / Builtins . cpp <nl> int CBuiltins : : Execute ( const CStdString & execString ) <nl> <nl> CUtil : : DeleteVideoDatabaseDirectoryCache ( ) ; <nl> CGUIMessage msg ( GUI_MSG_NOTIFY_ALL , 0 , 0 , GUI_MSG_UPDATE ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> else if ( execute . Equals ( " takescreenshot " ) ) <nl> { <nl> int CBuiltins : : Execute ( const CStdString & execString ) <nl> int controlID = atol ( params [ 0 ] . c_str ( ) ) ; <nl> int subItem = ( params . size ( ) > 1 ) ? atol ( params [ 1 ] . c_str ( ) ) + 1 : 0 ; <nl> CGUIMessage msg ( GUI_MSG_SETFOCUS , m_gWindowManager . GetActiveWindow ( ) , controlID , subItem ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> } <nl> # ifdef HAS_PYTHON <nl> else if ( execute . Equals ( " runscript " ) & & params . size ( ) ) <nl> int CBuiltins : : Execute ( const CStdString & execString ) <nl> { <nl> int id = atoi ( parameter . c_str ( ) ) ; <nl> CGUIMessage message ( GUI_MSG_PAGE_DOWN , m_gWindowManager . GetFocusedWindow ( ) , id ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " pageup " ) ) <nl> { <nl> int id = atoi ( parameter . c_str ( ) ) ; <nl> CGUIMessage message ( GUI_MSG_PAGE_UP , m_gWindowManager . GetFocusedWindow ( ) , id ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " updatelibrary " ) & & params . size ( ) ) <nl> { <nl> int CBuiltins : : Execute ( const CStdString & execString ) <nl> else if ( execute . Equals ( " control . move " ) & & params . size ( ) > 1 ) <nl> { <nl> CGUIMessage message ( GUI_MSG_MOVE_OFFSET , m_gWindowManager . GetFocusedWindow ( ) , atoi ( params [ 0 ] . c_str ( ) ) , atoi ( params [ 1 ] . c_str ( ) ) ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . refresh " ) ) <nl> { / / NOTE : These messages require a media window , thus they ' re sent to the current activewindow . <nl> / / This shouldn ' t stop a dialog intercepting it though . <nl> CGUIMessage message ( GUI_MSG_NOTIFY_ALL , m_gWindowManager . GetActiveWindow ( ) , 0 , GUI_MSG_UPDATE , 1 ) ; / / 1 to reset the history <nl> message . SetStringParam ( parameter ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . update " ) & & params . size ( ) ) <nl> { <nl> int CBuiltins : : Execute ( const CStdString & execString ) <nl> message . SetStringParam ( params [ 0 ] ) ; <nl> if ( params . size ( ) > 1 & & params [ 1 ] . CompareNoCase ( " replace " ) = = 0 ) <nl> message . SetParam2 ( 1 ) ; / / reset the history <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . nextviewmode " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_VIEW_MODE , m_gWindowManager . GetActiveWindow ( ) , 0 , 0 , 1 ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . previousviewmode " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_VIEW_MODE , m_gWindowManager . GetActiveWindow ( ) , 0 , 0 , - 1 ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . setviewmode " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_VIEW_MODE , m_gWindowManager . GetActiveWindow ( ) , 0 , atoi ( parameter . c_str ( ) ) ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . nextsortmethod " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_SORT_METHOD , m_gWindowManager . GetActiveWindow ( ) , 0 , 0 , 1 ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . previoussortmethod " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_SORT_METHOD , m_gWindowManager . GetActiveWindow ( ) , 0 , 0 , - 1 ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . setsortmethod " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_SORT_METHOD , m_gWindowManager . GetActiveWindow ( ) , 0 , atoi ( parameter . c_str ( ) ) ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " container . sortdirection " ) ) <nl> { <nl> CGUIMessage message ( GUI_MSG_CHANGE_SORT_DIRECTION , m_gWindowManager . GetActiveWindow ( ) , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else if ( execute . Equals ( " control . message " ) & & params . size ( ) > = 2 ) <nl> { <nl> int controlID = atoi ( params [ 0 ] . c_str ( ) ) ; <nl> int windowID = ( params . size ( ) = = 3 ) ? CButtonTranslator : : TranslateWindowString ( params [ 2 ] . c_str ( ) ) : m_gWindowManager . GetActiveWindow ( ) ; <nl> if ( params [ 1 ] = = " moveup " ) <nl> - g_graphicsContext . SendMessage ( GUI_MSG_MOVE_OFFSET , windowID , controlID , 1 ) ; <nl> + m_gWindowManager . SendMessage ( GUI_MSG_MOVE_OFFSET , windowID , controlID , 1 ) ; <nl> else if ( params [ 1 ] = = " movedown " ) <nl> - g_graphicsContext . SendMessage ( GUI_MSG_MOVE_OFFSET , windowID , controlID , - 1 ) ; <nl> + m_gWindowManager . SendMessage ( GUI_MSG_MOVE_OFFSET , windowID , controlID , - 1 ) ; <nl> else if ( params [ 1 ] = = " pageup " ) <nl> - g_graphicsContext . SendMessage ( GUI_MSG_PAGE_UP , windowID , controlID ) ; <nl> + m_gWindowManager . SendMessage ( GUI_MSG_PAGE_UP , windowID , controlID ) ; <nl> else if ( params [ 1 ] = = " pagedown " ) <nl> - g_graphicsContext . SendMessage ( GUI_MSG_PAGE_DOWN , windowID , controlID ) ; <nl> + m_gWindowManager . SendMessage ( GUI_MSG_PAGE_DOWN , windowID , controlID ) ; <nl> else if ( params [ 1 ] = = " click " ) <nl> - g_graphicsContext . SendMessage ( GUI_MSG_CLICKED , controlID , windowID ) ; <nl> + m_gWindowManager . SendMessage ( GUI_MSG_CLICKED , controlID , windowID ) ; <nl> } <nl> else if ( execute . Equals ( " sendclick " ) & & params . size ( ) ) <nl> { <nl> int CBuiltins : : Execute ( const CStdString & execString ) <nl> / / have a window - convert it <nl> int windowID = CButtonTranslator : : TranslateWindowString ( params [ 0 ] . c_str ( ) ) ; <nl> CGUIMessage message ( GUI_MSG_CLICKED , atoi ( params [ 1 ] . c_str ( ) ) , windowID ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> else <nl> { / / single param - assume you meant the active window <nl> CGUIMessage message ( GUI_MSG_CLICKED , atoi ( params [ 0 ] . c_str ( ) ) , m_gWindowManager . GetActiveWindow ( ) ) ; <nl> - g_graphicsContext . SendMessage ( message ) ; <nl> + m_gWindowManager . SendMessage ( message ) ; <nl> } <nl> } <nl> else if ( execute . Equals ( " action " ) & & params . size ( ) ) <nl> mmm a / xbmc / utils / GUIInfoManager . cpp <nl> ppp b / xbmc / utils / GUIInfoManager . cpp <nl> CStdString CGUIInfoManager : : GetLabel ( int info , int contextWindow ) <nl> case VISUALISATION_PRESET : <nl> { <nl> CGUIMessage msg ( GUI_MSG_GET_VISUALISATION , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> if ( msg . GetPointer ( ) ) <nl> { <nl> CVisualisation * pVis = ( CVisualisation * ) msg . GetPointer ( ) ; <nl> bool CGUIInfoManager : : GetBool ( int condition1 , int contextWindow , const CGUIListI <nl> case VISUALISATION_LOCKED : <nl> { <nl> CGUIMessage msg ( GUI_MSG_GET_VISUALISATION , 0 , 0 ) ; <nl> - g_graphicsContext . SendMessage ( msg ) ; <nl> + m_gWindowManager . SendMessage ( msg ) ; <nl> if ( msg . GetPointer ( ) ) <nl> { <nl> CVisualisation * pVis = ( CVisualisation * ) msg . GetPointer ( ) ; <nl>
changed : Get rid of the use of g_graphicsContext to send messages ( all it did was passed them on to the window manager . )
xbmc/xbmc
363c74fafa695c1bfb23c0bf34f35ba69c1212ec
2009-10-07T01:27:50Z
mmm a / tools / swift / Immediate . cpp <nl> ppp b / tools / swift / Immediate . cpp <nl> static void appendEscapeSequence ( SmallVectorImpl < wchar_t > & dest , <nl> dest . push_back ( LITERAL_MODE_CHAR ) ; <nl> } <nl> <nl> + / / / RAII and Swift - specific setup wrapper for EditLine . All of its methods <nl> + / / / must be usable from a separate thread and so shouldn ' t touch anything <nl> + / / / outside of the EditLine , History , and member object state . <nl> + / / / <nl> + / / / FIXME : Need the TU for completions - - use a lock ? <nl> struct EditLineWrapper { <nl> TranslationUnit * TU ; <nl> <nl> static void printOrDumpDecl ( Decl * d , PrintOrDump which ) { <nl> d - > dump ( ) ; <nl> } <nl> <nl> + enum class REPLInputKind { <nl> + / / / The REPL got a " quit " signal . <nl> + REPLQuit , <nl> + / / / Empty whitespace - only input . <nl> + Empty , <nl> + / / / A REPL directive , such as ' : help ' . <nl> + REPLDirective , <nl> + / / / Swift source code . <nl> + SourceCode , <nl> + } ; <nl> + <nl> + / / NOTE : This code has to be able to run in its own thread . It should not touch <nl> + / / anything other than the EditLineWrapper and Line objects . <nl> + static REPLInputKind getREPLInput ( EditLineWrapper & e , <nl> + llvm : : SmallVectorImpl < char > & Line ) { <nl> + unsigned BraceCount = 0 ; <nl> + bool HadLineContinuation = false ; <nl> + unsigned CurChunkLines = 0 ; <nl> + <nl> + Line . clear ( ) ; <nl> + <nl> + do { <nl> + / / Read one line . <nl> + e . PromptContinuationLevel = BraceCount ; <nl> + e . NeedPromptContinuation = BraceCount ! = 0 | | HadLineContinuation ; <nl> + e . PromptedForLine = false ; <nl> + e . Outdented = false ; <nl> + int LineCount ; <nl> + size_t LineStart = Line . size ( ) ; <nl> + const wchar_t * WLine = el_wgets ( e , & LineCount ) ; <nl> + if ( ! WLine ) { <nl> + / / End - of - file . <nl> + if ( e . PromptedForLine ) <nl> + printf ( " \ n " ) ; <nl> + return REPLInputKind : : REPLQuit ; <nl> + } <nl> + <nl> + size_t indent = e . PromptContinuationLevel * 2 ; <nl> + Line . append ( indent , ' ' ) ; <nl> + <nl> + convertToUTF8 ( llvm : : makeArrayRef ( WLine , WLine + wcslen ( WLine ) ) , Line ) ; <nl> + <nl> + / / Special - case backslash for line continuations in the REPL . <nl> + if ( Line . size ( ) > 2 & & Line . end ( ) [ - 1 ] = = ' \ n ' & & Line . end ( ) [ - 2 ] = = ' \ \ ' ) { <nl> + HadLineContinuation = true ; <nl> + Line . erase ( Line . end ( ) - 2 ) ; <nl> + } else { <nl> + HadLineContinuation = false ; <nl> + } <nl> + <nl> + / / Enter the line into the line history . <nl> + / / FIXME : We should probably be a bit more clever here about which lines we <nl> + / / put into the history and when we put them in . <nl> + HistEventW ev ; <nl> + history_w ( e . h , & ev , H_ENTER , WLine ) ; <nl> + <nl> + + + CurChunkLines ; <nl> + <nl> + / / If we detect a line starting with a colon , treat it as a special <nl> + / / REPL escape . <nl> + char const * p = Line . data ( ) + LineStart ; <nl> + while ( p < Line . end ( ) & & isspace ( * p ) ) { <nl> + + + p ; <nl> + } <nl> + if ( p = = Line . end ( ) ) <nl> + return REPLInputKind : : Empty ; <nl> + <nl> + if ( CurChunkLines = = 1 & & BraceCount = = 0 & & * p = = ' : ' ) <nl> + return REPLInputKind : : REPLDirective ; <nl> + <nl> + / / If we detect unbalanced braces , keep reading before <nl> + / / we start parsing . <nl> + while ( p < Line . end ( ) ) { <nl> + if ( * p = = ' { ' | | * p = = ' ( ' | | * p = = ' [ ' ) <nl> + + + BraceCount ; <nl> + else if ( * p = = ' } ' | | * p = = ' ) ' | | * p = = ' ] ' ) <nl> + - - BraceCount ; <nl> + + + p ; <nl> + } <nl> + } while ( BraceCount ! = 0 | | HadLineContinuation ) ; <nl> + <nl> + / / The lexer likes null - terminated data . <nl> + Line . push_back ( ' \ 0 ' ) ; <nl> + Line . pop_back ( ) ; <nl> + <nl> + return REPLInputKind : : SourceCode ; <nl> + } <nl> + <nl> void swift : : REPL ( ASTContext & Context ) { <nl> / / FIXME : We should do something a bit more elaborate than <nl> / / " allocate a 1MB buffer and hope it ' s enough " . <nl> + static const size_t BUFFER_SIZE = 1 < < 20 ; <nl> llvm : : MemoryBuffer * Buffer = <nl> - llvm : : MemoryBuffer : : getNewMemBuffer ( 1 < < 20 , " < REPL Buffer > " ) ; <nl> + llvm : : MemoryBuffer : : getNewMemBuffer ( BUFFER_SIZE , " < REPL Buffer > " ) ; <nl> <nl> Component * Comp = new ( Context . Allocate < Component > ( 1 ) ) Component ( ) ; <nl> unsigned BufferID = <nl> void swift : : REPL ( ASTContext & Context ) { <nl> <nl> EditLineWrapper e ( TU ) ; <nl> <nl> - char * CurBuffer = const_cast < char * > ( Buffer - > getBufferStart ( ) ) ; <nl> - unsigned CurBufferOffset = 0 ; <nl> - unsigned CurBufferEndOffset = 0 ; <nl> + char * BufferStart = const_cast < char * > ( Buffer - > getBufferStart ( ) ) ; <nl> <nl> unsigned CurTUElem = 0 ; <nl> unsigned CurIRGenElem = 0 ; <nl> - unsigned BraceCount = 0 ; <nl> - bool HadLineContinuation = false ; <nl> - unsigned CurChunkLines = 0 ; <nl> <nl> / / Force swift . swift to be parsed / type - checked immediately . This forces <nl> / / any errors to appear upfront , and helps eliminate some nasty lag after <nl> / / the first statement is typed into the REPL . <nl> const char importstmt [ ] = " import swift \ n " ; <nl> - strcpy ( CurBuffer , importstmt ) ; <nl> - CurBuffer + = strlen ( importstmt ) ; <nl> - CurBufferEndOffset + = strlen ( importstmt ) ; <nl> - char * LastValidLineEnd = CurBuffer ; <nl> + strcpy ( BufferStart , importstmt ) ; <nl> <nl> + unsigned BufferOffset = 0 ; <nl> swift : : appendToMainTranslationUnit ( TU , BufferID , CurTUElem , <nl> - CurBufferOffset , <nl> - CurBufferEndOffset ) ; <nl> + / * startOffset * / BufferOffset , <nl> + / * endOffset * / strlen ( importstmt ) ) ; <nl> if ( Context . hadError ( ) ) <nl> return ; <nl> <nl> void swift : : REPL ( ASTContext & Context ) { <nl> printf ( " % s " , " Welcome to swift . Type ' : help ' for assistance . \ n " ) ; <nl> <nl> while ( 1 ) { <nl> - / / Read one line . <nl> - e . PromptContinuationLevel = BraceCount ; <nl> - e . NeedPromptContinuation = BraceCount ! = 0 | | HadLineContinuation ; <nl> - e . PromptedForLine = false ; <nl> - e . Outdented = false ; <nl> - int LineCount ; <nl> - const wchar_t * WLine = el_wgets ( e , & LineCount ) ; <nl> - if ( ! WLine ) { <nl> - if ( e . PromptedForLine ) <nl> - printf ( " \ n " ) ; <nl> - return ; <nl> - } <nl> - <nl> + / / Get the next input from the REPL . <nl> llvm : : SmallString < 80 > Line ; <nl> - convertToUTF8 ( llvm : : makeArrayRef ( WLine , WLine + wcslen ( WLine ) ) , Line ) ; <nl> - <nl> - size_t indent = e . PromptContinuationLevel * 2 ; <nl> - memset ( CurBuffer , ' ' , indent ) ; <nl> - CurBuffer + = indent ; <nl> - size_t LineLen = Line . size ( ) ; <nl> - memcpy ( CurBuffer , Line . c_str ( ) , LineLen ) ; <nl> - <nl> - / / Special - case backslash for line continuations in the REPL . <nl> - if ( LineLen > 1 & & Line [ LineLen - 1 ] = = ' \ n ' & & Line [ LineLen - 2 ] = = ' \ \ ' ) { <nl> - HadLineContinuation = true ; <nl> - CurBuffer [ LineLen - 2 ] = ' \ n ' ; <nl> - CurBuffer [ LineLen - 1 ] = ' \ 0 ' ; <nl> - LineLen - = 1 ; <nl> - } else { <nl> - HadLineContinuation = false ; <nl> - } <nl> - <nl> - / / Enter the line into the line history . <nl> - / / FIXME : We should probably be a bit more clever here about which lines we <nl> - / / put into the history and when we put them in . <nl> - HistEventW ev ; <nl> - history_w ( e . h , & ev , H_ENTER , WLine ) ; <nl> + REPLInputKind inputKind = getREPLInput ( e , Line ) ; <nl> <nl> - CurBuffer + = LineLen ; <nl> - CurBufferEndOffset + = LineLen + indent ; <nl> - + + CurChunkLines ; <nl> - <nl> - / / If we detect a line starting with a colon , treat it as a special <nl> - / / REPL escape . If we detect unbalanced braces , keep reading before <nl> - / / we start parsing . <nl> Lexer L ( Line , Context . SourceMgr , nullptr ) ; <nl> - Token Tok ; <nl> - L . lex ( Tok ) ; <nl> - if ( CurChunkLines = = 1 & & ! BraceCount & & Tok . is ( tok : : colon ) ) { <nl> + switch ( inputKind ) { <nl> + case REPLInputKind : : REPLQuit : <nl> + return ; <nl> + <nl> + case REPLInputKind : : Empty : <nl> + break ; <nl> + <nl> + case REPLInputKind : : REPLDirective : { <nl> + Token Tok ; <nl> + L . lex ( Tok ) ; <nl> + assert ( Tok . is ( tok : : colon ) ) ; <nl> + <nl> if ( L . peekNextToken ( ) . getText ( ) = = " help " ) { <nl> printf ( " % s " , " Available commands : \ n " <nl> - " : quit - quit the interpreter ( you can also use : exit " <nl> - " or Control + D or exit ( 0 ) ) \ n " <nl> - " : constraints ( on | off ) - turn on / off the constraint - " <nl> - " based type checker \ n " <nl> - " : constraints debug ( on | off ) - turn on / off the debug " <nl> - " output for the constraint - based type checker \ n " <nl> - " : dump_ir - dump the LLVM IR generated by the REPL \ n " <nl> - " : dump_ast - dump the AST representation of " <nl> - " the REPL input \ n " <nl> - " : dump_decl < name > - dump the AST representation of the " <nl> - " named declarations \ n " <nl> - " : dump_source - dump the user input ( ignoring " <nl> - " lines with errors ) \ n " <nl> - " : print_decl < name > - print the AST representation of the " <nl> - " named declarations \ n " <nl> - " API documentation etc . will be here eventually . \ n " ) ; <nl> + " : quit - quit the interpreter ( you can also use : exit " <nl> + " or Control + D or exit ( 0 ) ) \ n " <nl> + " : constraints ( on | off ) - turn on / off the constraint - " <nl> + " based type checker \ n " <nl> + " : constraints debug ( on | off ) - turn on / off the debug " <nl> + " output for the constraint - based type checker \ n " <nl> + " : dump_ir - dump the LLVM IR generated by the REPL \ n " <nl> + " : dump_ast - dump the AST representation of " <nl> + " the REPL input \ n " <nl> + " : dump_decl < name > - dump the AST representation of the " <nl> + " named declarations \ n " <nl> + " : dump_source - dump the user input ( ignoring " <nl> + " lines with errors ) \ n " <nl> + " : print_decl < name > - print the AST representation of the " <nl> + " named declarations \ n " <nl> + " API documentation etc . will be here eventually . \ n " ) ; <nl> } else if ( L . peekNextToken ( ) . getText ( ) = = " quit " | | <nl> L . peekNextToken ( ) . getText ( ) = = " exit " ) { <nl> return ; <nl> void swift : : REPL ( ASTContext & Context ) { <nl> for ( auto result : lookup . Results ) { <nl> if ( result . hasValueDecl ( ) ) { <nl> printOrDumpDecl ( result . getValueDecl ( ) , doPrint ) ; <nl> - <nl> + <nl> if ( auto typeDecl = dyn_cast < TypeDecl > ( result . getValueDecl ( ) ) ) { <nl> if ( auto typeAliasDecl = dyn_cast < TypeAliasDecl > ( typeDecl ) ) { <nl> TypeDecl * origTypeDecl = typeAliasDecl - > getUnderlyingType ( ) <nl> void swift : : REPL ( ASTContext & Context ) { <nl> for ( auto ext : TU - > lookupExtensions ( type ) ) { <nl> extensions . push_back ( ext ) ; <nl> } <nl> - <nl> + <nl> llvm : : SmallPtrSet < swift : : Module * , 16 > visited ; <nl> for ( auto & impEntry : TU - > getImportedModules ( ) ) { <nl> if ( ! visited . insert ( impEntry . second ) ) <nl> continue ; <nl> - <nl> + <nl> / / FIXME : Don ' t visit clang modules twice . <nl> if ( isa < ClangModule > ( impEntry . second ) ) { <nl> if ( searchedClangModule ) <nl> continue ; <nl> - <nl> + <nl> searchedClangModule = true ; <nl> } <nl> - <nl> + <nl> for ( auto ext : impEntry . second - > lookupExtensions ( type ) ) { <nl> extensions . push_back ( ext ) ; <nl> } <nl> } <nl> - <nl> + <nl> for ( auto ext : extensions ) { <nl> printOrDumpDecl ( ext , doPrint ) ; <nl> } <nl> void swift : : REPL ( ASTContext & Context ) { <nl> } else { <nl> printf ( " % s " , " Unknown interpreter escape ; try : help \ n " ) ; <nl> } <nl> - <nl> - CurBufferOffset = CurBufferEndOffset ; <nl> - CurChunkLines = 0 ; <nl> - LastValidLineEnd = CurBuffer ; <nl> - continue ; <nl> + break ; <nl> } <nl> - do { <nl> - if ( Tok . is ( tok : : l_brace ) | | Tok . is ( tok : : l_paren_starting ) | | <nl> - Tok . is ( tok : : l_paren_following ) | | Tok . is ( tok : : l_square_starting ) | | <nl> - Tok . is ( tok : : l_square_following ) ) <nl> - + + BraceCount ; <nl> - else if ( ( Tok . is ( tok : : r_brace ) | | Tok . is ( tok : : r_paren ) | | <nl> - Tok . is ( tok : : r_square ) ) & & BraceCount > 0 ) <nl> - - - BraceCount ; <nl> - else if ( Tok . is ( tok : : eof ) ) <nl> + <nl> + case REPLInputKind : : SourceCode : { <nl> + assert ( Line . size ( ) < BUFFER_SIZE & & <nl> + " line too big for our stupid fixed - size repl buffer " ) ; <nl> + strcpy ( BufferStart , Line . c_str ( ) ) ; <nl> + BufferOffset = 0 ; <nl> + / / Parse the current line ( s ) . <nl> + bool ShouldRun = <nl> + swift : : appendToMainTranslationUnit ( TU , BufferID , CurTUElem , <nl> + BufferOffset , Line . size ( ) ) ; <nl> + <nl> + if ( Context . hadError ( ) ) { <nl> + Context . Diags . resetHadAnyError ( ) ; <nl> + while ( TU - > Decls . size ( ) > CurTUElem ) <nl> + TU - > Decls . pop_back ( ) ; <nl> + TU - > clearUnresolvedIdentifierTypes ( ) ; <nl> + <nl> + / / FIXME : Handling of " import " declarations ? Is there any other <nl> + / / state which needs to be reset ? <nl> + <nl> break ; <nl> + } <nl> <nl> - L . lex ( Tok ) ; <nl> - } while ( 1 ) ; <nl> + CurTUElem = TU - > Decls . size ( ) ; <nl> + <nl> + DumpSource + = Line ; <nl> <nl> - if ( BraceCount | | HadLineContinuation ) <nl> - continue ; <nl> + / / If we didn ' t see an expression , statement , or decl which might have <nl> + / / side - effects , keep reading . <nl> + if ( ! ShouldRun ) <nl> + continue ; <nl> <nl> - / / Parse the current line ( s ) . <nl> - bool ShouldRun = <nl> - swift : : appendToMainTranslationUnit ( TU , BufferID , CurTUElem , <nl> - CurBufferOffset , <nl> - CurBufferEndOffset ) ; <nl> - <nl> - if ( Context . hadError ( ) ) { <nl> - Context . Diags . resetHadAnyError ( ) ; <nl> - while ( TU - > Decls . size ( ) > CurTUElem ) <nl> - TU - > Decls . pop_back ( ) ; <nl> - TU - > clearUnresolvedIdentifierTypes ( ) ; <nl> - <nl> - / / FIXME : Handling of " import " declarations ? Is there any other <nl> - / / state which needs to be reset ? <nl> - <nl> - if ( CurChunkLines > 1 ) <nl> - llvm : : errs ( ) < < " ( discarded " < < CurChunkLines < < " lines ) \ n " ; <nl> - CurChunkLines = 0 ; <nl> - LastValidLineEnd = CurBuffer ; <nl> - continue ; <nl> - } <nl> + / / IRGen the current line ( s ) . <nl> + llvm : : Module LineModule ( " REPLLine " , LLVMContext ) ; <nl> + performCaptureAnalysis ( TU , CurIRGenElem ) ; <nl> + performIRGeneration ( Options , & LineModule , TU , / * sil = * / nullptr , <nl> + CurIRGenElem ) ; <nl> + CurIRGenElem = CurTUElem ; <nl> <nl> - CurTUElem = TU - > Decls . size ( ) ; <nl> - CurChunkLines = 0 ; <nl> - <nl> - DumpSource . append ( LastValidLineEnd , CurBuffer ) ; <nl> - LastValidLineEnd = CurBuffer ; <nl> + if ( Context . hadError ( ) ) <nl> + return ; <nl> <nl> - / / If we didn ' t see an expression , statement , or decl which might have <nl> - / / side - effects , keep reading . <nl> - if ( ! ShouldRun ) <nl> - continue ; <nl> + std : : string ErrorMessage ; <nl> + if ( llvm : : Linker : : LinkModules ( & Module , & LineModule , <nl> + llvm : : Linker : : PreserveSource , <nl> + & ErrorMessage ) ) { <nl> + llvm : : errs ( ) < < " Error linking swift modules \ n " ; <nl> + llvm : : errs ( ) < < ErrorMessage < < " \ n " ; <nl> + return ; <nl> + } <nl> + if ( llvm : : Linker : : LinkModules ( & DumpModule , & LineModule , <nl> + llvm : : Linker : : DestroySource , <nl> + & ErrorMessage ) ) { <nl> + llvm : : errs ( ) < < " Error linking swift modules \ n " ; <nl> + llvm : : errs ( ) < < ErrorMessage < < " \ n " ; <nl> + return ; <nl> + } <nl> + llvm : : Function * DumpModuleMain = DumpModule . getFunction ( " main " ) ; <nl> + DumpModuleMain - > setName ( " repl . line " ) ; <nl> <nl> - / / IRGen the current line ( s ) . <nl> - llvm : : Module LineModule ( " REPLLine " , LLVMContext ) ; <nl> - performCaptureAnalysis ( TU , CurIRGenElem ) ; <nl> - performIRGeneration ( Options , & LineModule , TU , / * sil = * / nullptr , <nl> - CurIRGenElem ) ; <nl> - CurIRGenElem = CurTUElem ; <nl> + if ( IRGenImportedModules ( TU , Module , ImportedModules , InitFns , Options ) ) <nl> + return ; <nl> <nl> - if ( Context . hadError ( ) ) <nl> - return ; <nl> + for ( auto InitFn : InitFns ) <nl> + EE - > runFunctionAsMain ( InitFn , std : : vector < std : : string > ( ) , 0 ) ; <nl> + InitFns . clear ( ) ; <nl> <nl> - std : : string ErrorMessage ; <nl> - if ( llvm : : Linker : : LinkModules ( & Module , & LineModule , <nl> - llvm : : Linker : : PreserveSource , <nl> - & ErrorMessage ) ) { <nl> - llvm : : errs ( ) < < " Error linking swift modules \ n " ; <nl> - llvm : : errs ( ) < < ErrorMessage < < " \ n " ; <nl> - return ; <nl> + / / FIXME : The way we do this is really ugly . . . we should be able to <nl> + / / improve this . <nl> + EE - > runStaticConstructorsDestructors ( & Module , false ) ; <nl> + llvm : : Function * EntryFn = Module . getFunction ( " main " ) ; <nl> + EE - > runFunctionAsMain ( EntryFn , std : : vector < std : : string > ( ) , 0 ) ; <nl> + EE - > freeMachineCodeForFunction ( EntryFn ) ; <nl> + EntryFn - > eraseFromParent ( ) ; <nl> + <nl> + break ; <nl> } <nl> - if ( llvm : : Linker : : LinkModules ( & DumpModule , & LineModule , <nl> - llvm : : Linker : : DestroySource , <nl> - & ErrorMessage ) ) { <nl> - llvm : : errs ( ) < < " Error linking swift modules \ n " ; <nl> - llvm : : errs ( ) < < ErrorMessage < < " \ n " ; <nl> - return ; <nl> } <nl> - llvm : : Function * DumpModuleMain = DumpModule . getFunction ( " main " ) ; <nl> - DumpModuleMain - > setName ( " repl . line " ) ; <nl> - <nl> - if ( IRGenImportedModules ( TU , Module , ImportedModules , InitFns , Options ) ) <nl> - return ; <nl> - <nl> - for ( auto InitFn : InitFns ) <nl> - EE - > runFunctionAsMain ( InitFn , std : : vector < std : : string > ( ) , 0 ) ; <nl> - InitFns . clear ( ) ; <nl> - <nl> - / / FIXME : The way we do this is really ugly . . . we should be able to <nl> - / / improve this . <nl> - EE - > runStaticConstructorsDestructors ( & Module , false ) ; <nl> - llvm : : Function * EntryFn = Module . getFunction ( " main " ) ; <nl> - EE - > runFunctionAsMain ( EntryFn , std : : vector < std : : string > ( ) , 0 ) ; <nl> - EE - > freeMachineCodeForFunction ( EntryFn ) ; <nl> - EntryFn - > eraseFromParent ( ) ; <nl> } <nl> } <nl>
REPL : Separate the interface and response code .
apple/swift
d1c34dcfd627fef6084be50ff0ca40ff14b7ba93
2013-02-21T01:49:39Z
mmm a / vendor / brightray <nl> ppp b / vendor / brightray <nl> @ @ - 1 + 1 @ @ <nl> - Subproject commit baccc077948f504c6a6db58e855fd33938b2b625 <nl> + Subproject commit 28d713bb2a82ba690a21d62522ecd7bad09caba8 <nl>
Upgrade brightray for Windows 7 notifications
electron/electron
4f26424ace569e25dd35f21f9ef09895b84df0f4
2017-04-12T20:01:52Z
mmm a / xbmc / cores / VideoRenderers / LinuxRendererGLES . cpp <nl> ppp b / xbmc / cores / VideoRenderers / LinuxRendererGLES . cpp <nl> bool CLinuxRendererGLES : : RenderCapture ( CRenderCapture * capture ) <nl> if ( ! m_bValidated ) <nl> return false ; <nl> <nl> - / / get our screen rect <nl> - const CRect rv = g_graphicsContext . GetViewWindow ( ) ; <nl> - <nl> / / save current video rect <nl> CRect saveSize = m_destRect ; <nl> <nl> bool CLinuxRendererGLES : : RenderCapture ( CRenderCapture * capture ) <nl> <nl> Render ( RENDER_FLAG_NOOSD , m_iYV12RenderBuffer ) ; <nl> / / read pixels <nl> - glReadPixels ( 0 , rv . y2 - capture - > GetHeight ( ) , capture - > GetWidth ( ) , capture - > GetHeight ( ) , <nl> + glReadPixels ( 0 , g_graphicsContext . GetHeight ( ) - capture - > GetHeight ( ) , capture - > GetWidth ( ) , capture - > GetHeight ( ) , <nl> GL_RGBA , GL_UNSIGNED_BYTE , capture - > GetRenderBuffer ( ) ) ; <nl> <nl> / / OpenGLES returns in RGBA order but CRenderCapture needs BGRA order <nl>
apply a9f0ae0ecad9350b16940c98357b91822ac8f956 to CLinuxRendererGLES
xbmc/xbmc
45129a370197298cee3b69523479b9f0bef9755c
2011-11-18T20:58:00Z
mmm a / dlib / algs . h <nl> ppp b / dlib / algs . h <nl> namespace dlib <nl> template < > struct is_float_type < double > { const static bool value = true ; } ; <nl> template < > struct is_float_type < long double > { const static bool value = true ; } ; <nl> <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - <nl> - template < <nl> - typename T <nl> - > <nl> - bool is_finite ( <nl> - const T & value <nl> - ) <nl> - / * ! <nl> - ensures <nl> - - returns true if value is a finite value ( e . g . not infinity or NaN ) and false <nl> - otherwise . <nl> - ! * / <nl> - { <nl> - if ( is_float_type < T > : : value ) <nl> - return - std : : numeric_limits < T > : : infinity ( ) < value & & value < std : : numeric_limits < T > : : infinity ( ) ; <nl> - else <nl> - return true ; <nl> - } <nl> - <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> <nl> / * ! A is_convertible <nl> namespace dlib <nl> <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> <nl> + template < <nl> + typename T <nl> + > <nl> + typename enable_if < is_built_in_scalar_type < T > , bool > : : type is_finite ( <nl> + const T & value <nl> + ) <nl> + / * ! <nl> + requires <nl> + - value must be some kind of scalar type such as int or double <nl> + ensures <nl> + - returns true if value is a finite value ( e . g . not infinity or NaN ) and false <nl> + otherwise . <nl> + ! * / <nl> + { <nl> + if ( is_float_type < T > : : value ) <nl> + return - std : : numeric_limits < T > : : infinity ( ) < value & & value < std : : numeric_limits < T > : : infinity ( ) ; <nl> + else <nl> + return true ; <nl> + } <nl> + <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> + <nl> / * ! A promote <nl> <nl> This is a template that takes one of the built in scalar types and gives you another <nl> mmm a / dlib / matrix / matrix_utilities . h <nl> ppp b / dlib / matrix / matrix_utilities . h <nl> namespace dlib <nl> const matrix_exp < EXP > & m <nl> ) { return is_row_vector ( m ) | | is_col_vector ( m ) ; } <nl> <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> + <nl> + template < typename EXP > <nl> + inline bool is_finite ( <nl> + const matrix_exp < EXP > & m <nl> + ) <nl> + { <nl> + for ( long r = 0 ; r < m . nr ( ) ; + + r ) <nl> + { <nl> + for ( long c = 0 ; c < m . nc ( ) ; + + c ) <nl> + { <nl> + if ( ! is_finite ( m ( r , c ) ) ) <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> <nl> namespace impl <nl> mmm a / dlib / matrix / matrix_utilities_abstract . h <nl> ppp b / dlib / matrix / matrix_utilities_abstract . h <nl> namespace dlib <nl> - returns false <nl> ! * / <nl> <nl> + / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> + <nl> + bool is_finite ( <nl> + const matrix_exp & m <nl> + ) ; <nl> + / * ! <nl> + ensures <nl> + - returns true if all the values in m are finite values and also not any kind <nl> + of NaN value . <nl> + ! * / <nl> + <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> / / Thresholding relational operators <nl> mmm a / dlib / test / matrix . cpp <nl> ppp b / dlib / test / matrix . cpp <nl> namespace <nl> m1 = 1 ; <nl> m2 = 1 ; <nl> m1 = m1 * subm ( m2 , 0 , 0 , 3 , 3 ) ; <nl> + DLIB_TEST ( is_finite ( m1 ) ) ; <nl> } <nl> { <nl> matrix < double , 3 , 1 > m1 ; <nl> namespace <nl> <nl> DLIB_TEST ( m ( 0 ) = = 6 ) ; <nl> DLIB_TEST ( m ( 1 ) = = 6 ) ; <nl> + DLIB_TEST ( is_finite ( m ) ) ; <nl> } <nl> + <nl> + <nl> + { <nl> + matrix < double > m ( 3 , 3 ) ; <nl> + m = 3 ; <nl> + m ( 1 , 1 ) = std : : numeric_limits < double > : : infinity ( ) ; <nl> + DLIB_TEST ( is_finite ( m ) = = false ) ; <nl> + m ( 1 , 1 ) = - std : : numeric_limits < double > : : infinity ( ) ; <nl> + DLIB_TEST ( is_finite ( m ) = = false ) ; <nl> + m ( 1 , 1 ) = 2 ; <nl> + DLIB_TEST ( is_finite ( m ) ) ; <nl> + } <nl> + <nl> } <nl> <nl> <nl>
Added is_finite ( ) for matrix objects .
davisking/dlib
d9a93fdce1dc01a8b10cc68adffe49301bc31662
2013-08-08T14:04:05Z
mmm a / doc / developer - guide / multi_node . md <nl> ppp b / doc / developer - guide / multi_node . md <nl> <nl> <nl> MXNet uses a two - level * parameter server * for data synchronization . <nl> <nl> - < img src = https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / multi - node / ps_arch . png width = 400 / > <nl> + < img src = https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / multi - node / ps_arch . png width = 400 / > <nl> <nl> - On the first layer , data are synchronized over multiple devices within a <nl> single worker machine . A device could be a GPU card , CPU , or other computational <nl> mmm a / doc / developer - guide / note_engine . md <nl> ppp b / doc / developer - guide / note_engine . md <nl> However , it is quite hard to code the sequence manually , as the last operation , <nl> ` ` ` D = B * C ` ` ` , needs to wait for both the above operations to complete before it starts running . <nl> We can represent the computation as the following dependency graph . <nl> <nl> - ! [ Dep Simple ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_simple . png ) <nl> + ! [ Dep Simple ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_simple . png ) <nl> <nl> In this specific case , the graph is also called data - flow graph , as it represents the dependency <nl> in terms of data and computation . <nl> learning libraries when things go parallel . <nl> # # # Data Flow Dependency <nl> The central thing that almost every dependency engine will have to solve , is the dataflow dependency problem . <nl> <nl> - ! [ Dep Simple ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_simple . png ) <nl> + ! [ Dep Simple ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_simple . png ) <nl> <nl> Data Flow dependency describes how the outcome of one computation can be used in other computations . <nl> As we have elaborated this in last section , we will only put the same figure here . Libraries that have <nl> This is simple in the serial case . Because we can simply recycle the memory afte <nl> go out of scope . However , things becomes a bit harder in parallel case . Consider the following <nl> example <nl> <nl> - ! [ Dep Del ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_del . png ) <nl> + ! [ Dep Del ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_del . png ) <nl> <nl> In the above example , because both computation needs to use values from A . We cannot perform <nl> the memory recycling before these computation completes . So a correct engine <nl> is executed after both ` ` ` B = A + 1 ` ` ` and ` ` ` C = A + 2 ` ` ` completes . <nl> Random number generators are commonly used in machine learning . However , they also bring <nl> interesting challenges for dependency engine . Consider the following example <nl> <nl> - ! [ Dep Rand ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_rand . png ) <nl> + ! [ Dep Rand ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_rand . png ) <nl> <nl> Here we are generating random numbers in a sequence . While it seems that the two random number <nl> generations can be parallelized . This is usually not the case . Because usually a pseudorandom <nl> a simple SGD update , and copies the updated weight back to each GPU . <nl> This is a common data parallel program written in a serial manner . <nl> The following dependency graph shows how it can be parallelized : <nl> <nl> - ! [ Dep Net ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_net . png ) <nl> + ! [ Dep Net ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_net . png ) <nl> <nl> Few important notes : <nl> - The copy of gradient to CPU , can happen as soon as we get gradient of that layer . <nl> Because we cannot assume the object we are scheduling on . What we can do instead <nl> ` ` ` virtual tag ` ` ` that is associated with each object to represent what we need to schedule . <nl> So at the beginning , user can allocate the variable tag , and attach it to each of object that we want to schedule . <nl> <nl> - ! [ Dep Net ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / tag_var . png ) <nl> + ! [ Dep Net ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / tag_var . png ) <nl> <nl> After having the variable tags , user call ` ` ` push ` ` ` to tell the engine about the function we want to execute . <nl> In addition , user need to specify the dependencies of the operation by ` ` ` read_vars ` ` ` and ` ` ` write_vars ` ` ` . <nl> - ` ` ` read_vars ` ` ` are variable tags of objects which the operation will " read from " , without changing its internal state . <nl> - ` ` ` mutate_vars ` ` ` are variable tags of objects which the operation will mutate their internal states . <nl> <nl> - ! [ Push Op ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / push_var . png ) <nl> + ! [ Push Op ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / push_var . png ) <nl> <nl> The above figure shows how we can push operation ` ` ` B = A + 1 ` ` ` to dependency engine . Here ` ` ` B . data ` ` ` , <nl> ` ` ` A . data ` ` ` are the real allocated space . We should note that engine is * * * only aware of variable tags * * * . <nl> The first line reads variable ` A ` and mutates variable ` B ` . The second line read <nl> <nl> The engine is going to maintain a queue for each variable , as the following animation shows for each of the four lines . Green blocks represents a read action , while a red one represents a mutation . <nl> <nl> - ! [ Dependency Queue ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_queue . gif ) <nl> + ! [ Dependency Queue ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_queue . gif ) <nl> <nl> Upon building this queue , the engine sees that the first two green blocks at the front of A ' s queue , could actually be run in parallel , because they are both read actions and won ' t conflict with each other . The following graph illustrates this point . <nl> <nl> - ! [ Dependency Parallelism ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / dep_parallel . png ) <nl> + ! [ Dependency Parallelism ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / dep_parallel . png ) <nl> <nl> The cool thing about all this scheduling is , it is not confined to numerical calculations . Since everything scheduled is only a tag , the engine could schedule everything ! <nl> <nl> The following figure gives a complete push sequence of the programs we mentioned in previous sections . <nl> - ! [ Push Seq ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / push_seq . png ) <nl> + ! [ Push Seq ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / push_seq . png ) <nl> <nl> # # # Port Existing Codes to the Dependency Engine <nl> Because the generic interface do not take control of things like memory allocation and what operation to execute . <nl> The general idea is as follows <nl> The following figure gives a visual example of the scheduling algorithm , which might give you a better sense <nl> of what is going on in the engine . <nl> <nl> - ! [ Dep Tracking ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / engine_queue_step . png ) <nl> + ! [ Dep Tracking ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / engine_queue_step . png ) <nl> <nl> The following figure gives another example that involves random number generations . <nl> <nl> - ! [ Dep Rand ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / engine / engine_queue_rand . png ) <nl> + ! [ Dep Rand ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / engine / engine_queue_rand . png ) <nl> <nl> As we can see , the algorithm is mainly about update pending queues of operations and doing the right <nl> state transition when operation completed . More care should be taken to make sure the state transition <nl> mmm a / doc / program_model . md <nl> ppp b / doc / program_model . md <nl> The difference in symbolic programs is when ` ` ` C = B * A ` ` ` is executed , there i <nl> Instead , these operations generates a computation graph ( symbolic graph ) that represents the computation it described . <nl> The following picture gives a computation graph to compute ` ` ` D ` ` ` . <nl> <nl> - ! [ Comp Graph ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / prog_model / comp_graph . png ) <nl> + ! [ Comp Graph ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / prog_model / comp_graph . png ) <nl> <nl> Most symbolic style programs will contain , either explicitly or implicitly , a ` ` ` compile ` ` ` step . <nl> This converts the computation graph into a function that can be called . <nl> d = c + 1 <nl> . . . <nl> ` ` ` <nl> <nl> - ! [ Comp Graph ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / prog_model / comp_graph . png ) <nl> + ! [ Comp Graph ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / prog_model / comp_graph . png ) <nl> <nl> Assume each cell in the array cost 8 bytes . How many memory do we need to cost if we are going to execute the above program in python console ? <nl> Let us do some math , we need memory for 4 arrays of size 10 , that means we will need ` ` ` 4 * 10 * 8 = 320 ` ` ` bytes . On the other hand , <nl> Another optimization that symbolic programs can do is operation folding . In the <nl> Which is represented in the following graph . This means one GPU kernel will be executed ( instead of two ) if the computation runs on GPU . <nl> This is actually what we will do to hand crafted operations in optimized libraries such as cxxnet , caffe . Doing so will improve the computation efficiency . <nl> <nl> - ! [ Comp Graph Folded ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / prog_model / comp_graph_fold . png ) <nl> + ! [ Comp Graph Folded ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / prog_model / comp_graph_fold . png ) <nl> <nl> We cannot do that in imperative programs . Because the intermediate value can be reference <nl> some point in the future . The reason that such optimization is possible in symbolic programs , is that we get the entire computation graph , and a clear <nl> grad_a , grad_b = f ( A = np . ones ( 10 ) , B = np . ones ( 10 ) * 2 ) <nl> The grad function of D generate a backward computation graph , and return a gradient node ` ` ` gA , gB ` ` ` . <nl> They corresponds to the red nodes in the following figure . <nl> <nl> - ! [ Comp Graph Folded ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / prog_model / comp_graph_backward . png ) <nl> + ! [ Comp Graph Folded ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / prog_model / comp_graph_backward . png ) <nl> <nl> What the imperative program did was actually the same as the symbolic way . It implicitly saves a backward <nl> computation graph in the grad closure . When we invoked the ` ` ` d . grad ` ` ` , we start from ` ` ` d ( D ) ` ` ` , <nl> mmm a / doc / python / symbol_in_pictures . md <nl> ppp b / doc / python / symbol_in_pictures . md <nl> Compose Symbols <nl> The symbols are description of computation we want to do . The symbolic construction API generates the computation <nl> graph that describes the need of computation . The following picture is how we compose symbols to describe basic computations . <nl> <nl> - ! [ Symbol Compose ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / compose_basic . png ) <nl> + ! [ Symbol Compose ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / compose_basic . png ) <nl> <nl> - The ` ` ` mxnet . symbol . Variable ` ` ` function creates argument nodes that represents inputs to the computation . <nl> - The Symbol is overloaded with basic element - wise arithmetic operations . <nl> Configure Neural Nets <nl> Besides fine - grained operations , mxnet also provide a way to perform big operations that is analogy to layers in neural nets . <nl> We can use these operators to describe a neural net configuration . <nl> <nl> - ! [ Net Compose ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / compose_net . png ) <nl> + ! [ Net Compose ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / compose_net . png ) <nl> <nl> <nl> Example of Multi - Input Net <nl> mmmmmmmmmmmmmmmmmmmmmmmm - - <nl> The following is an example of configuring multiple input neural nets . <nl> <nl> - ! [ Multi Input ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / compose_multi_in . png ) <nl> + ! [ Multi Input ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / compose_multi_in . png ) <nl> <nl> <nl> Bind and Execute Symbol <nl> Bind and Execute Symbol <nl> When we need to execute a symbol graph . We call bind function to bind ` ` ` NDArrays ` ` ` to the argument nodes <nl> to get a ` ` ` Executor ` ` ` . <nl> <nl> - ! [ Bind ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / bind_basic . png ) <nl> + ! [ Bind ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / bind_basic . png ) <nl> <nl> You can call ` ` ` Executor . Forward ` ` ` to get the output results , given the binded NDArrays as input . <nl> <nl> - ! [ Forward ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / executor_forward . png ) <nl> + ! [ Forward ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / executor_forward . png ) <nl> <nl> <nl> Bind Multiple Outputs <nl> Bind Multiple Outputs <nl> You can use ` ` ` mx . symbol . Group ` ` ` to group symbols together then bind them to <nl> get outputs of both . <nl> <nl> - ! [ MultiOut ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / executor_multi_out . png ) <nl> + ! [ MultiOut ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / executor_multi_out . png ) <nl> <nl> But always remember , only bind what you need , so system can do more optimizations for you . <nl> <nl> Calculate Gradient <nl> You can specify gradient holder NDArrays in bind , then call ` ` ` Executor . backward ` ` ` after ` ` ` Executor . forward ` ` ` <nl> will give you the corresponding gradients . <nl> <nl> - ! [ Gradient ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / executor_backward . png ) <nl> + ! [ Gradient ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / executor_backward . png ) <nl> <nl> <nl> Simple Bind Interface for Neural Nets <nl> graph like neural nets . ` ` ` Symbol . simple_bind ` ` ` provides a way to simplify <nl> the procedure . You only need to specify input data shapes , and the function will allocate the arguments , and bind <nl> the Executor for you . <nl> <nl> - ! [ SimpleBind ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / executor_simple_bind . png ) <nl> + ! [ SimpleBind ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / executor_simple_bind . png ) <nl> <nl> Auxiliary States <nl> mmmmmmmmmmmmmmm - <nl> Auxiliary states are just like arguments , except that you cannot take gradient of them . These are states that may <nl> not be part of computation , but can be helpful to track . You can pass the auxiliary state in the same way as arguments . <nl> <nl> - ! [ SimpleBind ] ( https : / / raw . githubusercontent . com / dmlc / dmlc . github . io / master / img / mxnet / symbol / executor_aux_state . png ) <nl> + ! [ SimpleBind ] ( https : / / raw . githubusercontent . com / dmlc / web - data / master / mxnet / symbol / executor_aux_state . png ) <nl> <nl> More Information <nl> mmmmmmmmmmmmmmm - <nl>
Move the link to the figure to web - data
apache/incubator-mxnet
00bcab3de0d662cc54b8a6290a9ff009256cd04f
2015-10-22T22:31:29Z
mmm a / src / api / tesseractmain . cpp <nl> ppp b / src / api / tesseractmain . cpp <nl> <nl> # include < omp . h > <nl> # endif <nl> <nl> + # if defined ( HAVE_LIBARCHIVE ) <nl> + # include < archive . h > <nl> + # endif <nl> + <nl> # if defined ( _WIN32 ) <nl> # include < fcntl . h > <nl> # include < io . h > <nl> static void PrintVersionInfo ( ) { <nl> # ifdef _OPENMP <nl> printf ( " Found OpenMP % d \ n " , _OPENMP ) ; <nl> # endif <nl> + # if defined ( HAVE_LIBARCHIVE ) <nl> + printf ( " Found % s " , archive_version_details ( ) ) ; <nl> + # endif <nl> <nl> } <nl> <nl>
Report libArchive support
tesseract-ocr/tesseract
02a1ffe87a231c83e7fdb92d5dc913d26a0b7b75
2019-03-10T19:08:45Z
mmm a / AirLib / AirLib . vcxproj <nl> ppp b / AirLib / AirLib . vcxproj <nl> <nl> < ClInclude Include = " include \ common \ UpdatableObject . hpp " / > <nl> < ClInclude Include = " include \ common \ VectorMath . hpp " / > <nl> < ClInclude Include = " include \ common \ common_utils \ AsyncTasker . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ AirSimRosFlightCommLink . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ AirSimRosFlightBoard . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ board . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ commlink . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ commonstate . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ controller . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ dummyboard . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ dummycommlink . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ estimator . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ firmware . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ mixer . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ mode . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ mux . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ param . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ rc . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ sensors . hpp " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ turbotrig \ turbotrig . h " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ turbotrig \ turbovec . h " / > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ RosFlightDroneController . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ AirSimRosFlightBoard . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ AirSimRosFlightCommLink . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ board . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ commlink . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ commonstate . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ controller . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ dummyboard . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ dummycommlink . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ estimator . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ firmware . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ mixer . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ mode . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ mux . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ param . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ rc . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ sensors . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ turbotrig \ turbotrig . h " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ turbotrig \ turbovec . h " / > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ RosFlightDroneController . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ AirSimSimpleFlightBoard . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ AirSimSimpleFlightCommLink . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ firmware \ Board . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ firmware \ CommLink . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ firmware \ Firmware . hpp " / > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ SimpleFlightDroneController . hpp " / > <nl> < ClInclude Include = " include \ controllers \ VehicleCamera . hpp " / > <nl> < ClInclude Include = " include \ physics \ DebugPhysicsBody . hpp " / > <nl> < ClInclude Include = " include \ rpc \ ControlServerBase . hpp " / > <nl> <nl> < ClInclude Include = " include \ controllers \ RpyDirectController . hpp " / > <nl> < ClInclude Include = " include \ controllers \ RpyDirectControllerParams . hpp " / > <nl> < ClInclude Include = " include \ vehicles \ configs \ RosFlightQuadX . hpp " / > <nl> + < ClInclude Include = " include \ vehicles \ configs \ SimpleFlightQuadX . hpp " / > <nl> < ClInclude Include = " include \ vehicles \ MultiRotor . hpp " / > <nl> < ClInclude Include = " include \ vehicles \ MultiRotorParams . hpp " / > <nl> < ClInclude Include = " include \ vehicles \ MultiRotorParamsFactory . hpp " / > <nl> mmm a / AirLib / AirLib . vcxproj . filters <nl> ppp b / AirLib / AirLib . vcxproj . filters <nl> <nl> < ClInclude Include = " include \ common \ common_utils \ FileSystem . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ turbotrig \ turbotrig . h " > <nl> + < ClInclude Include = " include \ vehicles \ configs \ RosFlightQuadX . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ turbotrig \ turbovec . h " > <nl> + < ClInclude Include = " include \ vehicles \ MultiRotorParamsFactory . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ board . hpp " > <nl> + < ClInclude Include = " include \ common \ ClockBase . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ commlink . hpp " > <nl> + < ClInclude Include = " include \ common \ SimClock . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ commonstate . hpp " > <nl> + < ClInclude Include = " include \ common \ ClockFactory . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ controller . hpp " > <nl> + < ClInclude Include = " include \ vehicles \ configs \ Px4MultiRotor . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ dummyboard . hpp " > <nl> + < ClInclude Include = " include \ common \ common_utils \ Timer . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ dummycommlink . hpp " > <nl> + < ClInclude Include = " include \ common \ common_utils \ WorkerThread . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ estimator . hpp " > <nl> + < ClInclude Include = " include \ controllers \ VehicleCamera . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ firmware . hpp " > <nl> + < ClInclude Include = " include \ common \ DebugClock . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ mixer . hpp " > <nl> + < ClInclude Include = " include \ physics \ DebugPhysicsBody . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ mode . hpp " > <nl> + < ClInclude Include = " include \ vehicles \ configs \ SimpleFlightQuadX . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ mux . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ turbotrig \ turbotrig . h " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ param . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ turbotrig \ turbovec . h " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ rc . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ board . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ firmware \ sensors . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ commlink . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ RosFlightDroneController . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ commonstate . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ AirSimRosFlightBoard . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ controller . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ rosflight \ AirSimRosFlightCommLink . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ dummyboard . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ vehicles \ configs \ RosFlightQuadX . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ dummycommlink . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ vehicles \ MultiRotorParamsFactory . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ estimator . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ common \ ClockBase . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ firmware . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ common \ SimClock . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ mixer . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ common \ ClockFactory . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ mode . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ vehicles \ configs \ Px4MultiRotor . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ mux . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ common \ common_utils \ Timer . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ param . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ common \ common_utils \ WorkerThread . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ rc . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ controllers \ VehicleCamera . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ firmware \ sensors . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ common \ DebugClock . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ AirSimRosFlightBoard . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> - < ClInclude Include = " include \ physics \ DebugPhysicsBody . hpp " > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ AirSimRosFlightCommLink . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ ros_flight \ RosFlightDroneController . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ firmware \ Board . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ firmware \ Firmware . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ AirSimSimpleFlightBoard . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ SimpleFlightDroneController . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ firmware \ CommLink . hpp " > <nl> + < Filter > Header Files < / Filter > <nl> + < / ClInclude > <nl> + < ClInclude Include = " include \ controllers \ simple_flight \ AirSimSimpleFlightCommLink . hpp " > <nl> < Filter > Header Files < / Filter > <nl> < / ClInclude > <nl> < / ItemGroup > <nl> mmm a / AirLib / include / common / ClockBase . hpp <nl> ppp b / AirLib / include / common / ClockBase . hpp <nl> class ClockBase { <nl> public : <nl> / / returns value indicating nanoseconds elapsed since some reference timepoint in history <nl> / / typically nanoseconds from Unix epoch <nl> - virtual TTimePoint nowNanos ( ) = 0 ; <nl> + virtual TTimePoint nowNanos ( ) const = 0 ; <nl> / / converts time interval for wall clock to current clock <nl> / / For example , if implementation is scaled clock simulating 5X spped then below <nl> / / will retun dt * 5 . This functions are required to translate time to operating system <nl> / / which only has concept of wall clock . For example , to make thread sleep for specific duration . <nl> - virtual TTimeDelta fromWallDelta ( TTimeDelta dt ) = 0 ; <nl> - virtual TTimeDelta toWallDelta ( TTimeDelta dt ) = 0 ; <nl> + virtual TTimeDelta fromWallDelta ( TTimeDelta dt ) const = 0 ; <nl> + virtual TTimeDelta toWallDelta ( TTimeDelta dt ) const = 0 ; <nl> <nl> <nl> - TTimeDelta elapsedSince ( TTimePoint since ) <nl> + TTimeDelta elapsedSince ( TTimePoint since ) const <nl> { <nl> return elapsedBetween ( nowNanos ( ) , since ) ; <nl> } <nl> class ClockBase { <nl> { <nl> return ( second - first ) / 1 . 0E9 ; <nl> } <nl> - TTimeDelta updateSince ( TTimePoint & since ) <nl> + TTimeDelta updateSince ( TTimePoint & since ) const <nl> { <nl> TTimePoint cur = nowNanos ( ) ; <nl> double elapsed = elapsedBetween ( cur , since ) ; <nl> mmm a / AirLib / include / common / SimClock . hpp <nl> ppp b / AirLib / include / common / SimClock . hpp <nl> class SimClock : public ClockBase { <nl> offset_ = latency * ( scale_ - 1 ) ; <nl> } <nl> <nl> - virtual TTimePoint nowNanos ( ) override <nl> + virtual TTimePoint nowNanos ( ) const override <nl> { <nl> if ( offset_ = = 0 & & scale_ = = 1 ) / / optimized normal route <nl> return Utils : : getTimeSinceEpochNanos ( ) ; <nl> class SimClock : public ClockBase { <nl> } <nl> } <nl> <nl> - virtual TTimeDelta fromWallDelta ( TTimeDelta dt ) override <nl> + virtual TTimeDelta fromWallDelta ( TTimeDelta dt ) const override <nl> { <nl> return dt * scale_ ; <nl> } <nl> - virtual TTimeDelta toWallDelta ( TTimeDelta dt ) override <nl> + virtual TTimeDelta toWallDelta ( TTimeDelta dt ) const override <nl> { <nl> return dt / scale_ ; <nl> } <nl> mmm a / AirLib / include / controllers / ControllerBase . hpp <nl> ppp b / AirLib / include / controllers / ControllerBase . hpp <nl> namespace msr { namespace airlib { <nl> class ControllerBase : public UpdatableObject { <nl> public : <nl> / / reset any state in the controller <nl> - virtual void reset ( ) override = 0 ; <nl> - virtual void update ( ) override = 0 ; <nl> + virtual void reset ( ) override = 0 ; <nl> + virtual void update ( ) override = 0 ; <nl> <nl> / / return 0 to 1 ( corresponds to zero to full thrust ) <nl> - virtual real_T getVertexControlSignal ( unsigned int rotor_index ) = 0 ; <nl> + virtual real_T getVertexControlSignal ( unsigned int rotor_index ) = 0 ; <nl> virtual size_t getVertexCount ( ) = 0 ; <nl> <nl> virtual void getStatusMessages ( std : : vector < std : : string > & messages ) <nl> similarity index 94 % <nl> rename from AirLib / include / controllers / rosflight / AirSimRosFlightBoard . hpp <nl> rename to AirLib / include / controllers / ros_flight / AirSimRosFlightBoard . hpp <nl> mmm a / AirLib / include / controllers / rosflight / AirSimRosFlightBoard . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / AirSimRosFlightBoard . hpp <nl> <nl> - / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> - / / Licensed under the MIT License . <nl> - <nl> - # ifndef msr_airlib_AirSimRosFlightBoard_hpp <nl> - # define msr_airlib_AirSimRosFlightBoard_hpp <nl> - <nl> - # include < exception > <nl> - # include " firmware / board . hpp " <nl> - # include " common / Common . hpp " <nl> - # include " vehicles / MultiRotorParams . hpp " <nl> - # include " sensors / SensorCollection . hpp " <nl> - # include " common / ClockFactory . hpp " <nl> - <nl> - / / sensors <nl> - # include " sensors / barometer / BarometerSimple . hpp " <nl> - # include " sensors / imu / ImuSimple . hpp " <nl> - # include " sensors / gps / GpsSimple . hpp " <nl> - # include " sensors / magnetometer / MagnetometerSimple . hpp " <nl> - <nl> - namespace msr { namespace airlib { <nl> - <nl> - class AirSimRosFlightBoard : public rosflight : : Board { <nl> - public : / / type <nl> - typedef MultiRotorParams : : EnabledSensors EnabledSensors ; <nl> - <nl> - public : <nl> - AirSimRosFlightBoard ( const EnabledSensors * enabled_sensors , const SensorCollection * sensors ) <nl> - : enabled_sensors_ ( enabled_sensors ) , sensors_ ( sensors ) <nl> - { <nl> - } <nl> - <nl> - / / interface for simulator mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - real_T getMotorControlSignal ( uint index ) <nl> - { <nl> - / / convert PWM to scalled 0 to 1 control signal <nl> - return ( motors_pwm_ [ index ] - 1000 ) / 1000 . 0f ; <nl> - } <nl> - <nl> - void setInputChannel ( uint channel , uint16_t val ) <nl> - { <nl> - input_channels_ [ channel ] = val ; <nl> - } <nl> - <nl> - void notifySensorUpdated ( rosflight : : Board : : SensorType type ) <nl> - { <nl> - if ( type = = rosflight : : Board : : SensorType : : Imu ) <nl> - imu_updated_callback_ ( ) ; <nl> - } <nl> - <nl> - public : <nl> - / / Board interface implementation mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> - virtual void init ( ) override <nl> - { <nl> - imu_ = static_cast < const ImuBase * > ( sensors_ - > getByType ( SensorCollection : : SensorType : : Imu ) ) ; <nl> - baro_ = static_cast < const BarometerBase * > ( sensors_ - > getByType ( SensorCollection : : SensorType : : Barometer ) ) ; <nl> - mag_ = static_cast < const MagnetometerBase * > ( sensors_ - > getByType ( SensorCollection : : SensorType : : Magnetometer ) ) ; <nl> - } <nl> - <nl> - virtual uint64_t micros ( ) override <nl> - { <nl> - return static_cast < uint64_t > ( clock ( ) - > nowNanos ( ) / 1 . 0E3 ) ; <nl> - } <nl> - <nl> - virtual uint32_t millis ( ) override <nl> - { <nl> - return static_cast < uint32_t > ( clock ( ) - > nowNanos ( ) / 1 . 0E6 ) ; <nl> - } <nl> - <nl> - virtual void init_sensors ( uint16_t & acc1G , float & gyro_scale , int boardVersion , const std : : function < void ( void ) > & imu_updated_callback ) override <nl> - { <nl> - imu_updated_callback_ = imu_updated_callback ; <nl> - init_imu ( acc1G , gyro_scale , boardVersion ) ; <nl> - } <nl> - <nl> - virtual bool is_sensor_present ( SensorType type ) override <nl> - { <nl> - switch ( type ) { <nl> - case SensorType : : Baro : return enabled_sensors_ - > barometer ; <nl> - case SensorType : : Gps : return enabled_sensors_ - > gps ; <nl> - case SensorType : : Imu : return enabled_sensors_ - > imu ; <nl> - case SensorType : : Mag : return enabled_sensors_ - > magnetometer ; <nl> - default : <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - virtual void pwmInit ( bool useCPPM , bool usePwmFilter , bool fastPWM , uint32_t motorPwmRate , uint16_t idlePulseUsec ) override <nl> - { <nl> - unused ( useCPPM ) ; <nl> - unused ( usePwmFilter ) ; <nl> - unused ( fastPWM ) ; <nl> - unused ( motorPwmRate ) ; <nl> - unused ( idlePulseUsec ) ; <nl> - for ( uint i = 0 ; i < OutputMotorCount ; + + i ) <nl> - motors_pwm_ [ i ] = 1000 ; <nl> - for ( uint i = 0 ; i < InputChannelCount ; + + i ) <nl> - input_channels_ [ i ] = 1000 ; <nl> - } <nl> - <nl> - virtual uint16_t pwmRead ( int16_t channel ) override <nl> - { <nl> - / / convert range - 1 to 1 input signal to 1000 to 2000 PWM <nl> - return static_cast < uint16_t > ( input_channels_ [ channel ] ) ; <nl> - } <nl> - <nl> - virtual void pwmWriteMotor ( uint8_t index , uint16_t value ) override <nl> - { <nl> - if ( index < OutputMotorCount ) <nl> - motors_pwm_ [ index ] = value ; <nl> - else <nl> - throw std : : runtime_error ( " cannot write motor output for index > motor count " ) ; <nl> - } <nl> - <nl> - virtual void set_led ( uint8_t index , bool is_on ) override <nl> - { <nl> - / / ignored for now <nl> - unused ( index ) ; <nl> - unused ( is_on ) ; <nl> - } <nl> - <nl> - virtual void toggle_led ( uint8_t index ) override <nl> - { <nl> - / / ignored for now <nl> - unused ( index ) ; <nl> - } <nl> - <nl> - virtual void init_params ( ) override <nl> - { <nl> - / / ignored for now <nl> - } <nl> - <nl> - virtual bool read_params ( ) override <nl> - { <nl> - return false ; <nl> - } <nl> - <nl> - virtual bool write_params ( bool blink_led ) override <nl> - { <nl> - unused ( blink_led ) ; <nl> - return false ; <nl> - } <nl> - <nl> - virtual void init_imu ( uint16_t & acc1G , float & gyroScale , int boardVersion ) override <nl> - { <nl> - unused ( boardVersion ) ; <nl> - / / same as mpu6050_init <nl> - acc1G = kAccelAdcBits ; <nl> - gyroScale = kGyroScale ; <nl> - } <nl> - <nl> - virtual void read_accel ( int16_t accel_adc [ 3 ] ) override <nl> - { <nl> - const auto & output = imu_ - > getOutput ( ) ; <nl> - / / convert from SI units in NED to ADC output <nl> - accel_adc [ 0 ] = accel_to_adc ( output . linear_acceleration . x ( ) ) ; <nl> - accel_adc [ 1 ] = - accel_to_adc ( output . linear_acceleration . y ( ) ) ; <nl> - accel_adc [ 2 ] = - accel_to_adc ( output . linear_acceleration . z ( ) ) ; <nl> - } <nl> - <nl> - virtual void read_gyro ( int16_t gyro_adc [ 3 ] ) override <nl> - { <nl> - const auto & output = imu_ - > getOutput ( ) ; <nl> - / / convert from SI units in NED to ADC output <nl> - gyro_adc [ 0 ] = angular_vel_to_adc ( output . angular_velocity . x ( ) ) ; <nl> - gyro_adc [ 1 ] = - angular_vel_to_adc ( output . angular_velocity . y ( ) ) ; <nl> - gyro_adc [ 2 ] = - angular_vel_to_adc ( output . angular_velocity . z ( ) ) ; <nl> - } <nl> - <nl> - virtual void read_temperature ( int16_t & temp ) override <nl> - { <nl> - / / TODO : add separate temperature sensor in sim ? <nl> - temp = temperature_to_adc ( 25 . 0f ) ; <nl> - } <nl> - <nl> - virtual void read_baro ( float & altitude , float & pressure , float & temperature ) override <nl> - { <nl> - const auto & output = baro_ - > getOutput ( ) ; <nl> - altitude = output . altitude ; <nl> - pressure = output . pressure ; <nl> - / / TODO : barometer should output temperature as well ? <nl> - temperature = 25 . 0f ; <nl> - } <nl> - <nl> - virtual void read_diff_pressure ( float & differential_pressure , float & temp , float & velocity ) override <nl> - { <nl> - unused ( differential_pressure ) ; <nl> - unused ( temp ) ; <nl> - unused ( velocity ) ; <nl> - throw std : : runtime_error ( " Diff pressure sensor is not available " ) ; <nl> - } <nl> - <nl> - virtual float read_sonar ( ) override <nl> - { <nl> - throw std : : runtime_error ( " Sonar sensor is not available " ) ; <nl> - } <nl> - <nl> - virtual void read_mag ( int16_t mag_adc [ 3 ] ) override <nl> - { <nl> - const auto & output = mag_ - > getOutput ( ) ; <nl> - / / TODO : do we expect adc in Gauss ? Do we need NED conversion ? <nl> - mag_adc [ 0 ] = static_cast < int16_t > ( output . magnetic_field_body . x ( ) ) ; <nl> - mag_adc [ 1 ] = static_cast < int16_t > ( output . magnetic_field_body . y ( ) ) ; <nl> - mag_adc [ 2 ] = static_cast < int16_t > ( output . magnetic_field_body . z ( ) ) ; <nl> - } <nl> - <nl> - virtual void delay_micros ( uint32_t us ) override <nl> - { <nl> - sleep ( us * 1E3f ) ; <nl> - } <nl> - <nl> - virtual void delay_millis ( uint32_t ms ) override <nl> - { <nl> - sleep ( static_cast < float > ( ms ) ) ; <nl> - } <nl> - <nl> - virtual void system_reset ( bool toBootloader ) override <nl> - { <nl> - unused ( toBootloader ) ; <nl> - / / no internal state to reset <nl> - } <nl> - <nl> - private : <nl> - uint16_t accel_to_adc ( float accel ) <nl> - { <nl> - / / for MPU6050 <nl> - return static_cast < uint16_t > ( accel * kAccelAdcBits / ( kAccelG * kAccelScale ) ) ; <nl> - } <nl> - uint16_t angular_vel_to_adc ( float angular_vel ) <nl> - { <nl> - / / for MPU6050 <nl> - return static_cast < uint16_t > ( angular_vel / kGyroScale ) ; <nl> - } <nl> - int16_t temperature_to_adc ( float temperature ) <nl> - { <nl> - / / for MPU6050 <nl> - return static_cast < int16_t > ( ( temperature - 36 . 53f ) * 340 . 0f ) ; <nl> - } <nl> - void sleep ( double msec ) <nl> - { <nl> - clock ( ) - > sleep_for ( msec * 1000 . 0 ) ; <nl> - } <nl> - <nl> - <nl> - ClockBase * clock ( ) <nl> - { <nl> - return ClockFactory : : get ( ) ; <nl> - } <nl> - <nl> - private : / / types and consts <nl> - const MultiRotorParams : : EnabledSensors * enabled_sensors_ ; <nl> - const SensorCollection * sensors_ ; <nl> - const ImuBase * imu_ ; <nl> - const BarometerBase * baro_ ; <nl> - const MagnetometerBase * mag_ ; <nl> - <nl> - const uint16_t kAccelAdcBits = 512 * 8 ; / / for mpu6050 as per breezystm32 / drv_mpu6050 . c <nl> - const float kAccelScale = 1 . 0 ; / / as set in PARAM_ACCEL_SCALE in ROSFlight <nl> - const float kAccelG = 9 . 80665f ; / / as set in ROSFlight sensors . c init_sensors ( ) function <nl> - <nl> - / / 16 . 4 dps / lsb scalefactor for all Invensense devices <nl> - const float kGyroScale = ( 1 . 0f / 16 . 4f ) * ( M_PIf / 180 . 0f ) ; <nl> - <nl> - static constexpr uint OutputMotorCount = 16 ; <nl> - static constexpr uint InputChannelCount = 16 ; <nl> - <nl> - private : <nl> - / / motor outputs <nl> - uint16_t motors_pwm_ [ OutputMotorCount ] ; <nl> - uint16_t input_channels_ [ InputChannelCount ] ; <nl> - <nl> - std : : function < void ( void ) > imu_updated_callback_ ; <nl> - } ; <nl> - <nl> - } } / / namespace <nl> - # endif <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_AirSimRosFlightBoard_hpp <nl> + # define msr_airlib_AirSimRosFlightBoard_hpp <nl> + <nl> + # include < exception > <nl> + # include " firmware / board . hpp " <nl> + # include " common / Common . hpp " <nl> + # include " vehicles / MultiRotorParams . hpp " <nl> + # include " sensors / SensorCollection . hpp " <nl> + # include " common / ClockFactory . hpp " <nl> + <nl> + / / sensors <nl> + # include " sensors / barometer / BarometerSimple . hpp " <nl> + # include " sensors / imu / ImuSimple . hpp " <nl> + # include " sensors / gps / GpsSimple . hpp " <nl> + # include " sensors / magnetometer / MagnetometerSimple . hpp " <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + class AirSimRosFlightBoard : public ros_flight : : Board { <nl> + public : / / type <nl> + typedef MultiRotorParams : : EnabledSensors EnabledSensors ; <nl> + <nl> + public : <nl> + AirSimRosFlightBoard ( const EnabledSensors * enabled_sensors , const SensorCollection * sensors ) <nl> + : enabled_sensors_ ( enabled_sensors ) , sensors_ ( sensors ) <nl> + { <nl> + } <nl> + <nl> + / / interface for simulator mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + real_T getMotorControlSignal ( uint index ) <nl> + { <nl> + / / convert PWM to scalled 0 to 1 control signal <nl> + return ( motors_pwm_ [ index ] - 1000 ) / 1000 . 0f ; <nl> + } <nl> + <nl> + void setInputChannel ( uint channel , uint16_t val ) <nl> + { <nl> + input_channels_ [ channel ] = val ; <nl> + } <nl> + <nl> + void notifySensorUpdated ( ros_flight : : Board : : SensorType type ) <nl> + { <nl> + if ( type = = ros_flight : : Board : : SensorType : : Imu ) <nl> + imu_updated_callback_ ( ) ; <nl> + } <nl> + <nl> + public : <nl> + / / Board interface implementation mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + virtual void init ( ) override <nl> + { <nl> + imu_ = static_cast < const ImuBase * > ( sensors_ - > getByType ( SensorCollection : : SensorType : : Imu ) ) ; <nl> + baro_ = static_cast < const BarometerBase * > ( sensors_ - > getByType ( SensorCollection : : SensorType : : Barometer ) ) ; <nl> + mag_ = static_cast < const MagnetometerBase * > ( sensors_ - > getByType ( SensorCollection : : SensorType : : Magnetometer ) ) ; <nl> + } <nl> + <nl> + virtual uint64_t micros ( ) override <nl> + { <nl> + return static_cast < uint64_t > ( clock ( ) - > nowNanos ( ) / 1 . 0E3 ) ; <nl> + } <nl> + <nl> + virtual uint32_t millis ( ) override <nl> + { <nl> + return static_cast < uint32_t > ( clock ( ) - > nowNanos ( ) / 1 . 0E6 ) ; <nl> + } <nl> + <nl> + virtual void init_sensors ( uint16_t & acc1G , float & gyro_scale , int boardVersion , const std : : function < void ( void ) > & imu_updated_callback ) override <nl> + { <nl> + imu_updated_callback_ = imu_updated_callback ; <nl> + init_imu ( acc1G , gyro_scale , boardVersion ) ; <nl> + } <nl> + <nl> + virtual bool is_sensor_present ( SensorType type ) override <nl> + { <nl> + switch ( type ) { <nl> + case SensorType : : Baro : return enabled_sensors_ - > barometer ; <nl> + case SensorType : : Gps : return enabled_sensors_ - > gps ; <nl> + case SensorType : : Imu : return enabled_sensors_ - > imu ; <nl> + case SensorType : : Mag : return enabled_sensors_ - > magnetometer ; <nl> + default : <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + virtual void pwmInit ( bool useCPPM , bool usePwmFilter , bool fastPWM , uint32_t motorPwmRate , uint16_t idlePulseUsec ) override <nl> + { <nl> + unused ( useCPPM ) ; <nl> + unused ( usePwmFilter ) ; <nl> + unused ( fastPWM ) ; <nl> + unused ( motorPwmRate ) ; <nl> + unused ( idlePulseUsec ) ; <nl> + for ( uint i = 0 ; i < OutputMotorCount ; + + i ) <nl> + motors_pwm_ [ i ] = 1000 ; <nl> + for ( uint i = 0 ; i < InputChannelCount ; + + i ) <nl> + input_channels_ [ i ] = 1000 ; <nl> + } <nl> + <nl> + virtual uint16_t pwmRead ( int16_t channel ) override <nl> + { <nl> + / / convert range - 1 to 1 input signal to 1000 to 2000 PWM <nl> + return static_cast < uint16_t > ( input_channels_ [ channel ] ) ; <nl> + } <nl> + <nl> + virtual void pwmWriteMotor ( uint8_t index , uint16_t value ) override <nl> + { <nl> + if ( index < OutputMotorCount ) <nl> + motors_pwm_ [ index ] = value ; <nl> + else <nl> + throw std : : runtime_error ( " cannot write motor output for index > motor count " ) ; <nl> + } <nl> + <nl> + virtual void set_led ( uint8_t index , bool is_on ) override <nl> + { <nl> + / / ignored for now <nl> + unused ( index ) ; <nl> + unused ( is_on ) ; <nl> + } <nl> + <nl> + virtual void toggle_led ( uint8_t index ) override <nl> + { <nl> + / / ignored for now <nl> + unused ( index ) ; <nl> + } <nl> + <nl> + virtual void init_params ( ) override <nl> + { <nl> + / / ignored for now <nl> + } <nl> + <nl> + virtual bool read_params ( ) override <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + virtual bool write_params ( bool blink_led ) override <nl> + { <nl> + unused ( blink_led ) ; <nl> + return false ; <nl> + } <nl> + <nl> + virtual void init_imu ( uint16_t & acc1G , float & gyroScale , int boardVersion ) override <nl> + { <nl> + unused ( boardVersion ) ; <nl> + / / same as mpu6050_init <nl> + acc1G = kAccelAdcBits ; <nl> + gyroScale = kGyroScale ; <nl> + } <nl> + <nl> + virtual void read_accel ( int16_t accel_adc [ 3 ] ) override <nl> + { <nl> + const auto & output = imu_ - > getOutput ( ) ; <nl> + / / convert from SI units in NED to ADC output <nl> + accel_adc [ 0 ] = accel_to_adc ( output . linear_acceleration . x ( ) ) ; <nl> + accel_adc [ 1 ] = - accel_to_adc ( output . linear_acceleration . y ( ) ) ; <nl> + accel_adc [ 2 ] = - accel_to_adc ( output . linear_acceleration . z ( ) ) ; <nl> + } <nl> + <nl> + virtual void read_gyro ( int16_t gyro_adc [ 3 ] ) override <nl> + { <nl> + const auto & output = imu_ - > getOutput ( ) ; <nl> + / / convert from SI units in NED to ADC output <nl> + gyro_adc [ 0 ] = angular_vel_to_adc ( output . angular_velocity . x ( ) ) ; <nl> + gyro_adc [ 1 ] = - angular_vel_to_adc ( output . angular_velocity . y ( ) ) ; <nl> + gyro_adc [ 2 ] = - angular_vel_to_adc ( output . angular_velocity . z ( ) ) ; <nl> + } <nl> + <nl> + virtual void read_temperature ( int16_t & temp ) override <nl> + { <nl> + / / TODO : add separate temperature sensor in sim ? <nl> + temp = temperature_to_adc ( 25 . 0f ) ; <nl> + } <nl> + <nl> + virtual void read_baro ( float & altitude , float & pressure , float & temperature ) override <nl> + { <nl> + const auto & output = baro_ - > getOutput ( ) ; <nl> + altitude = output . altitude ; <nl> + pressure = output . pressure ; <nl> + / / TODO : barometer should output temperature as well ? <nl> + temperature = 25 . 0f ; <nl> + } <nl> + <nl> + virtual void read_diff_pressure ( float & differential_pressure , float & temp , float & velocity ) override <nl> + { <nl> + unused ( differential_pressure ) ; <nl> + unused ( temp ) ; <nl> + unused ( velocity ) ; <nl> + throw std : : runtime_error ( " Diff pressure sensor is not available " ) ; <nl> + } <nl> + <nl> + virtual float read_sonar ( ) override <nl> + { <nl> + throw std : : runtime_error ( " Sonar sensor is not available " ) ; <nl> + } <nl> + <nl> + virtual void read_mag ( int16_t mag_adc [ 3 ] ) override <nl> + { <nl> + const auto & output = mag_ - > getOutput ( ) ; <nl> + / / TODO : do we expect adc in Gauss ? Do we need NED conversion ? <nl> + mag_adc [ 0 ] = static_cast < int16_t > ( output . magnetic_field_body . x ( ) ) ; <nl> + mag_adc [ 1 ] = static_cast < int16_t > ( output . magnetic_field_body . y ( ) ) ; <nl> + mag_adc [ 2 ] = static_cast < int16_t > ( output . magnetic_field_body . z ( ) ) ; <nl> + } <nl> + <nl> + virtual void delay_micros ( uint32_t us ) override <nl> + { <nl> + sleep ( us * 1E3f ) ; <nl> + } <nl> + <nl> + virtual void delay_millis ( uint32_t ms ) override <nl> + { <nl> + sleep ( static_cast < float > ( ms ) ) ; <nl> + } <nl> + <nl> + virtual void system_reset ( bool toBootloader ) override <nl> + { <nl> + unused ( toBootloader ) ; <nl> + / / no internal state to reset <nl> + } <nl> + <nl> + private : <nl> + uint16_t accel_to_adc ( float accel ) <nl> + { <nl> + / / for MPU6050 <nl> + return static_cast < uint16_t > ( accel * kAccelAdcBits / ( kAccelG * kAccelScale ) ) ; <nl> + } <nl> + uint16_t angular_vel_to_adc ( float angular_vel ) <nl> + { <nl> + / / for MPU6050 <nl> + return static_cast < uint16_t > ( angular_vel / kGyroScale ) ; <nl> + } <nl> + int16_t temperature_to_adc ( float temperature ) <nl> + { <nl> + / / for MPU6050 <nl> + return static_cast < int16_t > ( ( temperature - 36 . 53f ) * 340 . 0f ) ; <nl> + } <nl> + void sleep ( double msec ) <nl> + { <nl> + clock ( ) - > sleep_for ( msec * 1000 . 0 ) ; <nl> + } <nl> + <nl> + <nl> + ClockBase * clock ( ) <nl> + { <nl> + return ClockFactory : : get ( ) ; <nl> + } <nl> + <nl> + private : / / types and consts <nl> + const MultiRotorParams : : EnabledSensors * enabled_sensors_ ; <nl> + const SensorCollection * sensors_ ; <nl> + const ImuBase * imu_ ; <nl> + const BarometerBase * baro_ ; <nl> + const MagnetometerBase * mag_ ; <nl> + <nl> + const uint16_t kAccelAdcBits = 512 * 8 ; / / for mpu6050 as per breezystm32 / drv_mpu6050 . c <nl> + const float kAccelScale = 1 . 0 ; / / as set in PARAM_ACCEL_SCALE in ROSFlight <nl> + const float kAccelG = 9 . 80665f ; / / as set in ROSFlight sensors . c init_sensors ( ) function <nl> + <nl> + / / 16 . 4 dps / lsb scalefactor for all Invensense devices <nl> + const float kGyroScale = ( 1 . 0f / 16 . 4f ) * ( M_PIf / 180 . 0f ) ; <nl> + <nl> + static constexpr uint OutputMotorCount = 16 ; <nl> + static constexpr uint InputChannelCount = 16 ; <nl> + <nl> + private : <nl> + / / motor outputs <nl> + uint16_t motors_pwm_ [ OutputMotorCount ] ; <nl> + uint16_t input_channels_ [ InputChannelCount ] ; <nl> + <nl> + std : : function < void ( void ) > imu_updated_callback_ ; <nl> + } ; <nl> + <nl> + } } / / namespace <nl> + # endif <nl> similarity index 91 % <nl> rename from AirLib / include / controllers / rosflight / AirSimRosFlightCommLink . hpp <nl> rename to AirLib / include / controllers / ros_flight / AirSimRosFlightCommLink . hpp <nl> mmm a / AirLib / include / controllers / rosflight / AirSimRosFlightCommLink . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / AirSimRosFlightCommLink . hpp <nl> <nl> - / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> - / / Licensed under the MIT License . <nl> - <nl> - # ifndef msr_airlib_AirSimRosFlightCommLink_hpp <nl> - # define msr_airlib_AirSimRosFlightCommLink_hpp <nl> - <nl> - # include < exception > <nl> - # include " firmware / commlink . hpp " <nl> - # include " common / Common . hpp " <nl> - # include " vehicles / MultiRotorParams . hpp " <nl> - # include " sensors / SensorCollection . hpp " <nl> - <nl> - <nl> - namespace msr { namespace airlib { <nl> - <nl> - <nl> - class AirSimRosFlightCommLink : public rosflight : : CommLink { <nl> - public : / / derived class specific methods <nl> - void getStatusMessages ( std : : vector < std : : string > & messages ) <nl> - { <nl> - if ( messages_ . size ( ) > 0 ) { <nl> - messages . insert ( messages . end ( ) , messages_ . begin ( ) , messages_ . end ( ) ) ; <nl> - messages_ . clear ( ) ; <nl> - } <nl> - } <nl> - <nl> - public : / / implement CommLink interface <nl> - virtual void init ( ) <nl> - { <nl> - messages_ . clear ( ) ; <nl> - } <nl> - <nl> - virtual void update ( ) <nl> - { <nl> - } <nl> - <nl> - virtual void set_sys_id ( int32_t sys_id ) <nl> - { <nl> - unused ( sys_id ) ; <nl> - } <nl> - <nl> - virtual void set_streaming_rate ( uint16_t param_id , int32_t rate ) <nl> - { <nl> - unused ( param_id ) ; <nl> - unused ( rate ) ; <nl> - } <nl> - <nl> - virtual void notify_param_change ( uint16_t param_id , int32_t value ) <nl> - { <nl> - unused ( param_id ) ; <nl> - unused ( value ) ; <nl> - } <nl> - <nl> - virtual void log_message ( const char * message , uint8_t error_level ) <nl> - { <nl> - unused ( error_level ) ; <nl> - messages_ . push_back ( std : : string ( message ) ) ; <nl> - } <nl> - <nl> - virtual void notify_controller_updated ( ) <nl> - { <nl> - } <nl> - <nl> - private : <nl> - std : : vector < std : : string > messages_ ; <nl> - <nl> - } ; <nl> - <nl> - <nl> - } } / / namespace <nl> - # endif <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_AirSimRosFlightCommLink_hpp <nl> + # define msr_airlib_AirSimRosFlightCommLink_hpp <nl> + <nl> + # include < exception > <nl> + # include " firmware / commlink . hpp " <nl> + # include " common / Common . hpp " <nl> + # include " vehicles / MultiRotorParams . hpp " <nl> + # include " sensors / SensorCollection . hpp " <nl> + <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + <nl> + class AirSimRosFlightCommLink : public ros_flight : : CommLink { <nl> + public : / / derived class specific methods <nl> + void getStatusMessages ( std : : vector < std : : string > & messages ) <nl> + { <nl> + if ( messages_ . size ( ) > 0 ) { <nl> + messages . insert ( messages . end ( ) , messages_ . begin ( ) , messages_ . end ( ) ) ; <nl> + messages_ . clear ( ) ; <nl> + } <nl> + } <nl> + <nl> + public : / / implement CommLink interface <nl> + virtual void init ( ) <nl> + { <nl> + messages_ . clear ( ) ; <nl> + } <nl> + <nl> + virtual void update ( ) <nl> + { <nl> + } <nl> + <nl> + virtual void set_sys_id ( int32_t sys_id ) <nl> + { <nl> + unused ( sys_id ) ; <nl> + } <nl> + <nl> + virtual void set_streaming_rate ( uint16_t param_id , int32_t rate ) <nl> + { <nl> + unused ( param_id ) ; <nl> + unused ( rate ) ; <nl> + } <nl> + <nl> + virtual void notify_param_change ( uint16_t param_id , int32_t value ) <nl> + { <nl> + unused ( param_id ) ; <nl> + unused ( value ) ; <nl> + } <nl> + <nl> + virtual void log_message ( const char * message , uint8_t error_level ) <nl> + { <nl> + unused ( error_level ) ; <nl> + messages_ . push_back ( std : : string ( message ) ) ; <nl> + } <nl> + <nl> + virtual void notify_controller_updated ( ) <nl> + { <nl> + } <nl> + <nl> + private : <nl> + std : : vector < std : : string > messages_ ; <nl> + <nl> + } ; <nl> + <nl> + <nl> + } } / / namespace <nl> + # endif <nl> similarity index 93 % <nl> rename from AirLib / include / controllers / rosflight / RosFlightDroneController . hpp <nl> rename to AirLib / include / controllers / ros_flight / RosFlightDroneController . hpp <nl> mmm a / AirLib / include / controllers / rosflight / RosFlightDroneController . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / RosFlightDroneController . hpp <nl> <nl> - / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> - / / Licensed under the MIT License . <nl> - <nl> - # ifndef msr_airlib_RosFlightDroneController_hpp <nl> - # define msr_airlib_RosFlightDroneController_hpp <nl> - <nl> - # include " controllers / DroneControllerBase . hpp " <nl> - # include " sensors / SensorCollection . hpp " <nl> - # include " physics / Environment . hpp " <nl> - # include " physics / Kinematics . hpp " <nl> - # include " vehicles / MultiRotorParams . hpp " <nl> - # include " common / Common . hpp " <nl> - # include " AirSimRosFlightBoard . hpp " <nl> - # include " AirSimRosFlightCommLink . hpp " <nl> - # include " controllers / Settings . hpp " <nl> - <nl> - STRICT_MODE_OFF <nl> - # include " firmware / firmware . hpp " <nl> - STRICT_MODE_ON <nl> - <nl> - namespace msr { namespace airlib { <nl> - <nl> - class RosFlightDroneController : public DroneControllerBase { <nl> - <nl> - public : <nl> - RosFlightDroneController ( const SensorCollection * sensors , const MultiRotorParams * vehicle_params ) <nl> - : vehicle_params_ ( vehicle_params ) <nl> - { <nl> - sensors_ = sensors ; <nl> - <nl> - board_ . reset ( new AirSimRosFlightBoard ( & vehicle_params_ - > getParams ( ) . enabled_sensors , sensors_ ) ) ; <nl> - comm_link_ . reset ( new AirSimRosFlightCommLink ( ) ) ; <nl> - firmware_ . reset ( new rosflight : : Firmware ( board_ . get ( ) , comm_link_ . get ( ) ) ) ; <nl> - firmware_ - > setup ( ) ; <nl> - <nl> - Settings child ; <nl> - Settings : : singleton ( ) . getChild ( " RosFlight " , child ) ; <nl> - remote_control_id_ = child . getInt ( " RemoteControlID " , 0 ) ; <nl> - } <nl> - <nl> - void initializePhysics ( const Environment * environment , const Kinematics : : State * kinematics ) <nl> - { <nl> - environment_ = environment ; <nl> - kinematics_ = kinematics ; <nl> - } <nl> - <nl> - public : <nl> - / / * * * Start : VehicleControllerBase implementation * * * / / <nl> - virtual void reset ( ) override <nl> - { <nl> - board_ - > system_reset ( false ) ; <nl> - } <nl> - <nl> - virtual void update ( ) override <nl> - { <nl> - board_ - > notifySensorUpdated ( rosflight : : Board : : SensorType : : Imu ) ; <nl> - firmware_ - > loop ( ) ; <nl> - } <nl> - <nl> - virtual void start ( ) override <nl> - { <nl> - } <nl> - virtual void stop ( ) override <nl> - { <nl> - } <nl> - <nl> - virtual size_t getVertexCount ( ) override <nl> - { <nl> - return vehicle_params_ - > getParams ( ) . rotor_count ; <nl> - } <nl> - <nl> - virtual real_T getVertexControlSignal ( unsigned int rotor_index ) override <nl> - { <nl> - / / convert counter clockwise index to ArduCopter ' s QuadX style index <nl> - unsigned int index_quadx ; <nl> - switch ( rotor_index ) <nl> - { <nl> - case 0 : index_quadx = 1 ; break ; <nl> - case 1 : index_quadx = 2 ; break ; <nl> - case 2 : index_quadx = 3 ; break ; <nl> - case 3 : index_quadx = 0 ; break ; <nl> - default : <nl> - throw std : : runtime_error ( " Rotor index beyond 3 is not supported yet in ROSFlight firmware " ) ; <nl> - } <nl> - <nl> - auto control_signal = board_ - > getMotorControlSignal ( index_quadx ) ; <nl> - <nl> - return control_signal ; <nl> - } <nl> - <nl> - virtual void getStatusMessages ( std : : vector < std : : string > & messages ) override <nl> - { <nl> - comm_link_ - > getStatusMessages ( messages ) ; <nl> - } <nl> - <nl> - virtual bool isOffboardMode ( ) override <nl> - { <nl> - / / TODO : support offboard mode <nl> - return false ; <nl> - } <nl> - <nl> - virtual bool isSimulationMode ( ) override <nl> - { <nl> - return true ; <nl> - } <nl> - <nl> - virtual void setOffboardMode ( bool is_set ) override <nl> - { <nl> - / / TODO : implement this <nl> - } <nl> - <nl> - virtual void setSimulationMode ( bool is_set ) override <nl> - { <nl> - if ( ! is_set ) <nl> - throw VehicleCommandNotImplementedException ( " setting non - simulation mode is not supported yet " ) ; <nl> - } <nl> - / / * * * End : VehicleControllerBase implementation * * * / / <nl> - <nl> - / / * * * Start : DroneControllerBase implementation * * * / / <nl> - public : <nl> - Vector3r getPosition ( ) override <nl> - { <nl> - return kinematics_ - > pose . position ; <nl> - } <nl> - <nl> - Vector3r getVelocity ( ) override <nl> - { <nl> - return kinematics_ - > twist . linear ; <nl> - } <nl> - <nl> - Quaternionr getOrientation ( ) override <nl> - { <nl> - return kinematics_ - > pose . orientation ; <nl> - } <nl> - <nl> - LandedState getLandedState ( ) override <nl> - { <nl> - / / todo : implement this <nl> - return LandedState : : Landed ; <nl> - } <nl> - <nl> - virtual int getRemoteControlID ( ) override <nl> - { <nl> - return remote_control_id_ ; <nl> - } <nl> - <nl> - RCData getRCData ( ) override <nl> - { <nl> - return RCData ( ) ; <nl> - } <nl> - <nl> - void setRCData ( const RCData & rcData ) override <nl> - { <nl> - if ( rcData . is_connected ) { <nl> - board_ - > setInputChannel ( 0 , angleToPwm ( rcData . roll ) ) ; / / X <nl> - board_ - > setInputChannel ( 1 , angleToPwm ( rcData . yaw ) ) ; / / Y <nl> - board_ - > setInputChannel ( 2 , thrustToPwm ( rcData . throttle ) ) ; / / F <nl> - board_ - > setInputChannel ( 3 , angleToPwm ( - rcData . pitch ) ) ; / / Z <nl> - board_ - > setInputChannel ( 4 , switchToPwm ( rcData . switch1 ) ) ; <nl> - board_ - > setInputChannel ( 5 , switchToPwm ( rcData . switch2 ) ) ; <nl> - board_ - > setInputChannel ( 6 , switchToPwm ( rcData . switch3 ) ) ; <nl> - board_ - > setInputChannel ( 7 , switchToPwm ( rcData . switch4 ) ) ; <nl> - board_ - > setInputChannel ( 8 , switchToPwm ( rcData . switch5 ) ) ; <nl> - board_ - > setInputChannel ( 9 , switchToPwm ( rcData . switch6 ) ) ; <nl> - board_ - > setInputChannel ( 10 , switchToPwm ( rcData . switch7 ) ) ; <nl> - board_ - > setInputChannel ( 11 , switchToPwm ( rcData . switch8 ) ) ; <nl> - } <nl> - / / else we don ' t have RC data <nl> - } <nl> - <nl> - bool armDisarm ( bool arm , CancelableBase & cancelable_action ) override <nl> - { <nl> - return true ; <nl> - } <nl> - <nl> - bool takeoff ( float max_wait_seconds , CancelableBase & cancelable_action ) override <nl> - { <nl> - return true ; <nl> - } <nl> - <nl> - bool land ( float max_wait_seconds , CancelableBase & cancelable_action ) override <nl> - { <nl> - return true ; <nl> - } <nl> - <nl> - bool goHome ( CancelableBase & cancelable_action ) override <nl> - { <nl> - return true ; <nl> - } <nl> - <nl> - bool hover ( CancelableBase & cancelable_action ) override <nl> - { <nl> - return true ; <nl> - } <nl> - <nl> - GeoPoint getHomePoint ( ) override <nl> - { <nl> - return environment_ - > getInitialState ( ) . geo_point ; <nl> - } <nl> - <nl> - GeoPoint getGpsLocation ( ) override <nl> - { <nl> - return environment_ - > getState ( ) . geo_point ; <nl> - } <nl> - <nl> - virtual void reportTelemetry ( float renderTime ) override <nl> - { <nl> - / / TODO : implement this <nl> - } <nl> - <nl> - float getCommandPeriod ( ) override <nl> - { <nl> - return 1 . 0f / 50 ; / / 50hz <nl> - } <nl> - <nl> - float getTakeoffZ ( ) override <nl> - { <nl> - / / pick a number , 3 meters is probably safe <nl> - / / enough to get out of the backwash turbulance . Negative due to NED coordinate system . <nl> - return - 3 . 0f ; <nl> - } <nl> - <nl> - float getDistanceAccuracy ( ) override <nl> - { <nl> - return 0 . 5f ; / / measured in simulator by firing commands " MoveToLocation - x 0 - y 0 " multiple times and looking at distance travelled <nl> - } <nl> - <nl> - protected : <nl> - void commandRollPitchZ ( float pitch , float roll , float z , float yaw ) override <nl> - { <nl> - / / TODO : implement this <nl> - } <nl> - <nl> - void commandVelocity ( float vx , float vy , float vz , const YawMode & yaw_mode ) override <nl> - { <nl> - / / TODO : implement this <nl> - } <nl> - <nl> - void commandVelocityZ ( float vx , float vy , float z , const YawMode & yaw_mode ) override <nl> - { <nl> - / / TODO : implement this <nl> - } <nl> - <nl> - void commandPosition ( float x , float y , float z , const YawMode & yaw_mode ) override <nl> - { <nl> - / / TODO : implement this <nl> - } <nl> - <nl> - const VehicleParams & getVehicleParams ( ) override <nl> - { <nl> - / / used for safety algos . For now just use defaults <nl> - static const VehicleParams safety_params ; <nl> - return safety_params ; <nl> - } <nl> - / / * * * End : DroneControllerBase implementation * * * / / <nl> - <nl> - private : <nl> - / / convert pitch , roll , yaw from - 1 to 1 to PWM <nl> - static uint16_t angleToPwm ( float angle ) <nl> - { <nl> - return static_cast < uint16_t > ( angle * 500 . 0f + 1500 . 0f ) ; <nl> - } <nl> - static uint16_t thrustToPwm ( float thrust ) <nl> - { <nl> - return static_cast < uint16_t > ( ( thrust < 0 ? 0 : thrust ) * 1000 . 0f + 1000 . 0f ) ; <nl> - } <nl> - static uint16_t switchToPwm ( uint switchVal , uint maxSwitchVal = 1 ) <nl> - { <nl> - return static_cast < uint16_t > ( 1000 . 0f * switchVal / maxSwitchVal + 1000 . 0f ) ; <nl> - } <nl> - <nl> - private : <nl> - const MultiRotorParams * vehicle_params_ ; <nl> - const Kinematics : : State * kinematics_ ; <nl> - const Environment * environment_ ; <nl> - const SensorCollection * sensors_ ; <nl> - <nl> - int remote_control_id_ = 0 ; <nl> - <nl> - unique_ptr < AirSimRosFlightBoard > board_ ; <nl> - unique_ptr < AirSimRosFlightCommLink > comm_link_ ; <nl> - unique_ptr < rosflight : : Firmware > firmware_ ; <nl> - } ; <nl> - <nl> - } } / / namespace <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_RosFlightDroneController_hpp <nl> + # define msr_airlib_RosFlightDroneController_hpp <nl> + <nl> + # include " controllers / DroneControllerBase . hpp " <nl> + # include " sensors / SensorCollection . hpp " <nl> + # include " physics / Environment . hpp " <nl> + # include " physics / Kinematics . hpp " <nl> + # include " vehicles / MultiRotorParams . hpp " <nl> + # include " common / Common . hpp " <nl> + # include " AirSimRosFlightBoard . hpp " <nl> + # include " AirSimRosFlightCommLink . hpp " <nl> + # include " controllers / Settings . hpp " <nl> + <nl> + STRICT_MODE_OFF <nl> + # include " firmware / firmware . hpp " <nl> + STRICT_MODE_ON <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + class RosFlightDroneController : public DroneControllerBase { <nl> + <nl> + public : <nl> + RosFlightDroneController ( const SensorCollection * sensors , const MultiRotorParams * vehicle_params ) <nl> + : vehicle_params_ ( vehicle_params ) <nl> + { <nl> + sensors_ = sensors ; <nl> + <nl> + board_ . reset ( new AirSimRosFlightBoard ( & vehicle_params_ - > getParams ( ) . enabled_sensors , sensors_ ) ) ; <nl> + comm_link_ . reset ( new AirSimRosFlightCommLink ( ) ) ; <nl> + firmware_ . reset ( new ros_flight : : Firmware ( board_ . get ( ) , comm_link_ . get ( ) ) ) ; <nl> + firmware_ - > setup ( ) ; <nl> + <nl> + Settings child ; <nl> + Settings : : singleton ( ) . getChild ( " RosFlight " , child ) ; <nl> + remote_control_id_ = child . getInt ( " RemoteControlID " , 0 ) ; <nl> + } <nl> + <nl> + void initializePhysics ( const Environment * environment , const Kinematics : : State * kinematics ) <nl> + { <nl> + environment_ = environment ; <nl> + kinematics_ = kinematics ; <nl> + } <nl> + <nl> + public : <nl> + / / * * * Start : VehicleControllerBase implementation * * * / / <nl> + virtual void reset ( ) override <nl> + { <nl> + board_ - > system_reset ( false ) ; <nl> + } <nl> + <nl> + virtual void update ( ) override <nl> + { <nl> + board_ - > notifySensorUpdated ( ros_flight : : Board : : SensorType : : Imu ) ; <nl> + firmware_ - > loop ( ) ; <nl> + } <nl> + <nl> + virtual void start ( ) override <nl> + { <nl> + } <nl> + virtual void stop ( ) override <nl> + { <nl> + } <nl> + <nl> + virtual size_t getVertexCount ( ) override <nl> + { <nl> + return vehicle_params_ - > getParams ( ) . rotor_count ; <nl> + } <nl> + <nl> + virtual real_T getVertexControlSignal ( unsigned int rotor_index ) override <nl> + { <nl> + / / convert counter clockwise index to ArduCopter ' s QuadX style index <nl> + unsigned int index_quadx ; <nl> + switch ( rotor_index ) <nl> + { <nl> + case 0 : index_quadx = 1 ; break ; <nl> + case 1 : index_quadx = 2 ; break ; <nl> + case 2 : index_quadx = 3 ; break ; <nl> + case 3 : index_quadx = 0 ; break ; <nl> + default : <nl> + throw std : : runtime_error ( " Rotor index beyond 3 is not supported yet in ROSFlight firmware " ) ; <nl> + } <nl> + <nl> + auto control_signal = board_ - > getMotorControlSignal ( index_quadx ) ; <nl> + <nl> + return control_signal ; <nl> + } <nl> + <nl> + virtual void getStatusMessages ( std : : vector < std : : string > & messages ) override <nl> + { <nl> + comm_link_ - > getStatusMessages ( messages ) ; <nl> + } <nl> + <nl> + virtual bool isOffboardMode ( ) override <nl> + { <nl> + / / TODO : support offboard mode <nl> + return false ; <nl> + } <nl> + <nl> + virtual bool isSimulationMode ( ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + virtual void setOffboardMode ( bool is_set ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + virtual void setSimulationMode ( bool is_set ) override <nl> + { <nl> + if ( ! is_set ) <nl> + throw VehicleCommandNotImplementedException ( " setting non - simulation mode is not supported yet " ) ; <nl> + } <nl> + / / * * * End : VehicleControllerBase implementation * * * / / <nl> + <nl> + / / * * * Start : DroneControllerBase implementation * * * / / <nl> + public : <nl> + Vector3r getPosition ( ) override <nl> + { <nl> + return kinematics_ - > pose . position ; <nl> + } <nl> + <nl> + Vector3r getVelocity ( ) override <nl> + { <nl> + return kinematics_ - > twist . linear ; <nl> + } <nl> + <nl> + Quaternionr getOrientation ( ) override <nl> + { <nl> + return kinematics_ - > pose . orientation ; <nl> + } <nl> + <nl> + LandedState getLandedState ( ) override <nl> + { <nl> + / / TODO : implement this <nl> + return LandedState : : Landed ; <nl> + } <nl> + <nl> + virtual int getRemoteControlID ( ) override <nl> + { <nl> + return remote_control_id_ ; <nl> + } <nl> + <nl> + RCData getRCData ( ) override <nl> + { <nl> + return RCData ( ) ; <nl> + } <nl> + <nl> + void setRCData ( const RCData & rcData ) override <nl> + { <nl> + if ( rcData . is_connected ) { <nl> + board_ - > setInputChannel ( 0 , angleToPwm ( rcData . roll ) ) ; / / X <nl> + board_ - > setInputChannel ( 1 , angleToPwm ( rcData . yaw ) ) ; / / Y <nl> + board_ - > setInputChannel ( 2 , thrustToPwm ( rcData . throttle ) ) ; / / F <nl> + board_ - > setInputChannel ( 3 , angleToPwm ( - rcData . pitch ) ) ; / / Z <nl> + board_ - > setInputChannel ( 4 , switchToPwm ( rcData . switch1 ) ) ; <nl> + board_ - > setInputChannel ( 5 , switchToPwm ( rcData . switch2 ) ) ; <nl> + board_ - > setInputChannel ( 6 , switchToPwm ( rcData . switch3 ) ) ; <nl> + board_ - > setInputChannel ( 7 , switchToPwm ( rcData . switch4 ) ) ; <nl> + board_ - > setInputChannel ( 8 , switchToPwm ( rcData . switch5 ) ) ; <nl> + board_ - > setInputChannel ( 9 , switchToPwm ( rcData . switch6 ) ) ; <nl> + board_ - > setInputChannel ( 10 , switchToPwm ( rcData . switch7 ) ) ; <nl> + board_ - > setInputChannel ( 11 , switchToPwm ( rcData . switch8 ) ) ; <nl> + } <nl> + / / else we don ' t have RC data <nl> + } <nl> + <nl> + bool armDisarm ( bool arm , CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool takeoff ( float max_wait_seconds , CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool land ( float max_wait_seconds , CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool goHome ( CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool hover ( CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + GeoPoint getHomePoint ( ) override <nl> + { <nl> + return environment_ - > getInitialState ( ) . geo_point ; <nl> + } <nl> + <nl> + GeoPoint getGpsLocation ( ) override <nl> + { <nl> + return environment_ - > getState ( ) . geo_point ; <nl> + } <nl> + <nl> + virtual void reportTelemetry ( float renderTime ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + float getCommandPeriod ( ) override <nl> + { <nl> + return 1 . 0f / 50 ; / / 50hz <nl> + } <nl> + <nl> + float getTakeoffZ ( ) override <nl> + { <nl> + / / pick a number , 3 meters is probably safe <nl> + / / enough to get out of the backwash turbulance . Negative due to NED coordinate system . <nl> + return - 3 . 0f ; <nl> + } <nl> + <nl> + float getDistanceAccuracy ( ) override <nl> + { <nl> + return 0 . 5f ; / / measured in simulator by firing commands " MoveToLocation - x 0 - y 0 " multiple times and looking at distance travelled <nl> + } <nl> + <nl> + protected : <nl> + void commandRollPitchZ ( float pitch , float roll , float z , float yaw ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + void commandVelocity ( float vx , float vy , float vz , const YawMode & yaw_mode ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + void commandVelocityZ ( float vx , float vy , float z , const YawMode & yaw_mode ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + void commandPosition ( float x , float y , float z , const YawMode & yaw_mode ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + const VehicleParams & getVehicleParams ( ) override <nl> + { <nl> + / / used for safety algos . For now just use defaults <nl> + static const VehicleParams safety_params ; <nl> + return safety_params ; <nl> + } <nl> + / / * * * End : DroneControllerBase implementation * * * / / <nl> + <nl> + private : <nl> + / / convert pitch , roll , yaw from - 1 to 1 to PWM <nl> + static uint16_t angleToPwm ( float angle ) <nl> + { <nl> + return static_cast < uint16_t > ( angle * 500 . 0f + 1500 . 0f ) ; <nl> + } <nl> + static uint16_t thrustToPwm ( float thrust ) <nl> + { <nl> + return static_cast < uint16_t > ( ( thrust < 0 ? 0 : thrust ) * 1000 . 0f + 1000 . 0f ) ; <nl> + } <nl> + static uint16_t switchToPwm ( uint switchVal , uint maxSwitchVal = 1 ) <nl> + { <nl> + return static_cast < uint16_t > ( 1000 . 0f * switchVal / maxSwitchVal + 1000 . 0f ) ; <nl> + } <nl> + <nl> + private : <nl> + const MultiRotorParams * vehicle_params_ ; <nl> + const Kinematics : : State * kinematics_ ; <nl> + const Environment * environment_ ; <nl> + const SensorCollection * sensors_ ; <nl> + <nl> + int remote_control_id_ = 0 ; <nl> + <nl> + unique_ptr < AirSimRosFlightBoard > board_ ; <nl> + unique_ptr < AirSimRosFlightCommLink > comm_link_ ; <nl> + unique_ptr < ros_flight : : Firmware > firmware_ ; <nl> + } ; <nl> + <nl> + } } / / namespace <nl> # endif <nl> \ No newline at end of file <nl> similarity index 95 % <nl> rename from AirLib / include / controllers / rosflight / firmware / board . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / board . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / board . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / board . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - # include < functional > <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Board { <nl> - public : / / types <nl> - enum SensorType { <nl> - Imu = 0 , <nl> - Baro = 1 , <nl> - Mag = 2 , <nl> - Gps = 3 , <nl> - Sonar = 4 , <nl> - DiffPressure = 5 <nl> - } ; <nl> - <nl> - public : <nl> - virtual void init ( ) = 0 ; <nl> - virtual uint64_t micros ( ) = 0 ; <nl> - virtual uint32_t millis ( ) = 0 ; <nl> - virtual void init_sensors ( uint16_t & acc1G , float & gyro_scale , int boardVersion , const std : : function < void ( void ) > & imu_updated_callback ) = 0 ; <nl> - virtual bool is_sensor_present ( SensorType type ) = 0 ; <nl> - virtual uint16_t pwmRead ( int16_t channel ) = 0 ; <nl> - virtual void pwmInit ( bool useCPPM , bool usePwmFilter , bool fastPWM , uint32_t motorPwmRate , uint16_t idlePulseUsec ) = 0 ; <nl> - virtual void pwmWriteMotor ( uint8_t index , uint16_t value ) = 0 ; <nl> - virtual void set_led ( uint8_t index , bool is_on ) = 0 ; <nl> - virtual void toggle_led ( uint8_t index ) = 0 ; <nl> - virtual void init_params ( ) = 0 ; <nl> - virtual bool read_params ( ) = 0 ; <nl> - virtual bool write_params ( bool blink_led ) = 0 ; <nl> - virtual void init_imu ( uint16_t & acc1G , float & gyroScale , int boardVersion ) = 0 ; <nl> - virtual void read_accel ( int16_t accel_adc [ 3 ] ) = 0 ; <nl> - virtual void read_gyro ( int16_t gyro_adc [ 3 ] ) = 0 ; <nl> - virtual void read_temperature ( int16_t & temp ) = 0 ; <nl> - virtual void read_baro ( float & altitude , float & pressure , float & temperature ) = 0 ; <nl> - virtual void read_diff_pressure ( float & differential_pressure , float & temp , float & velocity ) = 0 ; <nl> - virtual float read_sonar ( ) = 0 ; <nl> - virtual void read_mag ( int16_t mag_adc [ 3 ] ) = 0 ; <nl> - virtual void delay_micros ( uint32_t us ) = 0 ; <nl> - virtual void delay_millis ( uint32_t ms ) = 0 ; <nl> - virtual void system_reset ( bool toBootloader ) = 0 ; <nl> - } ; <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + # include < functional > <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Board { <nl> + public : / / types <nl> + enum SensorType { <nl> + Imu = 0 , <nl> + Baro = 1 , <nl> + Mag = 2 , <nl> + Gps = 3 , <nl> + Sonar = 4 , <nl> + DiffPressure = 5 <nl> + } ; <nl> + <nl> + public : <nl> + virtual void init ( ) = 0 ; <nl> + virtual uint64_t micros ( ) = 0 ; <nl> + virtual uint32_t millis ( ) = 0 ; <nl> + virtual void init_sensors ( uint16_t & acc1G , float & gyro_scale , int boardVersion , const std : : function < void ( void ) > & imu_updated_callback ) = 0 ; <nl> + virtual bool is_sensor_present ( SensorType type ) = 0 ; <nl> + virtual uint16_t pwmRead ( int16_t channel ) = 0 ; <nl> + virtual void pwmInit ( bool useCPPM , bool usePwmFilter , bool fastPWM , uint32_t motorPwmRate , uint16_t idlePulseUsec ) = 0 ; <nl> + virtual void pwmWriteMotor ( uint8_t index , uint16_t value ) = 0 ; <nl> + virtual void set_led ( uint8_t index , bool is_on ) = 0 ; <nl> + virtual void toggle_led ( uint8_t index ) = 0 ; <nl> + virtual void init_params ( ) = 0 ; <nl> + virtual bool read_params ( ) = 0 ; <nl> + virtual bool write_params ( bool blink_led ) = 0 ; <nl> + virtual void init_imu ( uint16_t & acc1G , float & gyroScale , int boardVersion ) = 0 ; <nl> + virtual void read_accel ( int16_t accel_adc [ 3 ] ) = 0 ; <nl> + virtual void read_gyro ( int16_t gyro_adc [ 3 ] ) = 0 ; <nl> + virtual void read_temperature ( int16_t & temp ) = 0 ; <nl> + virtual void read_baro ( float & altitude , float & pressure , float & temperature ) = 0 ; <nl> + virtual void read_diff_pressure ( float & differential_pressure , float & temp , float & velocity ) = 0 ; <nl> + virtual float read_sonar ( ) = 0 ; <nl> + virtual void read_mag ( int16_t mag_adc [ 3 ] ) = 0 ; <nl> + virtual void delay_micros ( uint32_t us ) = 0 ; <nl> + virtual void delay_millis ( uint32_t ms ) = 0 ; <nl> + virtual void system_reset ( bool toBootloader ) = 0 ; <nl> + } ; <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 89 % <nl> rename from AirLib / include / controllers / rosflight / firmware / commlink . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / commlink . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / commlink . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / commlink . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class CommLink { <nl> - public : <nl> - virtual void init ( ) = 0 ; <nl> - virtual void update ( ) = 0 ; <nl> - virtual void set_sys_id ( int32_t sys_id ) = 0 ; <nl> - virtual void set_streaming_rate ( uint16_t param_id , int32_t rate ) = 0 ; <nl> - virtual void notify_param_change ( uint16_t param_id , int32_t value ) = 0 ; <nl> - virtual void log_message ( const char * message , uint8_t error_level ) = 0 ; <nl> - virtual void notify_controller_updated ( ) = 0 ; <nl> - } ; <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class CommLink { <nl> + public : <nl> + virtual void init ( ) = 0 ; <nl> + virtual void update ( ) = 0 ; <nl> + virtual void set_sys_id ( int32_t sys_id ) = 0 ; <nl> + virtual void set_streaming_rate ( uint16_t param_id , int32_t rate ) = 0 ; <nl> + virtual void notify_param_change ( uint16_t param_id , int32_t value ) = 0 ; <nl> + virtual void log_message ( const char * message , uint8_t error_level ) = 0 ; <nl> + virtual void notify_controller_updated ( ) = 0 ; <nl> + } ; <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 93 % <nl> rename from AirLib / include / controllers / rosflight / firmware / commonstate . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / commonstate . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / commonstate . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / commonstate . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdio > <nl> - <nl> - namespace rosflight { <nl> - <nl> - class CommonState { <nl> - public : <nl> - typedef enum <nl> - { <nl> - ARMED , <nl> - DISARMED , <nl> - FAILSAFE_ARMED , <nl> - FAILSAFE_DISARMED <nl> - } armed_state_t ; <nl> - <nl> - armed_state_t get_armed_state ( ) { <nl> - return _armed_state ; <nl> - } <nl> - void setArmedState ( armed_state_t state ) { <nl> - _armed_state = state ; <nl> - } <nl> - <nl> - bool is_armed ( ) <nl> - { <nl> - return _armed_state = = armed_state_t : : ARMED ; <nl> - } <nl> - bool is_disarmed ( ) <nl> - { <nl> - return _armed_state = = armed_state_t : : DISARMED ; <nl> - } <nl> - void set_disarm ( ) <nl> - { <nl> - setArmedState ( armed_state_t : : DISARMED ) ; <nl> - } <nl> - void set_arm ( ) <nl> - { <nl> - setArmedState ( armed_state_t : : ARMED ) ; <nl> - } <nl> - <nl> - static std : : string stringf ( const char * format , . . . ) <nl> - { <nl> - va_list args ; <nl> - va_start ( args , format ) ; <nl> - IGNORE_FORMAT_STRING_ON <nl> - auto size = _vscprintf ( format , args ) + 1U ; <nl> - IGNORE_FORMAT_STRING_OFF <nl> - std : : unique_ptr < char [ ] > buf ( new char [ size ] ) ; <nl> - <nl> - # ifndef _MSC_VER <nl> - IGNORE_FORMAT_STRING_ON <nl> - vsnprintf ( buf . get ( ) , size , format , args ) ; <nl> - IGNORE_FORMAT_STRING_OFF <nl> - # else <nl> - vsnprintf_s ( buf . get ( ) , size , _TRUNCATE , format , args ) ; <nl> - # endif <nl> - <nl> - va_end ( args ) ; <nl> - <nl> - return std : : string ( buf . get ( ) ) ; <nl> - } <nl> - <nl> - private : <nl> - # ifndef _MSC_VER <nl> - static int _vscprintf ( const char * format , va_list pargs ) <nl> - { <nl> - int retval ; <nl> - va_list argcopy ; <nl> - va_copy ( argcopy , pargs ) ; <nl> - IGNORE_FORMAT_STRING_ON <nl> - retval = vsnprintf ( NULL , 0 , format , argcopy ) ; <nl> - IGNORE_FORMAT_STRING_OFF <nl> - va_end ( argcopy ) ; <nl> - return retval ; <nl> - } <nl> - # endif <nl> - <nl> - private : <nl> - armed_state_t _armed_state ; <nl> - } ; <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdio > <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class CommonState { <nl> + public : <nl> + typedef enum <nl> + { <nl> + ARMED , <nl> + DISARMED , <nl> + FAILSAFE_ARMED , <nl> + FAILSAFE_DISARMED <nl> + } armed_state_t ; <nl> + <nl> + armed_state_t get_armed_state ( ) { <nl> + return _armed_state ; <nl> + } <nl> + void setArmedState ( armed_state_t state ) { <nl> + _armed_state = state ; <nl> + } <nl> + <nl> + bool is_armed ( ) <nl> + { <nl> + return _armed_state = = armed_state_t : : ARMED ; <nl> + } <nl> + bool is_disarmed ( ) <nl> + { <nl> + return _armed_state = = armed_state_t : : DISARMED ; <nl> + } <nl> + void set_disarm ( ) <nl> + { <nl> + setArmedState ( armed_state_t : : DISARMED ) ; <nl> + } <nl> + void set_arm ( ) <nl> + { <nl> + setArmedState ( armed_state_t : : ARMED ) ; <nl> + } <nl> + <nl> + static std : : string stringf ( const char * format , . . . ) <nl> + { <nl> + va_list args ; <nl> + va_start ( args , format ) ; <nl> + IGNORE_FORMAT_STRING_ON <nl> + auto size = _vscprintf ( format , args ) + 1U ; <nl> + IGNORE_FORMAT_STRING_OFF <nl> + std : : unique_ptr < char [ ] > buf ( new char [ size ] ) ; <nl> + <nl> + # ifndef _MSC_VER <nl> + IGNORE_FORMAT_STRING_ON <nl> + vsnprintf ( buf . get ( ) , size , format , args ) ; <nl> + IGNORE_FORMAT_STRING_OFF <nl> + # else <nl> + vsnprintf_s ( buf . get ( ) , size , _TRUNCATE , format , args ) ; <nl> + # endif <nl> + <nl> + va_end ( args ) ; <nl> + <nl> + return std : : string ( buf . get ( ) ) ; <nl> + } <nl> + <nl> + private : <nl> + # ifndef _MSC_VER <nl> + static int _vscprintf ( const char * format , va_list pargs ) <nl> + { <nl> + int retval ; <nl> + va_list argcopy ; <nl> + va_copy ( argcopy , pargs ) ; <nl> + IGNORE_FORMAT_STRING_ON <nl> + retval = vsnprintf ( NULL , 0 , format , argcopy ) ; <nl> + IGNORE_FORMAT_STRING_OFF <nl> + va_end ( argcopy ) ; <nl> + return retval ; <nl> + } <nl> + # endif <nl> + <nl> + private : <nl> + armed_state_t _armed_state ; <nl> + } ; <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / controller . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / controller . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / controller . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / controller . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - # include < cstdbool > <nl> - <nl> - # include " mux . hpp " <nl> - # include " param . hpp " <nl> - # include " estimator . hpp " <nl> - # include " mixer . hpp " <nl> - # include " commonstate . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Controller { <nl> - public : <nl> - void run_controller ( ) ; <nl> - void init ( CommonState * _common_state , Board * _board , Mux * _mux , Mixer * _mixer , Estimator * _estimator , Params * _params , CommLink * _comm_link ) ; <nl> - <nl> - private : <nl> - typedef struct <nl> - { <nl> - Params : : param_id_t kp_param_id ; <nl> - Params : : param_id_t ki_param_id ; <nl> - Params : : param_id_t kd_param_id ; <nl> - <nl> - float * current_x ; <nl> - float * current_xdot ; <nl> - float * commanded_x ; <nl> - float * output ; <nl> - <nl> - float max ; <nl> - float min ; <nl> - <nl> - float integrator ; <nl> - float prev_time ; <nl> - float prev_x ; <nl> - float differentiator ; <nl> - float tau ; <nl> - } pid_t ; <nl> - <nl> - pid_t pid_roll ; <nl> - pid_t pid_roll_rate ; <nl> - pid_t pid_pitch ; <nl> - pid_t pid_pitch_rate ; <nl> - pid_t pid_yaw_rate ; <nl> - pid_t pid_altitude ; <nl> - <nl> - Estimator * estimator ; <nl> - CommonState * common_state ; <nl> - Mux * mux ; <nl> - Mixer * mixer ; <nl> - Params * params ; <nl> - Board * board ; <nl> - CommLink * comm_link ; <nl> - <nl> - void init_pid ( pid_t * pid , Params : : param_id_t kp_param_id , Params : : param_id_t ki_param_id , Params : : param_id_t kd_param_id , float * current_x , float * current_xdot , float * commanded_x , float * output , float max , float min ) ; <nl> - void run_pid ( pid_t * pid , float dt ) ; <nl> - <nl> - / / variables used by methods <nl> - float prev_time = 0 . 0f ; / / run_controller <nl> - <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - void Controller : : init ( CommonState * _common_state , Board * _board , Mux * _mux , Mixer * _mixer , Estimator * _estimator , Params * _params , CommLink * _comm_link ) <nl> - { <nl> - estimator = _estimator ; <nl> - mux = _mux ; <nl> - mixer = _mixer ; <nl> - common_state = _common_state ; <nl> - params = _params ; <nl> - board = _board ; <nl> - comm_link = _comm_link ; <nl> - <nl> - Mux : : control_t & combined_control = mux - > combined_control ( ) ; <nl> - Mixer : : command_t & mixer_command = mixer - > getCommand ( ) ; <nl> - <nl> - init_pid ( & pid_roll , <nl> - Params : : PARAM_PID_ROLL_ANGLE_P , <nl> - Params : : PARAM_PID_ROLL_ANGLE_I , <nl> - Params : : PARAM_PID_ROLL_ANGLE_D , <nl> - & _estimator - > state ( ) . euler . x , <nl> - & _estimator - > state ( ) . omega . x , <nl> - & combined_control . x . value , <nl> - & mixer_command . x , <nl> - params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> - - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> - <nl> - init_pid ( & pid_pitch , <nl> - Params : : PARAM_PID_PITCH_ANGLE_P , <nl> - Params : : PARAM_PID_PITCH_ANGLE_I , <nl> - Params : : PARAM_PID_PITCH_ANGLE_D , <nl> - & _estimator - > state ( ) . euler . y , <nl> - & _estimator - > state ( ) . omega . y , <nl> - & combined_control . y . value , <nl> - & mixer_command . y , <nl> - params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> - - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> - <nl> - init_pid ( & pid_roll_rate , <nl> - Params : : PARAM_PID_ROLL_RATE_P , <nl> - Params : : PARAM_PID_ROLL_RATE_I , <nl> - Params : : PARAM_PID_ROLL_RATE_D , <nl> - & _estimator - > state ( ) . omega . x , <nl> - NULL , <nl> - & combined_control . x . value , <nl> - & mixer_command . x , <nl> - params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> - - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> - <nl> - init_pid ( & pid_pitch_rate , <nl> - Params : : PARAM_PID_PITCH_RATE_P , <nl> - Params : : PARAM_PID_PITCH_RATE_I , <nl> - Params : : PARAM_PID_PITCH_RATE_D , <nl> - & _estimator - > state ( ) . omega . y , <nl> - NULL , <nl> - & combined_control . y . value , <nl> - & mixer_command . y , <nl> - params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> - - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> - <nl> - init_pid ( & pid_yaw_rate , <nl> - Params : : PARAM_PID_YAW_RATE_P , <nl> - Params : : PARAM_PID_YAW_RATE_I , <nl> - Params : : PARAM_PID_YAW_RATE_D , <nl> - & _estimator - > state ( ) . omega . z , <nl> - NULL , <nl> - & combined_control . z . value , <nl> - & mixer_command . z , <nl> - params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> - - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> - <nl> - init_pid ( & pid_altitude , <nl> - Params : : PARAM_PID_ALT_P , <nl> - Params : : PARAM_PID_ALT_I , <nl> - Params : : PARAM_PID_ALT_D , <nl> - & _estimator - > state ( ) . altitude , <nl> - NULL , <nl> - & combined_control . F . value , <nl> - & mixer_command . F , <nl> - static_cast < float > ( params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) ) , <nl> - 0 . 0f ) ; <nl> - } <nl> - <nl> - void Controller : : init_pid ( pid_t * pid , Params : : param_id_t kp_param_id , Params : : param_id_t ki_param_id , Params : : param_id_t kd_param_id , float * current_x , float * current_xdot , float * commanded_x , float * output , float max , float min ) <nl> - { <nl> - pid - > kp_param_id = kp_param_id ; <nl> - pid - > ki_param_id = ki_param_id ; <nl> - pid - > kd_param_id = kd_param_id ; <nl> - pid - > current_x = current_x ; <nl> - pid - > current_xdot = current_xdot ; <nl> - pid - > commanded_x = commanded_x ; <nl> - pid - > output = output ; <nl> - pid - > max = max ; <nl> - pid - > min = min ; <nl> - pid - > integrator = 0 . 0f ; <nl> - pid - > prev_time = board - > micros ( ) * 1e - 6f ; <nl> - pid - > differentiator = 0 . 0f ; <nl> - pid - > prev_x = 0 . 0f ; <nl> - pid - > tau = params - > get_param_float ( Params : : PARAM_PID_TAU ) ; <nl> - } <nl> - <nl> - <nl> - void Controller : : run_pid ( pid_t * pid , float dt ) <nl> - { <nl> - if ( dt > 0 . 010 | | common_state - > is_disarmed ( ) ) <nl> - { <nl> - / / This means that this is a ' ' stale ' ' controller and needs to be reset . <nl> - / / This would happen if we have been operating in a different mode for a while <nl> - / / and will result in some enormous integrator . <nl> - / / Or , it means we are disarmed and shouldn ' t integrate <nl> - / / Setting dt for this loop will mean that the integrator and dirty derivative <nl> - / / doesn ' t do anything this time but will keep it from exploding . <nl> - dt = 0 . 0 ; <nl> - pid - > differentiator = 0 . 0 ; <nl> - } <nl> - <nl> - / / Calculate Error ( make sure to de - reference pointers ) <nl> - float error = ( * pid - > commanded_x ) - ( * pid - > current_x ) ; <nl> - <nl> - / / Initialize Terms <nl> - float p_term = error * params - > get_param_float ( pid - > kp_param_id ) ; <nl> - float i_term = 0 . 0 ; <nl> - float d_term = 0 . 0 ; <nl> - <nl> - / / If there is a derivative term <nl> - if ( pid - > kd_param_id < Params : : PARAMS_COUNT ) <nl> - { <nl> - / / calculate D term ( use dirty derivative if we don ' t have access to a measurement of the derivative ) <nl> - / / The dirty derivative is a sort of low - pass filtered version of the derivative . <nl> - / / ( Be sure to de - reference pointers ) <nl> - if ( pid - > current_xdot = = NULL ) <nl> - { <nl> - if ( dt > 0 . 0f ) { <nl> - pid - > differentiator = ( 2 . 0f * pid - > tau - dt ) / ( 2 . 0f * pid - > tau + dt ) * pid - > differentiator + 2 . 0f / ( 2 . 0f * pid - > tau + dt ) * ( ( * pid - > current_x ) - pid - > prev_x ) ; <nl> - pid - > prev_x = * pid - > current_x ; <nl> - d_term = params - > get_param_float ( pid - > kd_param_id ) * pid - > differentiator ; <nl> - } <nl> - else <nl> - d_term = 0 ; <nl> - } else <nl> - { <nl> - d_term = params - > get_param_float ( pid - > kd_param_id ) * ( * pid - > current_xdot ) ; <nl> - } <nl> - } <nl> - <nl> - / / If there is an integrator , we are armed , and throttle is high <nl> - / / / TODO : better way to figure out if throttle is high <nl> - if ( ( pid - > ki_param_id < Params : : PARAMS_COUNT ) & & ( common_state - > is_armed ( ) ) & & ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) > 1200 ) ) ) <nl> - { <nl> - if ( params - > get_param_float ( pid - > ki_param_id ) > 0 . 0 ) <nl> - { <nl> - / / integrate <nl> - pid - > integrator + = error * dt ; <nl> - / / calculate I term ( be sure to de - reference pointer to gain ) <nl> - i_term = params - > get_param_float ( pid - > ki_param_id ) * pid - > integrator ; <nl> - } <nl> - } <nl> - <nl> - / / sum three terms <nl> - float u = p_term + i_term - d_term ; <nl> - <nl> - / / Integrator anti - windup <nl> - float u_sat = ( u > pid - > max ) ? pid - > max : ( u < pid - > min ) ? pid - > min : u ; <nl> - if ( u ! = u_sat & & fabs ( i_term ) > fabs ( u - p_term + d_term ) ) <nl> - pid - > integrator = ( u_sat - p_term + d_term ) / params - > get_param_float ( pid - > ki_param_id ) ; <nl> - <nl> - / / Set output <nl> - ( * pid - > output ) = u_sat ; <nl> - <nl> - return ; <nl> - } <nl> - <nl> - void Controller : : run_controller ( ) <nl> - { <nl> - Mux : : control_t & combined_control = mux - > combined_control ( ) ; <nl> - Mixer : : command_t & mixer_command = mixer - > getCommand ( ) ; <nl> - <nl> - if ( prev_time < 0 . 0001f ) <nl> - { <nl> - prev_time = estimator - > state ( ) . now_us * 1e - 6f ; <nl> - return ; <nl> - } <nl> - <nl> - float now = estimator - > state ( ) . now_us * 1e - 6f ; <nl> - float dt = now - prev_time ; <nl> - prev_time = now ; <nl> - <nl> - / / ROLL <nl> - if ( combined_control . x . type = = Mux : : control_type_t : : RATE ) <nl> - run_pid ( & pid_roll_rate , dt ) ; <nl> - else if ( combined_control . x . type = = Mux : : control_type_t : : ANGLE ) <nl> - run_pid ( & pid_roll , dt ) ; <nl> - else / / MOTOR_DIRECT <nl> - mixer_command . x = combined_control . x . value ; <nl> - <nl> - / / PITCH <nl> - if ( combined_control . y . type = = Mux : : control_type_t : : RATE ) <nl> - run_pid ( & pid_pitch_rate , dt ) ; <nl> - else if ( combined_control . y . type = = Mux : : control_type_t : : ANGLE ) <nl> - run_pid ( & pid_pitch , dt ) ; <nl> - else / / MOTOR_DIRECT <nl> - mixer_command . y = combined_control . y . value ; <nl> - <nl> - / / YAW <nl> - if ( combined_control . z . type = = Mux : : control_type_t : : RATE ) <nl> - run_pid ( & pid_yaw_rate , dt ) ; <nl> - else / / MOTOR_DIRECT <nl> - mixer_command . z = combined_control . z . value ; <nl> - <nl> - / / THROTTLE <nl> - / / if ( combined_control . F . type = = ALTITUDE ) <nl> - / / run_pid ( & pid_altitude ) ; <nl> - / / else / / MOTOR_DIRECT <nl> - mixer_command . F = combined_control . F . value ; <nl> - <nl> - comm_link - > notify_controller_updated ( ) ; <nl> - } <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + # include < cstdbool > <nl> + <nl> + # include " mux . hpp " <nl> + # include " param . hpp " <nl> + # include " estimator . hpp " <nl> + # include " mixer . hpp " <nl> + # include " commonstate . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Controller { <nl> + public : <nl> + void run_controller ( ) ; <nl> + void init ( CommonState * _common_state , Board * _board , Mux * _mux , Mixer * _mixer , Estimator * _estimator , Params * _params , CommLink * _comm_link ) ; <nl> + <nl> + private : <nl> + typedef struct <nl> + { <nl> + Params : : param_id_t kp_param_id ; <nl> + Params : : param_id_t ki_param_id ; <nl> + Params : : param_id_t kd_param_id ; <nl> + <nl> + float * current_x ; <nl> + float * current_xdot ; <nl> + float * commanded_x ; <nl> + float * output ; <nl> + <nl> + float max ; <nl> + float min ; <nl> + <nl> + float integrator ; <nl> + float prev_time ; <nl> + float prev_x ; <nl> + float differentiator ; <nl> + float tau ; <nl> + } pid_t ; <nl> + <nl> + pid_t pid_roll ; <nl> + pid_t pid_roll_rate ; <nl> + pid_t pid_pitch ; <nl> + pid_t pid_pitch_rate ; <nl> + pid_t pid_yaw_rate ; <nl> + pid_t pid_altitude ; <nl> + <nl> + Estimator * estimator ; <nl> + CommonState * common_state ; <nl> + Mux * mux ; <nl> + Mixer * mixer ; <nl> + Params * params ; <nl> + Board * board ; <nl> + CommLink * comm_link ; <nl> + <nl> + void init_pid ( pid_t * pid , Params : : param_id_t kp_param_id , Params : : param_id_t ki_param_id , Params : : param_id_t kd_param_id , float * current_x , float * current_xdot , float * commanded_x , float * output , float max , float min ) ; <nl> + void run_pid ( pid_t * pid , float dt ) ; <nl> + <nl> + / / variables used by methods <nl> + float prev_time = 0 . 0f ; / / run_controller <nl> + <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + void Controller : : init ( CommonState * _common_state , Board * _board , Mux * _mux , Mixer * _mixer , Estimator * _estimator , Params * _params , CommLink * _comm_link ) <nl> + { <nl> + estimator = _estimator ; <nl> + mux = _mux ; <nl> + mixer = _mixer ; <nl> + common_state = _common_state ; <nl> + params = _params ; <nl> + board = _board ; <nl> + comm_link = _comm_link ; <nl> + <nl> + Mux : : control_t & combined_control = mux - > combined_control ( ) ; <nl> + Mixer : : command_t & mixer_command = mixer - > getCommand ( ) ; <nl> + <nl> + init_pid ( & pid_roll , <nl> + Params : : PARAM_PID_ROLL_ANGLE_P , <nl> + Params : : PARAM_PID_ROLL_ANGLE_I , <nl> + Params : : PARAM_PID_ROLL_ANGLE_D , <nl> + & _estimator - > state ( ) . euler . x , <nl> + & _estimator - > state ( ) . omega . x , <nl> + & combined_control . x . value , <nl> + & mixer_command . x , <nl> + params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> + - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> + <nl> + init_pid ( & pid_pitch , <nl> + Params : : PARAM_PID_PITCH_ANGLE_P , <nl> + Params : : PARAM_PID_PITCH_ANGLE_I , <nl> + Params : : PARAM_PID_PITCH_ANGLE_D , <nl> + & _estimator - > state ( ) . euler . y , <nl> + & _estimator - > state ( ) . omega . y , <nl> + & combined_control . y . value , <nl> + & mixer_command . y , <nl> + params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> + - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> + <nl> + init_pid ( & pid_roll_rate , <nl> + Params : : PARAM_PID_ROLL_RATE_P , <nl> + Params : : PARAM_PID_ROLL_RATE_I , <nl> + Params : : PARAM_PID_ROLL_RATE_D , <nl> + & _estimator - > state ( ) . omega . x , <nl> + NULL , <nl> + & combined_control . x . value , <nl> + & mixer_command . x , <nl> + params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> + - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> + <nl> + init_pid ( & pid_pitch_rate , <nl> + Params : : PARAM_PID_PITCH_RATE_P , <nl> + Params : : PARAM_PID_PITCH_RATE_I , <nl> + Params : : PARAM_PID_PITCH_RATE_D , <nl> + & _estimator - > state ( ) . omega . y , <nl> + NULL , <nl> + & combined_control . y . value , <nl> + & mixer_command . y , <nl> + params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> + - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> + <nl> + init_pid ( & pid_yaw_rate , <nl> + Params : : PARAM_PID_YAW_RATE_P , <nl> + Params : : PARAM_PID_YAW_RATE_I , <nl> + Params : : PARAM_PID_YAW_RATE_D , <nl> + & _estimator - > state ( ) . omega . z , <nl> + NULL , <nl> + & combined_control . z . value , <nl> + & mixer_command . z , <nl> + params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f , <nl> + - 1 . 0f * params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) / 2 . 0f ) ; <nl> + <nl> + init_pid ( & pid_altitude , <nl> + Params : : PARAM_PID_ALT_P , <nl> + Params : : PARAM_PID_ALT_I , <nl> + Params : : PARAM_PID_ALT_D , <nl> + & _estimator - > state ( ) . altitude , <nl> + NULL , <nl> + & combined_control . F . value , <nl> + & mixer_command . F , <nl> + static_cast < float > ( params - > get_param_int ( Params : : PARAM_MAX_COMMAND ) ) , <nl> + 0 . 0f ) ; <nl> + } <nl> + <nl> + void Controller : : init_pid ( pid_t * pid , Params : : param_id_t kp_param_id , Params : : param_id_t ki_param_id , Params : : param_id_t kd_param_id , float * current_x , float * current_xdot , float * commanded_x , float * output , float max , float min ) <nl> + { <nl> + pid - > kp_param_id = kp_param_id ; <nl> + pid - > ki_param_id = ki_param_id ; <nl> + pid - > kd_param_id = kd_param_id ; <nl> + pid - > current_x = current_x ; <nl> + pid - > current_xdot = current_xdot ; <nl> + pid - > commanded_x = commanded_x ; <nl> + pid - > output = output ; <nl> + pid - > max = max ; <nl> + pid - > min = min ; <nl> + pid - > integrator = 0 . 0f ; <nl> + pid - > prev_time = board - > micros ( ) * 1e - 6f ; <nl> + pid - > differentiator = 0 . 0f ; <nl> + pid - > prev_x = 0 . 0f ; <nl> + pid - > tau = params - > get_param_float ( Params : : PARAM_PID_TAU ) ; <nl> + } <nl> + <nl> + <nl> + void Controller : : run_pid ( pid_t * pid , float dt ) <nl> + { <nl> + if ( dt > 0 . 010 | | common_state - > is_disarmed ( ) ) <nl> + { <nl> + / / This means that this is a ' ' stale ' ' controller and needs to be reset . <nl> + / / This would happen if we have been operating in a different mode for a while <nl> + / / and will result in some enormous integrator . <nl> + / / Or , it means we are disarmed and shouldn ' t integrate <nl> + / / Setting dt for this loop will mean that the integrator and dirty derivative <nl> + / / doesn ' t do anything this time but will keep it from exploding . <nl> + dt = 0 . 0 ; <nl> + pid - > differentiator = 0 . 0 ; <nl> + } <nl> + <nl> + / / Calculate Error ( make sure to de - reference pointers ) <nl> + float error = ( * pid - > commanded_x ) - ( * pid - > current_x ) ; <nl> + <nl> + / / Initialize Terms <nl> + float p_term = error * params - > get_param_float ( pid - > kp_param_id ) ; <nl> + float i_term = 0 . 0 ; <nl> + float d_term = 0 . 0 ; <nl> + <nl> + / / If there is a derivative term <nl> + if ( pid - > kd_param_id < Params : : PARAMS_COUNT ) <nl> + { <nl> + / / calculate D term ( use dirty derivative if we don ' t have access to a measurement of the derivative ) <nl> + / / The dirty derivative is a sort of low - pass filtered version of the derivative . <nl> + / / ( Be sure to de - reference pointers ) <nl> + if ( pid - > current_xdot = = NULL ) <nl> + { <nl> + if ( dt > 0 . 0f ) { <nl> + pid - > differentiator = ( 2 . 0f * pid - > tau - dt ) / ( 2 . 0f * pid - > tau + dt ) * pid - > differentiator + 2 . 0f / ( 2 . 0f * pid - > tau + dt ) * ( ( * pid - > current_x ) - pid - > prev_x ) ; <nl> + pid - > prev_x = * pid - > current_x ; <nl> + d_term = params - > get_param_float ( pid - > kd_param_id ) * pid - > differentiator ; <nl> + } <nl> + else <nl> + d_term = 0 ; <nl> + } else <nl> + { <nl> + d_term = params - > get_param_float ( pid - > kd_param_id ) * ( * pid - > current_xdot ) ; <nl> + } <nl> + } <nl> + <nl> + / / If there is an integrator , we are armed , and throttle is high <nl> + / / / TODO : better way to figure out if throttle is high <nl> + if ( ( pid - > ki_param_id < Params : : PARAMS_COUNT ) & & ( common_state - > is_armed ( ) ) & & ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) > 1200 ) ) ) <nl> + { <nl> + if ( params - > get_param_float ( pid - > ki_param_id ) > 0 . 0 ) <nl> + { <nl> + / / integrate <nl> + pid - > integrator + = error * dt ; <nl> + / / calculate I term ( be sure to de - reference pointer to gain ) <nl> + i_term = params - > get_param_float ( pid - > ki_param_id ) * pid - > integrator ; <nl> + } <nl> + } <nl> + <nl> + / / sum three terms <nl> + float u = p_term + i_term - d_term ; <nl> + <nl> + / / Integrator anti - windup <nl> + float u_sat = ( u > pid - > max ) ? pid - > max : ( u < pid - > min ) ? pid - > min : u ; <nl> + if ( u ! = u_sat & & fabs ( i_term ) > fabs ( u - p_term + d_term ) ) <nl> + pid - > integrator = ( u_sat - p_term + d_term ) / params - > get_param_float ( pid - > ki_param_id ) ; <nl> + <nl> + / / Set output <nl> + ( * pid - > output ) = u_sat ; <nl> + <nl> + return ; <nl> + } <nl> + <nl> + void Controller : : run_controller ( ) <nl> + { <nl> + Mux : : control_t & combined_control = mux - > combined_control ( ) ; <nl> + Mixer : : command_t & mixer_command = mixer - > getCommand ( ) ; <nl> + <nl> + if ( prev_time < 0 . 0001f ) <nl> + { <nl> + prev_time = estimator - > state ( ) . now_us * 1e - 6f ; <nl> + return ; <nl> + } <nl> + <nl> + float now = estimator - > state ( ) . now_us * 1e - 6f ; <nl> + float dt = now - prev_time ; <nl> + prev_time = now ; <nl> + <nl> + / / ROLL <nl> + if ( combined_control . x . type = = Mux : : control_type_t : : RATE ) <nl> + run_pid ( & pid_roll_rate , dt ) ; <nl> + else if ( combined_control . x . type = = Mux : : control_type_t : : ANGLE ) <nl> + run_pid ( & pid_roll , dt ) ; <nl> + else / / MOTOR_DIRECT <nl> + mixer_command . x = combined_control . x . value ; <nl> + <nl> + / / PITCH <nl> + if ( combined_control . y . type = = Mux : : control_type_t : : RATE ) <nl> + run_pid ( & pid_pitch_rate , dt ) ; <nl> + else if ( combined_control . y . type = = Mux : : control_type_t : : ANGLE ) <nl> + run_pid ( & pid_pitch , dt ) ; <nl> + else / / MOTOR_DIRECT <nl> + mixer_command . y = combined_control . y . value ; <nl> + <nl> + / / YAW <nl> + if ( combined_control . z . type = = Mux : : control_type_t : : RATE ) <nl> + run_pid ( & pid_yaw_rate , dt ) ; <nl> + else / / MOTOR_DIRECT <nl> + mixer_command . z = combined_control . z . value ; <nl> + <nl> + / / THROTTLE <nl> + / / if ( combined_control . F . type = = ALTITUDE ) <nl> + / / run_pid ( & pid_altitude ) ; <nl> + / / else / / MOTOR_DIRECT <nl> + mixer_command . F = combined_control . F . value ; <nl> + <nl> + comm_link - > notify_controller_updated ( ) ; <nl> + } <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / dummyboard . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / dummyboard . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / dummyboard . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / dummyboard . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include " board . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class DummyBoard : public Board { <nl> - public : <nl> - virtual void init ( ) override { } <nl> - virtual uint64_t micros ( ) override { return 0 ; } <nl> - virtual uint32_t millis ( ) override { return 0 ; } <nl> - virtual void init_sensors ( uint16_t & acc1G , float & gyro_scale , int boardVersion , const std : : function < void ( void ) > & imu_updated_callback ) override { } <nl> - virtual bool is_sensor_present ( SensorType type ) override { return false ; } <nl> - virtual uint16_t pwmRead ( int16_t channel ) override { return 0 ; } <nl> - virtual void pwmInit ( bool useCPPM , bool usePwmFilter , bool fastPWM , uint32_t motorPwmRate , uint16_t idlePulseUsec ) override { } <nl> - virtual void pwmWriteMotor ( uint8_t index , uint16_t value ) override { } <nl> - virtual void set_led ( uint8_t index , bool is_on ) override { } <nl> - virtual void toggle_led ( uint8_t index ) override { } <nl> - virtual void init_params ( ) override { } <nl> - virtual bool read_params ( ) override { return false ; } <nl> - virtual bool write_params ( bool blink_led ) override { return false ; } <nl> - virtual void init_imu ( uint16_t & acc1G , float & gyroScale , int boardVersion ) override { } <nl> - virtual void read_accel ( int16_t accel_adc [ 3 ] ) override { } <nl> - virtual void read_gyro ( int16_t gyro_adc [ 3 ] ) override { } <nl> - virtual void read_temperature ( int16_t & temp ) override { } <nl> - virtual void read_baro ( float & altitude , float & pressure , float & temperature ) override { } <nl> - virtual void read_diff_pressure ( float & differential_pressure , float & temp , float & velocity ) override { } <nl> - virtual float read_sonar ( ) override { return 0 ; } <nl> - virtual void read_mag ( int16_t mag_adc [ 3 ] ) override { } <nl> - virtual void delay_micros ( uint32_t us ) override { } <nl> - virtual void delay_millis ( uint32_t ms ) override { } <nl> - virtual void system_reset ( bool toBootloader ) { } <nl> - } ; <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include " board . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class DummyBoard : public Board { <nl> + public : <nl> + virtual void init ( ) override { } <nl> + virtual uint64_t micros ( ) override { return 0 ; } <nl> + virtual uint32_t millis ( ) override { return 0 ; } <nl> + virtual void init_sensors ( uint16_t & acc1G , float & gyro_scale , int boardVersion , const std : : function < void ( void ) > & imu_updated_callback ) override { } <nl> + virtual bool is_sensor_present ( SensorType type ) override { return false ; } <nl> + virtual uint16_t pwmRead ( int16_t channel ) override { return 0 ; } <nl> + virtual void pwmInit ( bool useCPPM , bool usePwmFilter , bool fastPWM , uint32_t motorPwmRate , uint16_t idlePulseUsec ) override { } <nl> + virtual void pwmWriteMotor ( uint8_t index , uint16_t value ) override { } <nl> + virtual void set_led ( uint8_t index , bool is_on ) override { } <nl> + virtual void toggle_led ( uint8_t index ) override { } <nl> + virtual void init_params ( ) override { } <nl> + virtual bool read_params ( ) override { return false ; } <nl> + virtual bool write_params ( bool blink_led ) override { return false ; } <nl> + virtual void init_imu ( uint16_t & acc1G , float & gyroScale , int boardVersion ) override { } <nl> + virtual void read_accel ( int16_t accel_adc [ 3 ] ) override { } <nl> + virtual void read_gyro ( int16_t gyro_adc [ 3 ] ) override { } <nl> + virtual void read_temperature ( int16_t & temp ) override { } <nl> + virtual void read_baro ( float & altitude , float & pressure , float & temperature ) override { } <nl> + virtual void read_diff_pressure ( float & differential_pressure , float & temp , float & velocity ) override { } <nl> + virtual float read_sonar ( ) override { return 0 ; } <nl> + virtual void read_mag ( int16_t mag_adc [ 3 ] ) override { } <nl> + virtual void delay_micros ( uint32_t us ) override { } <nl> + virtual void delay_millis ( uint32_t ms ) override { } <nl> + virtual void system_reset ( bool toBootloader ) { } <nl> + } ; <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 90 % <nl> rename from AirLib / include / controllers / rosflight / firmware / dummycommlink . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / dummycommlink . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / dummycommlink . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / dummycommlink . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include " commlink . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class DummyCommLink : public CommLink { <nl> - public : <nl> - virtual void init ( ) override { } <nl> - virtual void update ( ) override { } <nl> - virtual void set_sys_id ( int32_t sys_id ) override { } <nl> - virtual void set_streaming_rate ( uint16_t param_id , int32_t rate ) override { } <nl> - virtual void notify_param_change ( uint16_t param_id , int32_t value ) override { } <nl> - virtual void log_message ( const char * message , uint8_t error_level ) override { } <nl> - virtual void notify_controller_updated ( ) { } <nl> - } ; <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include " commlink . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class DummyCommLink : public CommLink { <nl> + public : <nl> + virtual void init ( ) override { } <nl> + virtual void update ( ) override { } <nl> + virtual void set_sys_id ( int32_t sys_id ) override { } <nl> + virtual void set_streaming_rate ( uint16_t param_id , int32_t rate ) override { } <nl> + virtual void notify_param_change ( uint16_t param_id , int32_t value ) override { } <nl> + virtual void log_message ( const char * message , uint8_t error_level ) override { } <nl> + virtual void notify_controller_updated ( ) { } <nl> + } ; <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / estimator . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / estimator . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / estimator . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / estimator . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - # include < cstdbool > <nl> - # include " turbotrig / turbotrig . h " <nl> - # include " turbotrig / turbovec . h " <nl> - # include " param . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Estimator { <nl> - public : <nl> - struct state_t <nl> - { <nl> - quaternion_t q ; <nl> - vector_t euler ; <nl> - vector_t omega ; <nl> - <nl> - / / float p ; <nl> - / / float q ; <nl> - / / float r ; <nl> - <nl> - / / float phi ; <nl> - / / float theta ; <nl> - / / float psi ; <nl> - <nl> - float altitude ; <nl> - uint64_t now_us ; <nl> - <nl> - } ; <nl> - <nl> - public : <nl> - void init ( Params * _params , bool use_matrix_exponential , bool use_quadratic_integration , bool use_accelerometer ) ; <nl> - void reset_state ( ) ; <nl> - void reset_adaptive_bias ( ) ; <nl> - void run_estimator ( const vector_t & accel , const vector_t & gyro , const uint64_t & imu_time ) ; <nl> - state_t & state ( ) { return _current_state ; } ; <nl> - <nl> - private : <nl> - void run_LPF ( const vector_t & accel , const vector_t & gyro ) ; <nl> - <nl> - <nl> - private : <nl> - state_t _current_state ; <nl> - Params * params ; <nl> - Board * board ; <nl> - <nl> - vector_t _adaptive_gyro_bias ; <nl> - <nl> - vector_t w1 ; <nl> - vector_t w2 ; <nl> - vector_t wbar ; <nl> - vector_t wfinal ; <nl> - vector_t w_acc ; <nl> - const vector_t g = { 0 . 0f , 0 . 0f , - 1 . 0f } ; / / ' static constexpr ' here results in link error . <nl> - vector_t b ; <nl> - quaternion_t q_tilde ; <nl> - quaternion_t q_hat ; <nl> - uint64_t last_time ; <nl> - <nl> - bool mat_exp ; <nl> - bool quad_int ; <nl> - bool use_acc ; <nl> - <nl> - vector_t _accel_LPF ; <nl> - vector_t _gyro_LPF ; <nl> - <nl> - float kp = 0 , ki = 0 ; / / run_estimator <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - <nl> - void Estimator : : init ( Params * _params , bool use_matrix_exponential , bool use_quadratic_integration , bool use_accelerometer ) <nl> - { <nl> - params = _params ; <nl> - <nl> - mat_exp = use_matrix_exponential ; <nl> - quad_int = use_quadratic_integration ; <nl> - use_acc = use_accelerometer ; <nl> - <nl> - last_time = 0 ; <nl> - <nl> - reset_state ( ) ; <nl> - } <nl> - <nl> - void Estimator : : reset_state ( ) <nl> - { <nl> - _current_state . q . w = 1 . 0f ; <nl> - _current_state . q . x = 0 . 0f ; <nl> - _current_state . q . y = 0 . 0f ; <nl> - _current_state . q . z = 0 . 0f ; <nl> - _current_state . omega . x = 0 . 0f ; <nl> - _current_state . omega . y = 0 . 0f ; <nl> - _current_state . omega . z = 0 . 0f ; <nl> - _current_state . euler . x = 0 . 0f ; <nl> - _current_state . euler . y = 0 . 0f ; <nl> - _current_state . euler . z = 0 . 0f ; <nl> - <nl> - q_hat . w = 1 . 0f ; <nl> - q_hat . x = 0 . 0f ; <nl> - q_hat . y = 0 . 0f ; <nl> - q_hat . z = 0 . 0f ; <nl> - <nl> - w1 . x = 0 . 0f ; <nl> - w1 . y = 0 . 0f ; <nl> - w1 . z = 0 . 0f ; <nl> - <nl> - w2 . x = 0 . 0f ; <nl> - w2 . y = 0 . 0f ; <nl> - w2 . z = 0 . 0f ; <nl> - <nl> - b . x = 0 . 0f ; <nl> - b . y = 0 . 0f ; <nl> - b . z = 0 . 0f ; <nl> - <nl> - w_acc . x = 0 . 0f ; <nl> - w_acc . y = 0 . 0f ; <nl> - w_acc . z = 0 . 0f ; <nl> - <nl> - q_tilde . w = 1 . 0f ; <nl> - q_tilde . x = 0 . 0f ; <nl> - q_tilde . y = 0 . 0f ; <nl> - q_tilde . z = 0 . 0f ; <nl> - <nl> - _accel_LPF . x = 0 ; <nl> - _accel_LPF . y = 0 ; <nl> - _accel_LPF . z = - 9 . 80665f ; <nl> - <nl> - _gyro_LPF . x = 0 ; <nl> - _gyro_LPF . y = 0 ; <nl> - _gyro_LPF . z = 0 ; <nl> - } <nl> - <nl> - void Estimator : : reset_adaptive_bias ( ) <nl> - { <nl> - b . x = 0 ; <nl> - b . y = 0 ; <nl> - b . z = 0 ; <nl> - } <nl> - <nl> - void Estimator : : run_LPF ( const vector_t & accel , const vector_t & gyro ) <nl> - { <nl> - float alpha_acc = params - > get_param_float ( Params : : PARAM_ACC_ALPHA ) ; <nl> - _accel_LPF . x = ( 1 . 0f - alpha_acc ) * accel . x + alpha_acc * _accel_LPF . x ; <nl> - _accel_LPF . y = ( 1 . 0f - alpha_acc ) * accel . y + alpha_acc * _accel_LPF . y ; <nl> - _accel_LPF . z = ( 1 . 0f - alpha_acc ) * accel . z + alpha_acc * _accel_LPF . z ; <nl> - <nl> - float alpha_gyro = params - > get_param_float ( Params : : PARAM_GYRO_ALPHA ) ; <nl> - _gyro_LPF . x = ( 1 . 0f - alpha_gyro ) * gyro . x + alpha_gyro * _gyro_LPF . x ; <nl> - _gyro_LPF . y = ( 1 . 0f - alpha_gyro ) * gyro . y + alpha_gyro * _gyro_LPF . y ; <nl> - _gyro_LPF . z = ( 1 . 0f - alpha_gyro ) * gyro . z + alpha_gyro * _gyro_LPF . z ; <nl> - } <nl> - <nl> - <nl> - void Estimator : : run_estimator ( const vector_t & accel , const vector_t & gyro , const uint64_t & imu_time ) <nl> - { <nl> - _current_state . now_us = imu_time ; <nl> - if ( last_time = = 0 | | _current_state . now_us < = last_time ) <nl> - { <nl> - last_time = _current_state . now_us ; <nl> - return ; <nl> - } <nl> - <nl> - float dt = ( _current_state . now_us - last_time ) * 1e - 6f ; <nl> - last_time = _current_state . now_us ; <nl> - <nl> - / / Crank up the gains for the first few seconds for quick convergence <nl> - if ( imu_time < ( uint64_t ) params - > get_param_int ( Params : : PARAM_INIT_TIME ) * 1000 ) <nl> - { <nl> - kp = params - > get_param_float ( Params : : PARAM_FILTER_KP ) * 10 . 0f ; <nl> - ki = params - > get_param_float ( Params : : PARAM_FILTER_KI ) * 10 . 0f ; <nl> - } <nl> - else <nl> - { <nl> - kp = params - > get_param_float ( Params : : PARAM_FILTER_KP ) ; <nl> - ki = params - > get_param_float ( Params : : PARAM_FILTER_KI ) ; <nl> - } <nl> - <nl> - / / Run LPF to reject a lot of noise <nl> - run_LPF ( accel , gyro ) ; <nl> - <nl> - / / add in accelerometer <nl> - float a_sqrd_norm = _accel_LPF . x * _accel_LPF . x + _accel_LPF . y * _accel_LPF . y + _accel_LPF . z * _accel_LPF . z ; <nl> - <nl> - if ( use_acc & & a_sqrd_norm < 1 . 15f * 1 . 15f * 9 . 80665f * 9 . 80665f & & a_sqrd_norm > 0 . 85f * 0 . 85f * 9 . 80665f * 9 . 80665f ) <nl> - { <nl> - / / Get error estimated by accelerometer measurement <nl> - vector_t a = vector_normalize ( _accel_LPF ) ; <nl> - / / Get the quaternion from accelerometer ( low - frequency measure q ) <nl> - / / ( Not in either paper ) <nl> - quaternion_t q_acc_inv = quaternion_inverse ( quat_from_two_vectors ( a , g ) ) ; <nl> - / / Get the error quaternion between observer and low - freq q <nl> - / / Below Eq . 45 Mahoney Paper <nl> - q_tilde = quaternion_multiply ( q_acc_inv , q_hat ) ; <nl> - / / Correction Term of Eq . 47a and 47b Mahoney Paper <nl> - / / w_acc = 2 * s_tilde * v_tilde <nl> - w_acc . x = - 2 . 0f * q_tilde . w * q_tilde . x ; <nl> - w_acc . y = - 2 . 0f * q_tilde . w * q_tilde . y ; <nl> - w_acc . z = 0 . 0f ; / / Don ' t correct z , because it ' s unobservable from the accelerometer <nl> - <nl> - / / integrate biases from accelerometer feedback <nl> - / / ( eq 47b Mahoney Paper , using correction term w_acc found above ) <nl> - b . x - = ki * w_acc . x * dt ; <nl> - b . y - = ki * w_acc . y * dt ; <nl> - b . z = 0 . 0 ; / / Don ' t integrate z bias , because it ' s unobservable <nl> - } <nl> - else <nl> - { <nl> - w_acc . x = 0 . 0f ; <nl> - w_acc . y = 0 . 0f ; <nl> - w_acc . z = 0 . 0f ; <nl> - } <nl> - <nl> - / / Pull out Gyro measurements <nl> - if ( quad_int ) <nl> - { <nl> - / / Quadratic Integration ( Eq . 14 Casey Paper ) <nl> - / / this integration step adds 12 us on the STM32F10x chips <nl> - wbar = vector_add ( vector_add ( scalar_multiply ( - 1 . 0f / 12 . 0f , w2 ) , scalar_multiply ( 8 . 0f / 12 . 0f , w1 ) ) , <nl> - scalar_multiply ( 5 . 0f / 12 . 0f , _gyro_LPF ) ) ; <nl> - w2 = w1 ; <nl> - w1 = _gyro_LPF ; <nl> - } <nl> - else <nl> - { <nl> - wbar = _gyro_LPF ; <nl> - } <nl> - <nl> - / / Build the composite omega vector for kinematic propagation <nl> - / / This the stuff inside the p function in eq . 47a - Mahoney Paper <nl> - wfinal = vector_add ( vector_sub ( wbar , b ) , scalar_multiply ( kp , w_acc ) ) ; <nl> - <nl> - / / Propagate Dynamics ( only if we ' ve moved ) <nl> - float sqrd_norm_w = sqrd_norm ( wfinal ) ; <nl> - if ( sqrd_norm_w > 0 . 0f ) <nl> - { <nl> - float p = wfinal . x ; <nl> - float q = wfinal . y ; <nl> - float r = wfinal . z ; <nl> - <nl> - if ( mat_exp ) <nl> - { <nl> - / / Matrix Exponential Approximation ( From Attitude Representation and Kinematic <nl> - / / Propagation for Low - Cost UAVs by Robert T . Casey ) <nl> - / / ( Eq . 12 Casey Paper ) <nl> - / / This adds 90 us on STM32F10x chips <nl> - float norm_w = sqrtf ( sqrd_norm_w ) ; <nl> - quaternion_t qhat_np1 ; <nl> - float t1 = cosf ( ( norm_w * dt ) / 2 . 0f ) ; <nl> - float t2 = 1 . 0f / norm_w * sinf ( ( norm_w * dt ) / 2 . 0f ) ; <nl> - qhat_np1 . w = t1 * q_hat . w + t2 * ( - p * q_hat . x - q * q_hat . y - r * q_hat . z ) ; <nl> - qhat_np1 . x = t1 * q_hat . x + t2 * ( p * q_hat . w + r * q_hat . y - q * q_hat . z ) ; <nl> - qhat_np1 . y = t1 * q_hat . y + t2 * ( q * q_hat . w - r * q_hat . x + p * q_hat . z ) ; <nl> - qhat_np1 . z = t1 * q_hat . z + t2 * ( r * q_hat . w + q * q_hat . x - p * q_hat . y ) ; <nl> - q_hat = quaternion_normalize ( qhat_np1 ) ; <nl> - } <nl> - else <nl> - { <nl> - / / Euler Integration <nl> - / / ( Eq . 47a Mahoney Paper ) , but this is pretty straight - forward <nl> - quaternion_t qdot = { 0 . 5f * ( - p * q_hat . x - q * q_hat . y - r * q_hat . z ) , <nl> - 0 . 5f * ( p * q_hat . w + r * q_hat . y - q * q_hat . z ) , <nl> - 0 . 5f * ( q * q_hat . w - r * q_hat . x + p * q_hat . z ) , <nl> - 0 . 5f * ( r * q_hat . w + q * q_hat . x - p * q_hat . y ) <nl> - } ; <nl> - q_hat . w + = qdot . w * dt ; <nl> - q_hat . x + = qdot . x * dt ; <nl> - q_hat . y + = qdot . y * dt ; <nl> - q_hat . z + = qdot . z * dt ; <nl> - q_hat = quaternion_normalize ( q_hat ) ; <nl> - } <nl> - } <nl> - <nl> - / / Save attitude estimate <nl> - _current_state . q = q_hat ; <nl> - <nl> - / / Extract Euler Angles for controller <nl> - euler_from_quat ( _current_state . q , & _current_state . euler . x , & _current_state . euler . y , & _current_state . euler . z ) ; <nl> - <nl> - / / Save off adjust gyro measurements with estimated biases for control <nl> - _current_state . omega = vector_sub ( _gyro_LPF , b ) ; <nl> - } <nl> - <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + # include < cstdbool > <nl> + # include " turbotrig / turbotrig . h " <nl> + # include " turbotrig / turbovec . h " <nl> + # include " param . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Estimator { <nl> + public : <nl> + struct state_t <nl> + { <nl> + quaternion_t q ; <nl> + vector_t euler ; <nl> + vector_t omega ; <nl> + <nl> + / / float p ; <nl> + / / float q ; <nl> + / / float r ; <nl> + <nl> + / / float phi ; <nl> + / / float theta ; <nl> + / / float psi ; <nl> + <nl> + float altitude ; <nl> + uint64_t now_us ; <nl> + <nl> + } ; <nl> + <nl> + public : <nl> + void init ( Params * _params , bool use_matrix_exponential , bool use_quadratic_integration , bool use_accelerometer ) ; <nl> + void reset_state ( ) ; <nl> + void reset_adaptive_bias ( ) ; <nl> + void run_estimator ( const vector_t & accel , const vector_t & gyro , const uint64_t & imu_time ) ; <nl> + state_t & state ( ) { return _current_state ; } ; <nl> + <nl> + private : <nl> + void run_LPF ( const vector_t & accel , const vector_t & gyro ) ; <nl> + <nl> + <nl> + private : <nl> + state_t _current_state ; <nl> + Params * params ; <nl> + Board * board ; <nl> + <nl> + vector_t _adaptive_gyro_bias ; <nl> + <nl> + vector_t w1 ; <nl> + vector_t w2 ; <nl> + vector_t wbar ; <nl> + vector_t wfinal ; <nl> + vector_t w_acc ; <nl> + const vector_t g = { 0 . 0f , 0 . 0f , - 1 . 0f } ; / / ' static constexpr ' here results in link error . <nl> + vector_t b ; <nl> + quaternion_t q_tilde ; <nl> + quaternion_t q_hat ; <nl> + uint64_t last_time ; <nl> + <nl> + bool mat_exp ; <nl> + bool quad_int ; <nl> + bool use_acc ; <nl> + <nl> + vector_t _accel_LPF ; <nl> + vector_t _gyro_LPF ; <nl> + <nl> + float kp = 0 , ki = 0 ; / / run_estimator <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + <nl> + void Estimator : : init ( Params * _params , bool use_matrix_exponential , bool use_quadratic_integration , bool use_accelerometer ) <nl> + { <nl> + params = _params ; <nl> + <nl> + mat_exp = use_matrix_exponential ; <nl> + quad_int = use_quadratic_integration ; <nl> + use_acc = use_accelerometer ; <nl> + <nl> + last_time = 0 ; <nl> + <nl> + reset_state ( ) ; <nl> + } <nl> + <nl> + void Estimator : : reset_state ( ) <nl> + { <nl> + _current_state . q . w = 1 . 0f ; <nl> + _current_state . q . x = 0 . 0f ; <nl> + _current_state . q . y = 0 . 0f ; <nl> + _current_state . q . z = 0 . 0f ; <nl> + _current_state . omega . x = 0 . 0f ; <nl> + _current_state . omega . y = 0 . 0f ; <nl> + _current_state . omega . z = 0 . 0f ; <nl> + _current_state . euler . x = 0 . 0f ; <nl> + _current_state . euler . y = 0 . 0f ; <nl> + _current_state . euler . z = 0 . 0f ; <nl> + <nl> + q_hat . w = 1 . 0f ; <nl> + q_hat . x = 0 . 0f ; <nl> + q_hat . y = 0 . 0f ; <nl> + q_hat . z = 0 . 0f ; <nl> + <nl> + w1 . x = 0 . 0f ; <nl> + w1 . y = 0 . 0f ; <nl> + w1 . z = 0 . 0f ; <nl> + <nl> + w2 . x = 0 . 0f ; <nl> + w2 . y = 0 . 0f ; <nl> + w2 . z = 0 . 0f ; <nl> + <nl> + b . x = 0 . 0f ; <nl> + b . y = 0 . 0f ; <nl> + b . z = 0 . 0f ; <nl> + <nl> + w_acc . x = 0 . 0f ; <nl> + w_acc . y = 0 . 0f ; <nl> + w_acc . z = 0 . 0f ; <nl> + <nl> + q_tilde . w = 1 . 0f ; <nl> + q_tilde . x = 0 . 0f ; <nl> + q_tilde . y = 0 . 0f ; <nl> + q_tilde . z = 0 . 0f ; <nl> + <nl> + _accel_LPF . x = 0 ; <nl> + _accel_LPF . y = 0 ; <nl> + _accel_LPF . z = - 9 . 80665f ; <nl> + <nl> + _gyro_LPF . x = 0 ; <nl> + _gyro_LPF . y = 0 ; <nl> + _gyro_LPF . z = 0 ; <nl> + } <nl> + <nl> + void Estimator : : reset_adaptive_bias ( ) <nl> + { <nl> + b . x = 0 ; <nl> + b . y = 0 ; <nl> + b . z = 0 ; <nl> + } <nl> + <nl> + void Estimator : : run_LPF ( const vector_t & accel , const vector_t & gyro ) <nl> + { <nl> + float alpha_acc = params - > get_param_float ( Params : : PARAM_ACC_ALPHA ) ; <nl> + _accel_LPF . x = ( 1 . 0f - alpha_acc ) * accel . x + alpha_acc * _accel_LPF . x ; <nl> + _accel_LPF . y = ( 1 . 0f - alpha_acc ) * accel . y + alpha_acc * _accel_LPF . y ; <nl> + _accel_LPF . z = ( 1 . 0f - alpha_acc ) * accel . z + alpha_acc * _accel_LPF . z ; <nl> + <nl> + float alpha_gyro = params - > get_param_float ( Params : : PARAM_GYRO_ALPHA ) ; <nl> + _gyro_LPF . x = ( 1 . 0f - alpha_gyro ) * gyro . x + alpha_gyro * _gyro_LPF . x ; <nl> + _gyro_LPF . y = ( 1 . 0f - alpha_gyro ) * gyro . y + alpha_gyro * _gyro_LPF . y ; <nl> + _gyro_LPF . z = ( 1 . 0f - alpha_gyro ) * gyro . z + alpha_gyro * _gyro_LPF . z ; <nl> + } <nl> + <nl> + <nl> + void Estimator : : run_estimator ( const vector_t & accel , const vector_t & gyro , const uint64_t & imu_time ) <nl> + { <nl> + _current_state . now_us = imu_time ; <nl> + if ( last_time = = 0 | | _current_state . now_us < = last_time ) <nl> + { <nl> + last_time = _current_state . now_us ; <nl> + return ; <nl> + } <nl> + <nl> + float dt = ( _current_state . now_us - last_time ) * 1e - 6f ; <nl> + last_time = _current_state . now_us ; <nl> + <nl> + / / Crank up the gains for the first few seconds for quick convergence <nl> + if ( imu_time < ( uint64_t ) params - > get_param_int ( Params : : PARAM_INIT_TIME ) * 1000 ) <nl> + { <nl> + kp = params - > get_param_float ( Params : : PARAM_FILTER_KP ) * 10 . 0f ; <nl> + ki = params - > get_param_float ( Params : : PARAM_FILTER_KI ) * 10 . 0f ; <nl> + } <nl> + else <nl> + { <nl> + kp = params - > get_param_float ( Params : : PARAM_FILTER_KP ) ; <nl> + ki = params - > get_param_float ( Params : : PARAM_FILTER_KI ) ; <nl> + } <nl> + <nl> + / / Run LPF to reject a lot of noise <nl> + run_LPF ( accel , gyro ) ; <nl> + <nl> + / / add in accelerometer <nl> + float a_sqrd_norm = _accel_LPF . x * _accel_LPF . x + _accel_LPF . y * _accel_LPF . y + _accel_LPF . z * _accel_LPF . z ; <nl> + <nl> + if ( use_acc & & a_sqrd_norm < 1 . 15f * 1 . 15f * 9 . 80665f * 9 . 80665f & & a_sqrd_norm > 0 . 85f * 0 . 85f * 9 . 80665f * 9 . 80665f ) <nl> + { <nl> + / / Get error estimated by accelerometer measurement <nl> + vector_t a = vector_normalize ( _accel_LPF ) ; <nl> + / / Get the quaternion from accelerometer ( low - frequency measure q ) <nl> + / / ( Not in either paper ) <nl> + quaternion_t q_acc_inv = quaternion_inverse ( quat_from_two_vectors ( a , g ) ) ; <nl> + / / Get the error quaternion between observer and low - freq q <nl> + / / Below Eq . 45 Mahoney Paper <nl> + q_tilde = quaternion_multiply ( q_acc_inv , q_hat ) ; <nl> + / / Correction Term of Eq . 47a and 47b Mahoney Paper <nl> + / / w_acc = 2 * s_tilde * v_tilde <nl> + w_acc . x = - 2 . 0f * q_tilde . w * q_tilde . x ; <nl> + w_acc . y = - 2 . 0f * q_tilde . w * q_tilde . y ; <nl> + w_acc . z = 0 . 0f ; / / Don ' t correct z , because it ' s unobservable from the accelerometer <nl> + <nl> + / / integrate biases from accelerometer feedback <nl> + / / ( eq 47b Mahoney Paper , using correction term w_acc found above ) <nl> + b . x - = ki * w_acc . x * dt ; <nl> + b . y - = ki * w_acc . y * dt ; <nl> + b . z = 0 . 0 ; / / Don ' t integrate z bias , because it ' s unobservable <nl> + } <nl> + else <nl> + { <nl> + w_acc . x = 0 . 0f ; <nl> + w_acc . y = 0 . 0f ; <nl> + w_acc . z = 0 . 0f ; <nl> + } <nl> + <nl> + / / Pull out Gyro measurements <nl> + if ( quad_int ) <nl> + { <nl> + / / Quadratic Integration ( Eq . 14 Casey Paper ) <nl> + / / this integration step adds 12 us on the STM32F10x chips <nl> + wbar = vector_add ( vector_add ( scalar_multiply ( - 1 . 0f / 12 . 0f , w2 ) , scalar_multiply ( 8 . 0f / 12 . 0f , w1 ) ) , <nl> + scalar_multiply ( 5 . 0f / 12 . 0f , _gyro_LPF ) ) ; <nl> + w2 = w1 ; <nl> + w1 = _gyro_LPF ; <nl> + } <nl> + else <nl> + { <nl> + wbar = _gyro_LPF ; <nl> + } <nl> + <nl> + / / Build the composite omega vector for kinematic propagation <nl> + / / This the stuff inside the p function in eq . 47a - Mahoney Paper <nl> + wfinal = vector_add ( vector_sub ( wbar , b ) , scalar_multiply ( kp , w_acc ) ) ; <nl> + <nl> + / / Propagate Dynamics ( only if we ' ve moved ) <nl> + float sqrd_norm_w = sqrd_norm ( wfinal ) ; <nl> + if ( sqrd_norm_w > 0 . 0f ) <nl> + { <nl> + float p = wfinal . x ; <nl> + float q = wfinal . y ; <nl> + float r = wfinal . z ; <nl> + <nl> + if ( mat_exp ) <nl> + { <nl> + / / Matrix Exponential Approximation ( From Attitude Representation and Kinematic <nl> + / / Propagation for Low - Cost UAVs by Robert T . Casey ) <nl> + / / ( Eq . 12 Casey Paper ) <nl> + / / This adds 90 us on STM32F10x chips <nl> + float norm_w = sqrtf ( sqrd_norm_w ) ; <nl> + quaternion_t qhat_np1 ; <nl> + float t1 = cosf ( ( norm_w * dt ) / 2 . 0f ) ; <nl> + float t2 = 1 . 0f / norm_w * sinf ( ( norm_w * dt ) / 2 . 0f ) ; <nl> + qhat_np1 . w = t1 * q_hat . w + t2 * ( - p * q_hat . x - q * q_hat . y - r * q_hat . z ) ; <nl> + qhat_np1 . x = t1 * q_hat . x + t2 * ( p * q_hat . w + r * q_hat . y - q * q_hat . z ) ; <nl> + qhat_np1 . y = t1 * q_hat . y + t2 * ( q * q_hat . w - r * q_hat . x + p * q_hat . z ) ; <nl> + qhat_np1 . z = t1 * q_hat . z + t2 * ( r * q_hat . w + q * q_hat . x - p * q_hat . y ) ; <nl> + q_hat = quaternion_normalize ( qhat_np1 ) ; <nl> + } <nl> + else <nl> + { <nl> + / / Euler Integration <nl> + / / ( Eq . 47a Mahoney Paper ) , but this is pretty straight - forward <nl> + quaternion_t qdot = { 0 . 5f * ( - p * q_hat . x - q * q_hat . y - r * q_hat . z ) , <nl> + 0 . 5f * ( p * q_hat . w + r * q_hat . y - q * q_hat . z ) , <nl> + 0 . 5f * ( q * q_hat . w - r * q_hat . x + p * q_hat . z ) , <nl> + 0 . 5f * ( r * q_hat . w + q * q_hat . x - p * q_hat . y ) <nl> + } ; <nl> + q_hat . w + = qdot . w * dt ; <nl> + q_hat . x + = qdot . x * dt ; <nl> + q_hat . y + = qdot . y * dt ; <nl> + q_hat . z + = qdot . z * dt ; <nl> + q_hat = quaternion_normalize ( q_hat ) ; <nl> + } <nl> + } <nl> + <nl> + / / Save attitude estimate <nl> + _current_state . q = q_hat ; <nl> + <nl> + / / Extract Euler Angles for controller <nl> + euler_from_quat ( _current_state . q , & _current_state . euler . x , & _current_state . euler . y , & _current_state . euler . z ) ; <nl> + <nl> + / / Save off adjust gyro measurements with estimated biases for control <nl> + _current_state . omega = vector_sub ( _gyro_LPF , b ) ; <nl> + } <nl> + <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 95 % <nl> rename from AirLib / include / controllers / rosflight / firmware / firmware . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / firmware . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / firmware . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / firmware . hpp <nl> <nl> - # pragma once <nl> - <nl> - # if defined ( _MSC_VER ) <nl> - __pragma ( warning ( push ) ) <nl> - __pragma ( warning ( disable : 4268 ) ) <nl> - # endif <nl> - <nl> - # include " estimator . hpp " <nl> - # include " mode . hpp " <nl> - # include " param . hpp " <nl> - # include " sensors . hpp " <nl> - # include " controller . hpp " <nl> - # include " mixer . hpp " <nl> - # include " rc . hpp " <nl> - # include " board . hpp " <nl> - # include " commlink . hpp " <nl> - # include " commonstate . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Firmware { <nl> - public : <nl> - Firmware ( Board * _board , CommLink * _comm_link ) ; <nl> - <nl> - void setup ( ) ; <nl> - void loop ( ) ; <nl> - <nl> - / / getters <nl> - Board * get_board ( ) { return board ; } <nl> - CommLink * get_commLink ( ) { return comm_link ; } <nl> - Estimator * get_estimator ( ) { return & estimator ; } <nl> - Sensors * get_sensors ( ) { return & sensors ; } <nl> - Mux * get_mux ( ) { return & mux ; } <nl> - Mixer * get_mixer ( ) { return & mixer ; } <nl> - Controller * get_controller ( ) { return & controller ; } <nl> - RC * get_rc ( ) { return & rc ; } <nl> - Mode * get_mode ( ) { return & mode ; } <nl> - <nl> - private : <nl> - / / params and shared state <nl> - Params params ; <nl> - CommonState common_state ; <nl> - <nl> - / / objects we use <nl> - Board * board ; <nl> - CommLink * comm_link ; <nl> - Estimator estimator ; <nl> - Sensors sensors ; <nl> - Mux mux ; <nl> - Mixer mixer ; <nl> - Controller controller ; <nl> - RC rc ; <nl> - Mode mode ; <nl> - <nl> - / / variables to real IMU <nl> - vector_t accel , gyro ; <nl> - uint64_t imu_time ; <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - Firmware : : Firmware ( Board * _board , CommLink * _comm_link ) <nl> - : board ( _board ) , comm_link ( _comm_link ) <nl> - { <nl> - } <nl> - <nl> - void Firmware : : setup ( ) <nl> - { <nl> - board - > init ( ) ; <nl> - <nl> - / / initialize parameters source such as EPROM <nl> - params . init ( board , comm_link ) ; <nl> - <nl> - / / Initialize communication stack such as MavLink <nl> - comm_link - > init ( ) ; <nl> - <nl> - <nl> - / / Initialize Estimator <nl> - / / mat_exp < - greater accuracy , but adds ~ 90 us <nl> - / / quadratic_integration < - some additional accuracy , adds ~ 20 us <nl> - / / accelerometer correction < - if using angle mode , this is required , adds ~ 70 us <nl> - estimator . init ( & params , false , false , true ) ; <nl> - <nl> - / / Initialize Sensors <nl> - sensors . init ( & common_state , board , & estimator , & params , comm_link ) ; <nl> - <nl> - mux . init ( & common_state , board , & params ) ; <nl> - <nl> - / / Initialize Motor Mixing <nl> - mixer . init ( & common_state , board , & params ) ; <nl> - <nl> - controller . init ( & common_state , board , & mux , & mixer , & estimator , & params , comm_link ) ; <nl> - <nl> - rc . init ( & common_state , board , & mux , & params , comm_link ) ; <nl> - <nl> - mode . init ( board , comm_link , & common_state , & sensors , & rc , & params ) ; <nl> - <nl> - comm_link - > log_message ( " ROSFlight firmware initialized " , 0 ) ; <nl> - } <nl> - <nl> - void Firmware : : loop ( ) <nl> - { <nl> - / * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * Control Loop * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * / <nl> - if ( sensors . update_sensors ( ) ) / / 595 | 591 | 590 us <nl> - { <nl> - / / If I have new IMU data , then perform control <nl> - sensors . get_imu_measurements ( accel , gyro , imu_time ) ; <nl> - estimator . run_estimator ( accel , gyro , imu_time ) ; / / 212 | 195 us ( acc and gyro only , not exp propagation no quadratic integration ) <nl> - controller . run_controller ( ) ; / / 278 | 271 <nl> - mixer . mix_output ( ) ; / / 16 | 13 us <nl> - } <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * Post - Process * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * / <nl> - / / Let communication stack send and recieve messages <nl> - comm_link - > update ( ) ; / / 165 | 27 | 2 <nl> - <nl> - / / update the armed_states , an internal timer runs this at a fixed rate <nl> - mode . check_mode ( board - > micros ( ) ) ; / / 108 | 1 | 1 <nl> - <nl> - / / get RC , an internal timer runs this every 20 ms ( 50 Hz ) <nl> - rc . receive_rc ( board - > micros ( ) ) ; / / 42 | 2 | 1 <nl> - <nl> - / / update commands ( internal logic tells whether or not we should do anything or not ) <nl> - mux . mux_inputs ( ) ; / / 6 | 1 | 1 <nl> - } <nl> - <nl> - <nl> - <nl> - } / / namespace <nl> - <nl> - <nl> - # if defined ( _MSC_VER ) <nl> - __pragma ( warning ( pop ) ) <nl> - # endif <nl> + # pragma once <nl> + <nl> + # if defined ( _MSC_VER ) <nl> + __pragma ( warning ( push ) ) <nl> + __pragma ( warning ( disable : 4268 ) ) <nl> + # endif <nl> + <nl> + # include " estimator . hpp " <nl> + # include " mode . hpp " <nl> + # include " param . hpp " <nl> + # include " sensors . hpp " <nl> + # include " controller . hpp " <nl> + # include " mixer . hpp " <nl> + # include " rc . hpp " <nl> + # include " board . hpp " <nl> + # include " commlink . hpp " <nl> + # include " commonstate . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Firmware { <nl> + public : <nl> + Firmware ( Board * _board , CommLink * _comm_link ) ; <nl> + <nl> + void setup ( ) ; <nl> + void loop ( ) ; <nl> + <nl> + / / getters <nl> + Board * get_board ( ) { return board ; } <nl> + CommLink * get_commLink ( ) { return comm_link ; } <nl> + Estimator * get_estimator ( ) { return & estimator ; } <nl> + Sensors * get_sensors ( ) { return & sensors ; } <nl> + Mux * get_mux ( ) { return & mux ; } <nl> + Mixer * get_mixer ( ) { return & mixer ; } <nl> + Controller * get_controller ( ) { return & controller ; } <nl> + RC * get_rc ( ) { return & rc ; } <nl> + Mode * get_mode ( ) { return & mode ; } <nl> + <nl> + private : <nl> + / / params and shared state <nl> + Params params ; <nl> + CommonState common_state ; <nl> + <nl> + / / objects we use <nl> + Board * board ; <nl> + CommLink * comm_link ; <nl> + Estimator estimator ; <nl> + Sensors sensors ; <nl> + Mux mux ; <nl> + Mixer mixer ; <nl> + Controller controller ; <nl> + RC rc ; <nl> + Mode mode ; <nl> + <nl> + / / variables to real IMU <nl> + vector_t accel , gyro ; <nl> + uint64_t imu_time ; <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + Firmware : : Firmware ( Board * _board , CommLink * _comm_link ) <nl> + : board ( _board ) , comm_link ( _comm_link ) <nl> + { <nl> + } <nl> + <nl> + void Firmware : : setup ( ) <nl> + { <nl> + board - > init ( ) ; <nl> + <nl> + / / initialize parameters source such as EPROM <nl> + params . init ( board , comm_link ) ; <nl> + <nl> + / / Initialize communication stack such as MavLink <nl> + comm_link - > init ( ) ; <nl> + <nl> + <nl> + / / Initialize Estimator <nl> + / / mat_exp < - greater accuracy , but adds ~ 90 us <nl> + / / quadratic_integration < - some additional accuracy , adds ~ 20 us <nl> + / / accelerometer correction < - if using angle mode , this is required , adds ~ 70 us <nl> + estimator . init ( & params , false , false , true ) ; <nl> + <nl> + / / Initialize Sensors <nl> + sensors . init ( & common_state , board , & estimator , & params , comm_link ) ; <nl> + <nl> + mux . init ( & common_state , board , & params ) ; <nl> + <nl> + / / Initialize Motor Mixing <nl> + mixer . init ( & common_state , board , & params ) ; <nl> + <nl> + controller . init ( & common_state , board , & mux , & mixer , & estimator , & params , comm_link ) ; <nl> + <nl> + rc . init ( & common_state , board , & mux , & params , comm_link ) ; <nl> + <nl> + mode . init ( board , comm_link , & common_state , & sensors , & rc , & params ) ; <nl> + <nl> + comm_link - > log_message ( " ROSFlight firmware initialized " , 0 ) ; <nl> + } <nl> + <nl> + void Firmware : : loop ( ) <nl> + { <nl> + / * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * Control Loop * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * / <nl> + if ( sensors . update_sensors ( ) ) / / 595 | 591 | 590 us <nl> + { <nl> + / / If I have new IMU data , then perform control <nl> + sensors . get_imu_measurements ( accel , gyro , imu_time ) ; <nl> + estimator . run_estimator ( accel , gyro , imu_time ) ; / / 212 | 195 us ( acc and gyro only , not exp propagation no quadratic integration ) <nl> + controller . run_controller ( ) ; / / 278 | 271 <nl> + mixer . mix_output ( ) ; / / 16 | 13 us <nl> + } <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * Post - Process * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * / <nl> + / / Let communication stack send and recieve messages <nl> + comm_link - > update ( ) ; / / 165 | 27 | 2 <nl> + <nl> + / / update the armed_states , an internal timer runs this at a fixed rate <nl> + mode . check_mode ( board - > micros ( ) ) ; / / 108 | 1 | 1 <nl> + <nl> + / / get RC , an internal timer runs this every 20 ms ( 50 Hz ) <nl> + rc . receive_rc ( board - > micros ( ) ) ; / / 42 | 2 | 1 <nl> + <nl> + / / update commands ( internal logic tells whether or not we should do anything or not ) <nl> + mux . mux_inputs ( ) ; / / 6 | 1 | 1 <nl> + } <nl> + <nl> + <nl> + <nl> + } / / namespace <nl> + <nl> + <nl> + # if defined ( _MSC_VER ) <nl> + __pragma ( warning ( pop ) ) <nl> + # endif <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / mixer . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / mixer . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / mixer . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / mixer . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - # include < cstdbool > <nl> - # include " commonstate . hpp " <nl> - # include " param . hpp " <nl> - # include " board . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Mixer { <nl> - public : <nl> - struct command_t <nl> - { <nl> - float F ; <nl> - float x ; <nl> - float y ; <nl> - float z ; <nl> - } ; <nl> - <nl> - typedef enum <nl> - { <nl> - QUADCOPTER_PLUS = 0 , <nl> - QUADCOPTER_X = 1 , <nl> - QUADCOPTER_H , <nl> - TRICOPTER , <nl> - Y6 , <nl> - FIXEDWING , <nl> - NUM_MIXERS <nl> - } mixer_type_t ; <nl> - <nl> - public : <nl> - void init ( CommonState * _common_state , Board * _board , Params * _params ) ; <nl> - void init_PWM ( ) ; <nl> - void mix_output ( ) ; <nl> - command_t & getCommand ( ) { return _command ; } <nl> - <nl> - private : <nl> - void write_motor ( uint8_t index , int32_t value ) ; <nl> - void write_servo ( uint8_t index , int32_t value ) ; <nl> - <nl> - private : <nl> - typedef enum <nl> - { <nl> - NONE , / / None <nl> - S , / / Servo <nl> - M , / / Motor <nl> - G / / GPIO <nl> - } output_type_t ; <nl> - <nl> - typedef struct <nl> - { <nl> - output_type_t output_type [ 8 ] ; <nl> - float F [ 8 ] ; <nl> - float x [ 8 ] ; <nl> - float y [ 8 ] ; <nl> - float z [ 8 ] ; <nl> - } mixer_t ; <nl> - <nl> - int32_t _GPIO_outputs [ 8 ] ; <nl> - int32_t prescaled_outputs [ 8 ] ; <nl> - int32_t _outputs [ 8 ] ; <nl> - command_t _command ; <nl> - output_type_t _GPIO_output_type [ 8 ] ; <nl> - <nl> - CommonState * common_state ; <nl> - Params * params ; <nl> - Board * board ; <nl> - <nl> - const mixer_t quadcopter_plus_mixing = <nl> - { <nl> - { M , M , M , M , NONE , NONE , NONE , NONE } , / / output_type <nl> - <nl> - { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> - { 0 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> - { - 1 . 0f , 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> - { - 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> - } ; <nl> - <nl> - <nl> - const mixer_t quadcopter_x_mixing = <nl> - { <nl> - { M , M , M , M , NONE , NONE , NONE , NONE } , / / output_type <nl> - <nl> - { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> - { - 1 . 0f , - 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> - { - 1 . 0f , 1 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> - { - 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> - } ; <nl> - <nl> - const mixer_t quadcopter_h_mixing = <nl> - { <nl> - { M , M , M , M , NONE , NONE , NONE , NONE } , / / output_type <nl> - <nl> - { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> - { - 1057 , - 943 , 1057 , 943 , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> - { - 1005 , 995 , - 1005 , 995 , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> - { - 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> - } ; <nl> - <nl> - const mixer_t fixedwing_mixing = <nl> - { <nl> - { S , S , M , S , NONE , NONE , NONE , NONE } , <nl> - <nl> - { 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> - { 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> - { 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> - { 0 . 0f , 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> - } ; <nl> - <nl> - const mixer_t tricopter_mixing = <nl> - { <nl> - { M , M , M , S , NONE , NONE , NONE , NONE } , <nl> - <nl> - { 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> - { - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> - { - 0 . 667f , - 0 . 667f , 1 . 333f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> - { 0 . 0f , 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> - } ; <nl> - <nl> - const mixer_t Y6_mixing = <nl> - { <nl> - { M , M , M , M , M , M , NONE , NONE } , <nl> - { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> - { 0 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> - { - 1 . 333f , 0 . 667f , 0 . 667f , - 1 . 333f , 0 . 667f , 0 . 667f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> - { - 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> - } ; <nl> - <nl> - const mixer_t * array_of_mixers [ NUM_MIXERS ] = <nl> - { <nl> - & quadcopter_plus_mixing , <nl> - & quadcopter_x_mixing , <nl> - & quadcopter_h_mixing , <nl> - & tricopter_mixing , <nl> - & Y6_mixing , <nl> - & fixedwing_mixing <nl> - } ; <nl> - <nl> - mixer_t mixer_to_use ; <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - void Mixer : : init ( CommonState * _common_state , Board * _board , Params * _params ) <nl> - { <nl> - common_state = _common_state ; <nl> - params = _params ; <nl> - board = _board ; <nl> - <nl> - / / We need a better way to choosing the mixer <nl> - mixer_to_use = * array_of_mixers [ params - > get_param_int ( Params : : PARAM_MIXER ) ] ; <nl> - <nl> - for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> - { <nl> - _outputs [ i ] = 0 ; <nl> - prescaled_outputs [ i ] = 0 ; <nl> - _GPIO_outputs [ i ] = 0 ; <nl> - _GPIO_output_type [ i ] = NONE ; <nl> - } <nl> - _command . F = 0 ; <nl> - _command . x = 0 ; <nl> - _command . y = 0 ; <nl> - _command . z = 0 ; <nl> - <nl> - init_PWM ( ) ; <nl> - } <nl> - <nl> - void Mixer : : init_PWM ( ) <nl> - { <nl> - bool useCPPM = false ; <nl> - if ( params - > get_param_int ( Params : : PARAM_RC_TYPE ) = = 1 ) <nl> - { <nl> - useCPPM = true ; <nl> - } <nl> - int16_t motor_refresh_rate = params - > get_param_int ( Params : : PARAM_MOTOR_PWM_SEND_RATE ) ; <nl> - int16_t off_pwm = 1000 ; <nl> - board - > pwmInit ( useCPPM , false , false , motor_refresh_rate , off_pwm ) ; <nl> - } <nl> - <nl> - <nl> - void Mixer : : write_motor ( uint8_t index , int32_t value ) <nl> - { <nl> - value + = 1000 ; <nl> - if ( common_state - > is_armed ( ) ) <nl> - { <nl> - if ( value > 2000 ) <nl> - { <nl> - value = 2000 ; <nl> - } else if ( value < params - > get_param_int ( Params : : PARAM_MOTOR_IDLE_PWM ) & & params - > get_param_int ( Params : : PARAM_SPIN_MOTORS_WHEN_ARMED ) ) <nl> - { <nl> - value = params - > get_param_int ( Params : : PARAM_MOTOR_IDLE_PWM ) ; <nl> - } else if ( value < 1000 ) <nl> - { <nl> - value = 1000 ; <nl> - } <nl> - } else <nl> - { <nl> - value = 1000 ; <nl> - } <nl> - _outputs [ index ] = value ; <nl> - board - > pwmWriteMotor ( index , _outputs [ index ] ) ; <nl> - } <nl> - <nl> - <nl> - void Mixer : : write_servo ( uint8_t index , int32_t value ) <nl> - { <nl> - if ( value > 500 ) <nl> - { <nl> - value = 500 ; <nl> - } else if ( value < - 500 ) <nl> - { <nl> - value = - 500 ; <nl> - } <nl> - _outputs [ index ] = value + 1500 ; <nl> - board - > pwmWriteMotor ( index , _outputs [ index ] ) ; <nl> - } <nl> - <nl> - <nl> - void Mixer : : mix_output ( ) <nl> - { <nl> - int32_t max_output = 0 ; <nl> - <nl> - / / For now , we aren ' t supporting mixing with fixed wings . This is a total hack , and should be re - thought <nl> - if ( params - > get_param_int ( Params : : PARAM_FIXED_WING ) ) <nl> - { <nl> - / / AETR <nl> - prescaled_outputs [ 0 ] = static_cast < int32_t > ( _command . x ) ; <nl> - prescaled_outputs [ 1 ] = static_cast < int32_t > ( _command . y ) ; <nl> - prescaled_outputs [ 2 ] = static_cast < int32_t > ( _command . F * 1000 ) ; / / Throttle comes in scaled from 0 . 0 to 1 . 0 <nl> - prescaled_outputs [ 3 ] = static_cast < int32_t > ( _command . z ) ; <nl> - } else / / For multirotors , domixing the same way ( in fixed point for now ) ; <nl> - { <nl> - <nl> - for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> - { <nl> - if ( mixer_to_use . output_type [ i ] ! = NONE ) <nl> - { <nl> - / / Matrix multiply ( in so many words ) - - done in integer , hence the / 1000 at the end <nl> - prescaled_outputs [ i ] = ( int32_t ) ( ( _command . F * mixer_to_use . F [ i ] + _command . x * mixer_to_use . x [ i ] + <nl> - _command . y * mixer_to_use . y [ i ] + _command . z * mixer_to_use . z [ i ] ) * 1000 . 0f ) ; <nl> - if ( prescaled_outputs [ i ] > 1000 & & prescaled_outputs [ i ] > max_output ) <nl> - { <nl> - max_output = prescaled_outputs [ i ] ; <nl> - } <nl> - / / negative motor outputs are set to zero when writing to the motor , <nl> - / / but they have to be allowed here because the same logic is used for <nl> - / / servo commands , which may be negative <nl> - } <nl> - } <nl> - <nl> - / / saturate outputs to maintain controllability even during aggressive maneuvers <nl> - if ( max_output > 1000 ) <nl> - { <nl> - int32_t scale_factor = 1000 * 1000 / max_output ; <nl> - for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> - { <nl> - if ( mixer_to_use . output_type [ i ] = = M ) <nl> - { <nl> - prescaled_outputs [ i ] = ( prescaled_outputs [ i ] ) * scale_factor / 1000 ; / / divide by scale factor <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - / / Reverse Fixedwing channels <nl> - if ( params - > get_param_int ( Params : : PARAM_FIXED_WING ) ) <nl> - { <nl> - prescaled_outputs [ 0 ] * = params - > get_param_int ( Params : : PARAM_AILERON_REVERSE ) ? - 1 : 1 ; <nl> - prescaled_outputs [ 1 ] * = params - > get_param_int ( Params : : PARAM_ELEVATOR_REVERSE ) ? - 1 : 1 ; <nl> - prescaled_outputs [ 3 ] * = params - > get_param_int ( Params : : PARAM_RUDDER_REVERSE ) ? - 1 : 1 ; <nl> - } <nl> - <nl> - / / Add in GPIO inputs from Onboard Computer <nl> - for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> - { <nl> - output_type_t output_type = mixer_to_use . output_type [ i ] ; <nl> - if ( output_type = = NONE ) <nl> - { <nl> - / / Incorporate GPIO on not already reserved outputs <nl> - prescaled_outputs [ i ] = _GPIO_outputs [ i ] ; <nl> - output_type = _GPIO_output_type [ i ] ; <nl> - } <nl> - <nl> - / / Write output to motors <nl> - if ( output_type = = S ) <nl> - { <nl> - write_servo ( i , prescaled_outputs [ i ] ) ; <nl> - } else if ( output_type = = M ) <nl> - { <nl> - write_motor ( i , prescaled_outputs [ i ] ) ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + # include < cstdbool > <nl> + # include " commonstate . hpp " <nl> + # include " param . hpp " <nl> + # include " board . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Mixer { <nl> + public : <nl> + struct command_t <nl> + { <nl> + float F ; <nl> + float x ; <nl> + float y ; <nl> + float z ; <nl> + } ; <nl> + <nl> + typedef enum <nl> + { <nl> + QUADCOPTER_PLUS = 0 , <nl> + QUADCOPTER_X = 1 , <nl> + QUADCOPTER_H , <nl> + TRICOPTER , <nl> + Y6 , <nl> + FIXEDWING , <nl> + NUM_MIXERS <nl> + } mixer_type_t ; <nl> + <nl> + public : <nl> + void init ( CommonState * _common_state , Board * _board , Params * _params ) ; <nl> + void init_PWM ( ) ; <nl> + void mix_output ( ) ; <nl> + command_t & getCommand ( ) { return _command ; } <nl> + <nl> + private : <nl> + void write_motor ( uint8_t index , int32_t value ) ; <nl> + void write_servo ( uint8_t index , int32_t value ) ; <nl> + <nl> + private : <nl> + typedef enum <nl> + { <nl> + NONE , / / None <nl> + S , / / Servo <nl> + M , / / Motor <nl> + G / / GPIO <nl> + } output_type_t ; <nl> + <nl> + typedef struct <nl> + { <nl> + output_type_t output_type [ 8 ] ; <nl> + float F [ 8 ] ; <nl> + float x [ 8 ] ; <nl> + float y [ 8 ] ; <nl> + float z [ 8 ] ; <nl> + } mixer_t ; <nl> + <nl> + int32_t _GPIO_outputs [ 8 ] ; <nl> + int32_t prescaled_outputs [ 8 ] ; <nl> + int32_t _outputs [ 8 ] ; <nl> + command_t _command ; <nl> + output_type_t _GPIO_output_type [ 8 ] ; <nl> + <nl> + CommonState * common_state ; <nl> + Params * params ; <nl> + Board * board ; <nl> + <nl> + const mixer_t quadcopter_plus_mixing = <nl> + { <nl> + { M , M , M , M , NONE , NONE , NONE , NONE } , / / output_type <nl> + <nl> + { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> + { 0 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> + { - 1 . 0f , 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> + { - 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> + } ; <nl> + <nl> + <nl> + const mixer_t quadcopter_x_mixing = <nl> + { <nl> + { M , M , M , M , NONE , NONE , NONE , NONE } , / / output_type <nl> + <nl> + { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> + { - 1 . 0f , - 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> + { - 1 . 0f , 1 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> + { - 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> + } ; <nl> + <nl> + const mixer_t quadcopter_h_mixing = <nl> + { <nl> + { M , M , M , M , NONE , NONE , NONE , NONE } , / / output_type <nl> + <nl> + { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> + { - 1057 , - 943 , 1057 , 943 , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> + { - 1005 , 995 , - 1005 , 995 , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> + { - 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> + } ; <nl> + <nl> + const mixer_t fixedwing_mixing = <nl> + { <nl> + { S , S , M , S , NONE , NONE , NONE , NONE } , <nl> + <nl> + { 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> + { 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> + { 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> + { 0 . 0f , 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> + } ; <nl> + <nl> + const mixer_t tricopter_mixing = <nl> + { <nl> + { M , M , M , S , NONE , NONE , NONE , NONE } , <nl> + <nl> + { 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> + { - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> + { - 0 . 667f , - 0 . 667f , 1 . 333f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> + { 0 . 0f , 0 . 0f , 0 . 0f , 1 . 0f , 0 . 0f , 0 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> + } ; <nl> + <nl> + const mixer_t Y6_mixing = <nl> + { <nl> + { M , M , M , M , M , M , NONE , NONE } , <nl> + { 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f } , / / F Mix <nl> + { 0 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , - 1 . 0f , 1 . 0f , 0 . 0f , 0 . 0f } , / / X Mix <nl> + { - 1 . 333f , 0 . 667f , 0 . 667f , - 1 . 333f , 0 . 667f , 0 . 667f , 0 . 0f , 0 . 0f } , / / Y Mix <nl> + { - 1 . 0f , 1 . 0f , 1 . 0f , 1 . 0f , - 1 . 0f , - 1 . 0f , 0 . 0f , 0 . 0f } / / Z Mix <nl> + } ; <nl> + <nl> + const mixer_t * array_of_mixers [ NUM_MIXERS ] = <nl> + { <nl> + & quadcopter_plus_mixing , <nl> + & quadcopter_x_mixing , <nl> + & quadcopter_h_mixing , <nl> + & tricopter_mixing , <nl> + & Y6_mixing , <nl> + & fixedwing_mixing <nl> + } ; <nl> + <nl> + mixer_t mixer_to_use ; <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + void Mixer : : init ( CommonState * _common_state , Board * _board , Params * _params ) <nl> + { <nl> + common_state = _common_state ; <nl> + params = _params ; <nl> + board = _board ; <nl> + <nl> + / / We need a better way to choosing the mixer <nl> + mixer_to_use = * array_of_mixers [ params - > get_param_int ( Params : : PARAM_MIXER ) ] ; <nl> + <nl> + for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> + { <nl> + _outputs [ i ] = 0 ; <nl> + prescaled_outputs [ i ] = 0 ; <nl> + _GPIO_outputs [ i ] = 0 ; <nl> + _GPIO_output_type [ i ] = NONE ; <nl> + } <nl> + _command . F = 0 ; <nl> + _command . x = 0 ; <nl> + _command . y = 0 ; <nl> + _command . z = 0 ; <nl> + <nl> + init_PWM ( ) ; <nl> + } <nl> + <nl> + void Mixer : : init_PWM ( ) <nl> + { <nl> + bool useCPPM = false ; <nl> + if ( params - > get_param_int ( Params : : PARAM_RC_TYPE ) = = 1 ) <nl> + { <nl> + useCPPM = true ; <nl> + } <nl> + int16_t motor_refresh_rate = params - > get_param_int ( Params : : PARAM_MOTOR_PWM_SEND_RATE ) ; <nl> + int16_t off_pwm = 1000 ; <nl> + board - > pwmInit ( useCPPM , false , false , motor_refresh_rate , off_pwm ) ; <nl> + } <nl> + <nl> + <nl> + void Mixer : : write_motor ( uint8_t index , int32_t value ) <nl> + { <nl> + value + = 1000 ; <nl> + if ( common_state - > is_armed ( ) ) <nl> + { <nl> + if ( value > 2000 ) <nl> + { <nl> + value = 2000 ; <nl> + } else if ( value < params - > get_param_int ( Params : : PARAM_MOTOR_IDLE_PWM ) & & params - > get_param_int ( Params : : PARAM_SPIN_MOTORS_WHEN_ARMED ) ) <nl> + { <nl> + value = params - > get_param_int ( Params : : PARAM_MOTOR_IDLE_PWM ) ; <nl> + } else if ( value < 1000 ) <nl> + { <nl> + value = 1000 ; <nl> + } <nl> + } else <nl> + { <nl> + value = 1000 ; <nl> + } <nl> + _outputs [ index ] = value ; <nl> + board - > pwmWriteMotor ( index , _outputs [ index ] ) ; <nl> + } <nl> + <nl> + <nl> + void Mixer : : write_servo ( uint8_t index , int32_t value ) <nl> + { <nl> + if ( value > 500 ) <nl> + { <nl> + value = 500 ; <nl> + } else if ( value < - 500 ) <nl> + { <nl> + value = - 500 ; <nl> + } <nl> + _outputs [ index ] = value + 1500 ; <nl> + board - > pwmWriteMotor ( index , _outputs [ index ] ) ; <nl> + } <nl> + <nl> + <nl> + void Mixer : : mix_output ( ) <nl> + { <nl> + int32_t max_output = 0 ; <nl> + <nl> + / / For now , we aren ' t supporting mixing with fixed wings . This is a total hack , and should be re - thought <nl> + if ( params - > get_param_int ( Params : : PARAM_FIXED_WING ) ) <nl> + { <nl> + / / AETR <nl> + prescaled_outputs [ 0 ] = static_cast < int32_t > ( _command . x ) ; <nl> + prescaled_outputs [ 1 ] = static_cast < int32_t > ( _command . y ) ; <nl> + prescaled_outputs [ 2 ] = static_cast < int32_t > ( _command . F * 1000 ) ; / / Throttle comes in scaled from 0 . 0 to 1 . 0 <nl> + prescaled_outputs [ 3 ] = static_cast < int32_t > ( _command . z ) ; <nl> + } else / / For multirotors , domixing the same way ( in fixed point for now ) ; <nl> + { <nl> + <nl> + for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> + { <nl> + if ( mixer_to_use . output_type [ i ] ! = NONE ) <nl> + { <nl> + / / Matrix multiply ( in so many words ) - - done in integer , hence the / 1000 at the end <nl> + prescaled_outputs [ i ] = ( int32_t ) ( ( _command . F * mixer_to_use . F [ i ] + _command . x * mixer_to_use . x [ i ] + <nl> + _command . y * mixer_to_use . y [ i ] + _command . z * mixer_to_use . z [ i ] ) * 1000 . 0f ) ; <nl> + if ( prescaled_outputs [ i ] > 1000 & & prescaled_outputs [ i ] > max_output ) <nl> + { <nl> + max_output = prescaled_outputs [ i ] ; <nl> + } <nl> + / / negative motor outputs are set to zero when writing to the motor , <nl> + / / but they have to be allowed here because the same logic is used for <nl> + / / servo commands , which may be negative <nl> + } <nl> + } <nl> + <nl> + / / saturate outputs to maintain controllability even during aggressive maneuvers <nl> + if ( max_output > 1000 ) <nl> + { <nl> + int32_t scale_factor = 1000 * 1000 / max_output ; <nl> + for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> + { <nl> + if ( mixer_to_use . output_type [ i ] = = M ) <nl> + { <nl> + prescaled_outputs [ i ] = ( prescaled_outputs [ i ] ) * scale_factor / 1000 ; / / divide by scale factor <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Reverse Fixedwing channels <nl> + if ( params - > get_param_int ( Params : : PARAM_FIXED_WING ) ) <nl> + { <nl> + prescaled_outputs [ 0 ] * = params - > get_param_int ( Params : : PARAM_AILERON_REVERSE ) ? - 1 : 1 ; <nl> + prescaled_outputs [ 1 ] * = params - > get_param_int ( Params : : PARAM_ELEVATOR_REVERSE ) ? - 1 : 1 ; <nl> + prescaled_outputs [ 3 ] * = params - > get_param_int ( Params : : PARAM_RUDDER_REVERSE ) ? - 1 : 1 ; <nl> + } <nl> + <nl> + / / Add in GPIO inputs from Onboard Computer <nl> + for ( int8_t i = 0 ; i < 8 ; i + + ) <nl> + { <nl> + output_type_t output_type = mixer_to_use . output_type [ i ] ; <nl> + if ( output_type = = NONE ) <nl> + { <nl> + / / Incorporate GPIO on not already reserved outputs <nl> + prescaled_outputs [ i ] = _GPIO_outputs [ i ] ; <nl> + output_type = _GPIO_output_type [ i ] ; <nl> + } <nl> + <nl> + / / Write output to motors <nl> + if ( output_type = = S ) <nl> + { <nl> + write_servo ( i , prescaled_outputs [ i ] ) ; <nl> + } else if ( output_type = = M ) <nl> + { <nl> + write_motor ( i , prescaled_outputs [ i ] ) ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / mode . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / mode . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / mode . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / mode . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - # include " sensors . hpp " <nl> - # include " rc . hpp " <nl> - # include " commonstate . hpp " <nl> - # include " param . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Mode { <nl> - public : <nl> - typedef enum <nl> - { <nl> - INVALID_CONTROL_MODE , <nl> - INVALID_ARMED_STATE , <nl> - } error_state_t ; <nl> - <nl> - void init ( Board * _board , CommLink * _comm_link , CommonState * _common_state , Sensors * _sensors , RC * _rc , Params * _params ) ; <nl> - bool check_mode ( uint64_t now ) ; <nl> - <nl> - private : <nl> - bool arm ( void ) ; <nl> - void disarm ( void ) ; <nl> - bool check_failsafe ( void ) ; <nl> - void updateCommLinkArmStatus ( ) ; <nl> - <nl> - private : <nl> - error_state_t _error_state ; <nl> - CommonState * common_state ; <nl> - Sensors * sensors ; <nl> - RC * rc ; <nl> - Params * params ; <nl> - Board * board ; <nl> - CommLink * comm_link ; <nl> - <nl> - bool started_gyro_calibration = false ; / / arm <nl> - uint8_t blink_count = 0 ; / / check_failsafe <nl> - uint64_t prev_time = 0 ; / / check_mode <nl> - uint32_t time_sticks_have_been_in_arming_position = 0 ; / / check_mode <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - void Mode : : init ( Board * _board , CommLink * _comm_link , CommonState * _common_state , Sensors * _sensors , RC * _rc , Params * _params ) <nl> - { <nl> - board = _board ; <nl> - comm_link = _comm_link ; <nl> - params = _params ; <nl> - common_state = _common_state ; <nl> - sensors = _sensors ; <nl> - rc = _rc ; <nl> - <nl> - common_state - > set_disarm ( ) ; <nl> - } <nl> - <nl> - bool Mode : : arm ( void ) <nl> - { <nl> - bool success = false ; <nl> - if ( ! started_gyro_calibration ) <nl> - { <nl> - if ( common_state - > is_disarmed ( ) ) <nl> - comm_link - > log_message ( " Cannot arm because gyro calibration is not complete " , 1 ) ; <nl> - <nl> - sensors - > start_gyro_calibration ( ) ; <nl> - started_gyro_calibration = true ; <nl> - } else if ( sensors - > gyro_calibration_complete ( ) ) <nl> - { <nl> - started_gyro_calibration = false ; <nl> - common_state - > set_arm ( ) ; <nl> - board - > set_led ( 0 , true ) ; <nl> - success = true ; <nl> - } <nl> - <nl> - updateCommLinkArmStatus ( ) ; <nl> - <nl> - return success ; <nl> - } <nl> - <nl> - void Mode : : disarm ( void ) <nl> - { <nl> - common_state - > set_disarm ( ) ; <nl> - board - > set_led ( 0 , true ) ; <nl> - <nl> - updateCommLinkArmStatus ( ) ; <nl> - } <nl> - <nl> - / / / TODO : Be able to tell if the RC has become disconnected during flight <nl> - bool Mode : : check_failsafe ( void ) <nl> - { <nl> - for ( int8_t i = 0 ; i < params - > get_param_int ( Params : : PARAM_RC_NUM_CHANNELS ) ; i + + ) <nl> - { <nl> - if ( board - > pwmRead ( i ) < 900 | | board - > pwmRead ( i ) > 2100 ) <nl> - { <nl> - if ( common_state - > is_armed ( ) | | common_state - > is_disarmed ( ) ) <nl> - { <nl> - comm_link - > log_message ( " Switching to failsafe mode because of invalid PWM RC inputs " , 1 ) ; <nl> - common_state - > setArmedState ( CommonState : : FAILSAFE_DISARMED ) ; <nl> - } <nl> - <nl> - / / blink LED <nl> - if ( blink_count > 25 ) <nl> - { <nl> - board - > toggle_led ( 1 ) ; <nl> - blink_count = 0 ; <nl> - } <nl> - blink_count + + ; <nl> - return true ; <nl> - } <nl> - } <nl> - <nl> - / / we got a valid RC measurement for all channels <nl> - if ( common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_ARMED | | common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_DISARMED ) <nl> - { <nl> - / / return to appropriate mode <nl> - common_state - > setArmedState ( <nl> - ( common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_ARMED ) ? CommonState : : ARMED : CommonState : : DISARMED <nl> - ) ; <nl> - } <nl> - return false ; <nl> - } <nl> - <nl> - void Mode : : updateCommLinkArmStatus ( ) <nl> - { <nl> - if ( common_state - > is_armed ( ) ) <nl> - comm_link - > log_message ( " Vehicle is now armed " , 0 ) ; <nl> - else if ( common_state - > is_disarmed ( ) ) <nl> - comm_link - > log_message ( " Vehicle is now disarmed " , 0 ) ; <nl> - else <nl> - comm_link - > log_message ( " Attempt to arm or disarm failed " , 0 ) ; <nl> - <nl> - } <nl> - <nl> - bool Mode : : check_mode ( uint64_t now ) <nl> - { <nl> - / / see it has been at least 20 ms <nl> - uint32_t dt = static_cast < uint32_t > ( now - prev_time ) ; <nl> - if ( dt < 20000 ) <nl> - { <nl> - return false ; <nl> - } <nl> - <nl> - / / if it has , then do stuff <nl> - prev_time = now ; <nl> - <nl> - / / check for failsafe mode <nl> - if ( check_failsafe ( ) ) <nl> - { <nl> - return true ; <nl> - } else <nl> - { <nl> - / / check for arming switch <nl> - if ( params - > get_param_int ( Params : : PARAM_ARM_STICKS ) ) <nl> - { <nl> - if ( common_state - > get_armed_state ( ) = = CommonState : : DISARMED ) <nl> - { <nl> - / / if left stick is down and to the right <nl> - if ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ) < params - > get_param_int ( Params : : PARAM_RC_F_BOTTOM ) + params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) <nl> - & & board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) > ( params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) + params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) / 2 ) <nl> - - params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) ) <nl> - { <nl> - time_sticks_have_been_in_arming_position + = dt ; <nl> - } else <nl> - { <nl> - time_sticks_have_been_in_arming_position = 0 ; <nl> - } <nl> - if ( time_sticks_have_been_in_arming_position > 500000 ) <nl> - { <nl> - if ( arm ( ) ) <nl> - time_sticks_have_been_in_arming_position = 0 ; <nl> - } <nl> - } else / / _armed_state is ARMED <nl> - { <nl> - / / if left stick is down and to the left <nl> - if ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ) < params - > get_param_int ( Params : : PARAM_RC_F_BOTTOM ) + <nl> - params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) <nl> - & & board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) < ( params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) - params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) / 2 ) <nl> - + params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) ) <nl> - { <nl> - time_sticks_have_been_in_arming_position + = dt ; <nl> - } else <nl> - { <nl> - time_sticks_have_been_in_arming_position = 0 ; <nl> - } <nl> - if ( time_sticks_have_been_in_arming_position > 500000 ) <nl> - { <nl> - disarm ( ) ; <nl> - time_sticks_have_been_in_arming_position = 0 ; <nl> - } <nl> - } <nl> - } else <nl> - { <nl> - if ( rc - > rc_switch ( params - > get_param_int ( Params : : PARAM_ARM_CHANNEL ) ) ) <nl> - { <nl> - if ( common_state - > is_disarmed ( ) ) <nl> - arm ( ) ; <nl> - } else <nl> - { <nl> - if ( common_state - > is_armed ( ) ) <nl> - disarm ( ) ; <nl> - } <nl> - } <nl> - } <nl> - return true ; <nl> - } <nl> - <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + # include " sensors . hpp " <nl> + # include " rc . hpp " <nl> + # include " commonstate . hpp " <nl> + # include " param . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Mode { <nl> + public : <nl> + typedef enum <nl> + { <nl> + INVALID_CONTROL_MODE , <nl> + INVALID_ARMED_STATE , <nl> + } error_state_t ; <nl> + <nl> + void init ( Board * _board , CommLink * _comm_link , CommonState * _common_state , Sensors * _sensors , RC * _rc , Params * _params ) ; <nl> + bool check_mode ( uint64_t now ) ; <nl> + <nl> + private : <nl> + bool arm ( void ) ; <nl> + void disarm ( void ) ; <nl> + bool check_failsafe ( void ) ; <nl> + void updateCommLinkArmStatus ( ) ; <nl> + <nl> + private : <nl> + error_state_t _error_state ; <nl> + CommonState * common_state ; <nl> + Sensors * sensors ; <nl> + RC * rc ; <nl> + Params * params ; <nl> + Board * board ; <nl> + CommLink * comm_link ; <nl> + <nl> + bool started_gyro_calibration = false ; / / arm <nl> + uint8_t blink_count = 0 ; / / check_failsafe <nl> + uint64_t prev_time = 0 ; / / check_mode <nl> + uint32_t time_sticks_have_been_in_arming_position = 0 ; / / check_mode <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + void Mode : : init ( Board * _board , CommLink * _comm_link , CommonState * _common_state , Sensors * _sensors , RC * _rc , Params * _params ) <nl> + { <nl> + board = _board ; <nl> + comm_link = _comm_link ; <nl> + params = _params ; <nl> + common_state = _common_state ; <nl> + sensors = _sensors ; <nl> + rc = _rc ; <nl> + <nl> + common_state - > set_disarm ( ) ; <nl> + } <nl> + <nl> + bool Mode : : arm ( void ) <nl> + { <nl> + bool success = false ; <nl> + if ( ! started_gyro_calibration ) <nl> + { <nl> + if ( common_state - > is_disarmed ( ) ) <nl> + comm_link - > log_message ( " Cannot arm because gyro calibration is not complete " , 1 ) ; <nl> + <nl> + sensors - > start_gyro_calibration ( ) ; <nl> + started_gyro_calibration = true ; <nl> + } else if ( sensors - > gyro_calibration_complete ( ) ) <nl> + { <nl> + started_gyro_calibration = false ; <nl> + common_state - > set_arm ( ) ; <nl> + board - > set_led ( 0 , true ) ; <nl> + success = true ; <nl> + } <nl> + <nl> + updateCommLinkArmStatus ( ) ; <nl> + <nl> + return success ; <nl> + } <nl> + <nl> + void Mode : : disarm ( void ) <nl> + { <nl> + common_state - > set_disarm ( ) ; <nl> + board - > set_led ( 0 , true ) ; <nl> + <nl> + updateCommLinkArmStatus ( ) ; <nl> + } <nl> + <nl> + / / / TODO : Be able to tell if the RC has become disconnected during flight <nl> + bool Mode : : check_failsafe ( void ) <nl> + { <nl> + for ( int8_t i = 0 ; i < params - > get_param_int ( Params : : PARAM_RC_NUM_CHANNELS ) ; i + + ) <nl> + { <nl> + if ( board - > pwmRead ( i ) < 900 | | board - > pwmRead ( i ) > 2100 ) <nl> + { <nl> + if ( common_state - > is_armed ( ) | | common_state - > is_disarmed ( ) ) <nl> + { <nl> + comm_link - > log_message ( " Switching to failsafe mode because of invalid PWM RC inputs " , 1 ) ; <nl> + common_state - > setArmedState ( CommonState : : FAILSAFE_DISARMED ) ; <nl> + } <nl> + <nl> + / / blink LED <nl> + if ( blink_count > 25 ) <nl> + { <nl> + board - > toggle_led ( 1 ) ; <nl> + blink_count = 0 ; <nl> + } <nl> + blink_count + + ; <nl> + return true ; <nl> + } <nl> + } <nl> + <nl> + / / we got a valid RC measurement for all channels <nl> + if ( common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_ARMED | | common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_DISARMED ) <nl> + { <nl> + / / return to appropriate mode <nl> + common_state - > setArmedState ( <nl> + ( common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_ARMED ) ? CommonState : : ARMED : CommonState : : DISARMED <nl> + ) ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + void Mode : : updateCommLinkArmStatus ( ) <nl> + { <nl> + if ( common_state - > is_armed ( ) ) <nl> + comm_link - > log_message ( " Vehicle is now armed " , 0 ) ; <nl> + else if ( common_state - > is_disarmed ( ) ) <nl> + comm_link - > log_message ( " Vehicle is now disarmed " , 0 ) ; <nl> + else <nl> + comm_link - > log_message ( " Attempt to arm or disarm failed " , 0 ) ; <nl> + <nl> + } <nl> + <nl> + bool Mode : : check_mode ( uint64_t now ) <nl> + { <nl> + / / see it has been at least 20 ms <nl> + uint32_t dt = static_cast < uint32_t > ( now - prev_time ) ; <nl> + if ( dt < 20000 ) <nl> + { <nl> + return false ; <nl> + } <nl> + <nl> + / / if it has , then do stuff <nl> + prev_time = now ; <nl> + <nl> + / / check for failsafe mode <nl> + if ( check_failsafe ( ) ) <nl> + { <nl> + return true ; <nl> + } else <nl> + { <nl> + / / check for arming switch <nl> + if ( params - > get_param_int ( Params : : PARAM_ARM_STICKS ) ) <nl> + { <nl> + if ( common_state - > get_armed_state ( ) = = CommonState : : DISARMED ) <nl> + { <nl> + / / if left stick is down and to the right <nl> + if ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ) < params - > get_param_int ( Params : : PARAM_RC_F_BOTTOM ) + params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) <nl> + & & board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) > ( params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) + params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) / 2 ) <nl> + - params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) ) <nl> + { <nl> + time_sticks_have_been_in_arming_position + = dt ; <nl> + } else <nl> + { <nl> + time_sticks_have_been_in_arming_position = 0 ; <nl> + } <nl> + if ( time_sticks_have_been_in_arming_position > 500000 ) <nl> + { <nl> + if ( arm ( ) ) <nl> + time_sticks_have_been_in_arming_position = 0 ; <nl> + } <nl> + } else / / _armed_state is ARMED <nl> + { <nl> + / / if left stick is down and to the left <nl> + if ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ) < params - > get_param_int ( Params : : PARAM_RC_F_BOTTOM ) + <nl> + params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) <nl> + & & board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) < ( params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) - params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) / 2 ) <nl> + + params - > get_param_int ( Params : : PARAM_ARM_THRESHOLD ) ) <nl> + { <nl> + time_sticks_have_been_in_arming_position + = dt ; <nl> + } else <nl> + { <nl> + time_sticks_have_been_in_arming_position = 0 ; <nl> + } <nl> + if ( time_sticks_have_been_in_arming_position > 500000 ) <nl> + { <nl> + disarm ( ) ; <nl> + time_sticks_have_been_in_arming_position = 0 ; <nl> + } <nl> + } <nl> + } else <nl> + { <nl> + if ( rc - > rc_switch ( params - > get_param_int ( Params : : PARAM_ARM_CHANNEL ) ) ) <nl> + { <nl> + if ( common_state - > is_disarmed ( ) ) <nl> + arm ( ) ; <nl> + } else <nl> + { <nl> + if ( common_state - > is_armed ( ) ) <nl> + disarm ( ) ; <nl> + } <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / mux . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / mux . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / mux . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / mux . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdbool > <nl> - # include < cstdint > <nl> - # include " commonstate . hpp " <nl> - # include " param . hpp " <nl> - # include " board . hpp " <nl> - <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Mux { <nl> - public : <nl> - enum class control_type_t <nl> - { <nl> - RATE , / / Channel is is in rate mode ( mrad / s ) <nl> - ANGLE , / / Channel command is in angle mode ( mrad ) <nl> - THROTTLE , / / Channel is direcly controlling throttle max / 1000 <nl> - ALTITUDE , / / Channel is commanding a specified altitude in cm <nl> - MOTOR_DIRECT / / Channel directly passes PWM input to the mixer <nl> - } ; <nl> - <nl> - struct control_channel_t <nl> - { <nl> - bool active ; / / Whether or not the channel is active <nl> - control_type_t type ; / / What type the channel is <nl> - float value ; / / The value of the channel <nl> - } ; <nl> - <nl> - struct control_t <nl> - { <nl> - control_channel_t x ; <nl> - control_channel_t y ; <nl> - control_channel_t z ; <nl> - control_channel_t F ; <nl> - } ; <nl> - public : <nl> - void init ( CommonState * _common_state , Board * _board , Params * _params ) ; <nl> - bool mux_inputs ( ) ; <nl> - <nl> - control_t & rc_control ( ) { return _rc_control ; } <nl> - control_t & offboard_control ( ) { return _offboard_control ; } <nl> - control_t & combined_control ( ) { return _combined_control ; } <nl> - <nl> - void set_new_command ( bool val ) { _new_command = val ; } <nl> - <nl> - private : <nl> - CommonState * common_state ; <nl> - Params * params ; <nl> - Board * board ; <nl> - <nl> - control_t _rc_control ; <nl> - control_t _offboard_control ; <nl> - control_t _combined_control ; <nl> - <nl> - bool _new_command ; <nl> - <nl> - control_t _failsafe_control = { <nl> - { true , Mux : : control_type_t : : ANGLE , 0 . 0 } , <nl> - { true , Mux : : control_type_t : : ANGLE , 0 . 0 } , <nl> - { true , Mux : : control_type_t : : RATE , 0 . 0 } , <nl> - { true , Mux : : control_type_t : : THROTTLE , 0 . 0 } } ; <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - void Mux : : init ( CommonState * _common_state , Board * _board , Params * _params ) <nl> - { <nl> - params = _params ; <nl> - common_state = _common_state ; <nl> - board = _board ; <nl> - <nl> - } <nl> - <nl> - bool Mux : : mux_inputs ( ) <nl> - { <nl> - if ( ! _new_command ) <nl> - { <nl> - / / we haven ' t received any new commands , so we shouldn ' t do anything <nl> - return false ; <nl> - } <nl> - / / otherwise combine the new commands <nl> - <nl> - if ( common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_ARMED | | common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_DISARMED ) <nl> - { <nl> - _combined_control = _failsafe_control ; <nl> - } <nl> - else <nl> - { <nl> - if ( _rc_control . x . active ) <nl> - { <nl> - _combined_control . x = _rc_control . x ; <nl> - } <nl> - else if ( _offboard_control . x . active ) <nl> - { <nl> - _combined_control . x = _offboard_control . x ; <nl> - } <nl> - else <nl> - { <nl> - / / default to taking RC if neither is publishing <nl> - _combined_control . x = _rc_control . x ; <nl> - _combined_control . x . active = true ; <nl> - } <nl> - <nl> - <nl> - if ( _rc_control . y . active ) <nl> - { <nl> - _combined_control . y = _rc_control . y ; <nl> - } <nl> - else if ( _offboard_control . y . active ) <nl> - { <nl> - _combined_control . y = _offboard_control . y ; <nl> - } <nl> - else <nl> - { <nl> - / / default to taking RC if neither is publishing <nl> - _combined_control . y = _rc_control . y ; <nl> - _combined_control . y . active = true ; <nl> - } <nl> - <nl> - <nl> - if ( _rc_control . z . active ) <nl> - { <nl> - _combined_control . z = _rc_control . z ; <nl> - } <nl> - else if ( _offboard_control . z . active ) <nl> - { <nl> - _combined_control . z = _offboard_control . z ; <nl> - } <nl> - else <nl> - { <nl> - _combined_control . z = _rc_control . z ; <nl> - _combined_control . z . active = true ; <nl> - } <nl> - <nl> - if ( params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE ) ) <nl> - { <nl> - if ( _offboard_control . F . active ) <nl> - { <nl> - if ( _rc_control . F . type = = Mux : : control_type_t : : THROTTLE & & _offboard_control . F . type = = Mux : : control_type_t : : THROTTLE ) <nl> - { <nl> - _combined_control . F . value = ( _rc_control . F . value > _offboard_control . F . value ) ? <nl> - _offboard_control . F . value : _rc_control . F . value ; <nl> - _combined_control . F . type = Mux : : control_type_t : : THROTTLE ; <nl> - _combined_control . F . active = true ; <nl> - } <nl> - else <nl> - { <nl> - / / I ' m still not quite sure how to handle the mixed altitude / throttle cases <nl> - / / for now , just pass the rc along . I expect that what we really need to do <nl> - / / is run the altitude controller here so we can compare throttle to throttle <nl> - _combined_control . F = _rc_control . F ; <nl> - } <nl> - } <nl> - } <nl> - else / / no min throttle check <nl> - { <nl> - if ( _rc_control . F . active ) <nl> - { <nl> - _combined_control . F = _rc_control . F ; <nl> - } <nl> - else if ( _offboard_control . F . active ) <nl> - { <nl> - _combined_control . F = _offboard_control . F ; <nl> - } <nl> - else <nl> - { <nl> - _combined_control . F = _rc_control . F ; <nl> - _combined_control . F . active = true ; <nl> - } <nl> - } <nl> - <nl> - / / Light to indicate override <nl> - if ( _rc_control . x . active | | _rc_control . y . active | | _rc_control . z . active | | _rc_control . F . active ) <nl> - { <nl> - board - > set_led ( 0 , true ) ; <nl> - } <nl> - else <nl> - { <nl> - board - > set_led ( 0 , false ) ; <nl> - } <nl> - } <nl> - <nl> - / / reset the new command flag <nl> - _new_command = false ; <nl> - return true ; <nl> - } <nl> - <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdbool > <nl> + # include < cstdint > <nl> + # include " commonstate . hpp " <nl> + # include " param . hpp " <nl> + # include " board . hpp " <nl> + <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Mux { <nl> + public : <nl> + enum class control_type_t <nl> + { <nl> + RATE , / / Channel is is in rate mode ( mrad / s ) <nl> + ANGLE , / / Channel command is in angle mode ( mrad ) <nl> + THROTTLE , / / Channel is direcly controlling throttle max / 1000 <nl> + ALTITUDE , / / Channel is commanding a specified altitude in cm <nl> + MOTOR_DIRECT / / Channel directly passes PWM input to the mixer <nl> + } ; <nl> + <nl> + struct control_channel_t <nl> + { <nl> + bool active ; / / Whether or not the channel is active <nl> + control_type_t type ; / / What type the channel is <nl> + float value ; / / The value of the channel <nl> + } ; <nl> + <nl> + struct control_t <nl> + { <nl> + control_channel_t x ; <nl> + control_channel_t y ; <nl> + control_channel_t z ; <nl> + control_channel_t F ; <nl> + } ; <nl> + public : <nl> + void init ( CommonState * _common_state , Board * _board , Params * _params ) ; <nl> + bool mux_inputs ( ) ; <nl> + <nl> + control_t & rc_control ( ) { return _rc_control ; } <nl> + control_t & offboard_control ( ) { return _offboard_control ; } <nl> + control_t & combined_control ( ) { return _combined_control ; } <nl> + <nl> + void set_new_command ( bool val ) { _new_command = val ; } <nl> + <nl> + private : <nl> + CommonState * common_state ; <nl> + Params * params ; <nl> + Board * board ; <nl> + <nl> + control_t _rc_control ; <nl> + control_t _offboard_control ; <nl> + control_t _combined_control ; <nl> + <nl> + bool _new_command ; <nl> + <nl> + control_t _failsafe_control = { <nl> + { true , Mux : : control_type_t : : ANGLE , 0 . 0 } , <nl> + { true , Mux : : control_type_t : : ANGLE , 0 . 0 } , <nl> + { true , Mux : : control_type_t : : RATE , 0 . 0 } , <nl> + { true , Mux : : control_type_t : : THROTTLE , 0 . 0 } } ; <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + void Mux : : init ( CommonState * _common_state , Board * _board , Params * _params ) <nl> + { <nl> + params = _params ; <nl> + common_state = _common_state ; <nl> + board = _board ; <nl> + <nl> + } <nl> + <nl> + bool Mux : : mux_inputs ( ) <nl> + { <nl> + if ( ! _new_command ) <nl> + { <nl> + / / we haven ' t received any new commands , so we shouldn ' t do anything <nl> + return false ; <nl> + } <nl> + / / otherwise combine the new commands <nl> + <nl> + if ( common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_ARMED | | common_state - > get_armed_state ( ) = = CommonState : : FAILSAFE_DISARMED ) <nl> + { <nl> + _combined_control = _failsafe_control ; <nl> + } <nl> + else <nl> + { <nl> + if ( _rc_control . x . active ) <nl> + { <nl> + _combined_control . x = _rc_control . x ; <nl> + } <nl> + else if ( _offboard_control . x . active ) <nl> + { <nl> + _combined_control . x = _offboard_control . x ; <nl> + } <nl> + else <nl> + { <nl> + / / default to taking RC if neither is publishing <nl> + _combined_control . x = _rc_control . x ; <nl> + _combined_control . x . active = true ; <nl> + } <nl> + <nl> + <nl> + if ( _rc_control . y . active ) <nl> + { <nl> + _combined_control . y = _rc_control . y ; <nl> + } <nl> + else if ( _offboard_control . y . active ) <nl> + { <nl> + _combined_control . y = _offboard_control . y ; <nl> + } <nl> + else <nl> + { <nl> + / / default to taking RC if neither is publishing <nl> + _combined_control . y = _rc_control . y ; <nl> + _combined_control . y . active = true ; <nl> + } <nl> + <nl> + <nl> + if ( _rc_control . z . active ) <nl> + { <nl> + _combined_control . z = _rc_control . z ; <nl> + } <nl> + else if ( _offboard_control . z . active ) <nl> + { <nl> + _combined_control . z = _offboard_control . z ; <nl> + } <nl> + else <nl> + { <nl> + _combined_control . z = _rc_control . z ; <nl> + _combined_control . z . active = true ; <nl> + } <nl> + <nl> + if ( params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE ) ) <nl> + { <nl> + if ( _offboard_control . F . active ) <nl> + { <nl> + if ( _rc_control . F . type = = Mux : : control_type_t : : THROTTLE & & _offboard_control . F . type = = Mux : : control_type_t : : THROTTLE ) <nl> + { <nl> + _combined_control . F . value = ( _rc_control . F . value > _offboard_control . F . value ) ? <nl> + _offboard_control . F . value : _rc_control . F . value ; <nl> + _combined_control . F . type = Mux : : control_type_t : : THROTTLE ; <nl> + _combined_control . F . active = true ; <nl> + } <nl> + else <nl> + { <nl> + / / I ' m still not quite sure how to handle the mixed altitude / throttle cases <nl> + / / for now , just pass the rc along . I expect that what we really need to do <nl> + / / is run the altitude controller here so we can compare throttle to throttle <nl> + _combined_control . F = _rc_control . F ; <nl> + } <nl> + } <nl> + } <nl> + else / / no min throttle check <nl> + { <nl> + if ( _rc_control . F . active ) <nl> + { <nl> + _combined_control . F = _rc_control . F ; <nl> + } <nl> + else if ( _offboard_control . F . active ) <nl> + { <nl> + _combined_control . F = _offboard_control . F ; <nl> + } <nl> + else <nl> + { <nl> + _combined_control . F = _rc_control . F ; <nl> + _combined_control . F . active = true ; <nl> + } <nl> + } <nl> + <nl> + / / Light to indicate override <nl> + if ( _rc_control . x . active | | _rc_control . y . active | | _rc_control . z . active | | _rc_control . F . active ) <nl> + { <nl> + board - > set_led ( 0 , true ) ; <nl> + } <nl> + else <nl> + { <nl> + board - > set_led ( 0 , false ) ; <nl> + } <nl> + } <nl> + <nl> + / / reset the new command flag <nl> + _new_command = false ; <nl> + return true ; <nl> + } <nl> + <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 97 % <nl> rename from AirLib / include / controllers / rosflight / firmware / param . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / param . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / param . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / param . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdbool > <nl> - # include < cstdint > <nl> - # include " param . hpp " <nl> - # include " board . hpp " <nl> - # include " commlink . hpp " <nl> - # include " commonstate . hpp " <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Params { <nl> - public : <nl> - static constexpr uint8_t PARAMS_NAME_LENGTH = 15 ; <nl> - <nl> - typedef enum : uint16_t <nl> - { <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * HARDWARE CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_BOARD_REVISION = 0 , <nl> - PARAM_BAUD_RATE , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * COMM LINK CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_SYSTEM_ID , <nl> - PARAM_STREAM_HEARTBEAT_RATE , <nl> - <nl> - PARAM_STREAM_ATTITUDE_RATE , <nl> - PARAM_STREAM_IMU_RATE , <nl> - PARAM_STREAM_MAG_RATE , <nl> - PARAM_STREAM_BARO_RATE , <nl> - PARAM_STREAM_AIRSPEED_RATE , <nl> - PARAM_STREAM_GPS_RATE , <nl> - PARAM_STREAM_SONAR_RATE , <nl> - <nl> - PARAM_STREAM_SERVO_OUTPUT_RAW_RATE , <nl> - PARAM_STREAM_RC_RAW_RATE , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * CONTROLLER CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_MAX_COMMAND , <nl> - <nl> - PARAM_PID_ROLL_RATE_P , <nl> - PARAM_PID_ROLL_RATE_I , <nl> - PARAM_PID_ROLL_RATE_D , <nl> - PARAM_ROLL_RATE_TRIM , <nl> - PARAM_MAX_ROLL_RATE , <nl> - <nl> - PARAM_PID_PITCH_RATE_P , <nl> - PARAM_PID_PITCH_RATE_I , <nl> - PARAM_PID_PITCH_RATE_D , <nl> - PARAM_PITCH_RATE_TRIM , <nl> - PARAM_MAX_PITCH_RATE , <nl> - <nl> - PARAM_PID_YAW_RATE_P , <nl> - PARAM_PID_YAW_RATE_I , <nl> - PARAM_PID_YAW_RATE_D , <nl> - PARAM_YAW_RATE_TRIM , <nl> - PARAM_MAX_YAW_RATE , <nl> - <nl> - PARAM_PID_ROLL_ANGLE_P , <nl> - PARAM_PID_ROLL_ANGLE_I , <nl> - PARAM_PID_ROLL_ANGLE_D , <nl> - PARAM_ROLL_ANGLE_TRIM , <nl> - PARAM_MAX_ROLL_ANGLE , <nl> - <nl> - PARAM_PID_PITCH_ANGLE_P , <nl> - PARAM_PID_PITCH_ANGLE_I , <nl> - PARAM_PID_PITCH_ANGLE_D , <nl> - PARAM_PITCH_ANGLE_TRIM , <nl> - PARAM_MAX_PITCH_ANGLE , <nl> - <nl> - PARAM_PID_ALT_P , <nl> - PARAM_PID_ALT_I , <nl> - PARAM_PID_ALT_D , <nl> - PARAM_HOVER_THROTTLE , <nl> - <nl> - PARAM_PID_TAU , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * PWM CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_MOTOR_PWM_SEND_RATE , <nl> - PARAM_MOTOR_IDLE_PWM , <nl> - PARAM_SPIN_MOTORS_WHEN_ARMED , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * ESTIMATOR CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_INIT_TIME , <nl> - PARAM_FILTER_KP , <nl> - PARAM_FILTER_KI , <nl> - <nl> - PARAM_GYRO_ALPHA , <nl> - PARAM_ACC_ALPHA , <nl> - <nl> - PARAM_ACCEL_SCALE , <nl> - <nl> - PARAM_GYRO_X_BIAS , <nl> - PARAM_GYRO_Y_BIAS , <nl> - PARAM_GYRO_Z_BIAS , <nl> - PARAM_ACC_X_BIAS , <nl> - PARAM_ACC_Y_BIAS , <nl> - PARAM_ACC_Z_BIAS , <nl> - PARAM_ACC_X_TEMP_COMP , <nl> - PARAM_ACC_Y_TEMP_COMP , <nl> - PARAM_ACC_Z_TEMP_COMP , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * RC CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_RC_TYPE , <nl> - PARAM_RC_X_CHANNEL , <nl> - PARAM_RC_Y_CHANNEL , <nl> - PARAM_RC_Z_CHANNEL , <nl> - PARAM_RC_F_CHANNEL , <nl> - PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL , <nl> - PARAM_RC_THROTTLE_OVERRIDE_CHANNEL , <nl> - PARAM_RC_ATT_CONTROL_TYPE_CHANNEL , <nl> - PARAM_RC_F_CONTROL_TYPE_CHANNEL , <nl> - PARAM_RC_NUM_CHANNELS , <nl> - <nl> - PARAM_RC_X_CENTER , <nl> - PARAM_RC_Y_CENTER , <nl> - PARAM_RC_Z_CENTER , <nl> - PARAM_RC_F_BOTTOM , <nl> - PARAM_RC_X_RANGE , <nl> - PARAM_RC_Y_RANGE , <nl> - PARAM_RC_Z_RANGE , <nl> - PARAM_RC_F_RANGE , <nl> - PARAM_RC_SWITCH_5_DIRECTION , <nl> - PARAM_RC_SWITCH_6_DIRECTION , <nl> - PARAM_RC_SWITCH_7_DIRECTION , <nl> - PARAM_RC_SWITCH_8_DIRECTION , <nl> - <nl> - PARAM_RC_OVERRIDE_DEVIATION , <nl> - PARAM_OVERRIDE_LAG_TIME , <nl> - PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE , <nl> - <nl> - PARAM_RC_MAX_ROLL , <nl> - PARAM_RC_MAX_PITCH , <nl> - PARAM_RC_MAX_ROLLRATE , <nl> - PARAM_RC_MAX_PITCHRATE , <nl> - PARAM_RC_MAX_YAWRATE , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * FRAME CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_MIXER , <nl> - <nl> - PARAM_FIXED_WING , <nl> - PARAM_ELEVATOR_REVERSE , <nl> - PARAM_AILERON_REVERSE , <nl> - PARAM_RUDDER_REVERSE , <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * ARMING SETUP * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * / <nl> - PARAM_ARM_STICKS , <nl> - PARAM_ARM_CHANNEL , <nl> - PARAM_ARM_THRESHOLD , <nl> - <nl> - / / keep track of size of params array <nl> - PARAMS_COUNT <nl> - } param_id_t ; <nl> - <nl> - typedef enum <nl> - { <nl> - PARAM_TYPE_INT32 , <nl> - PARAM_TYPE_FLOAT , <nl> - PARAM_TYPE_INVALID <nl> - } param_type_t ; <nl> - <nl> - / / function declarations <nl> - / * * <nl> - * @ brief Initialize parameter values <nl> - * / <nl> - void init ( Board * _board , CommLink * _comm_link ) ; <nl> - <nl> - / * * <nl> - * @ brief Set all parameters to default values <nl> - * / <nl> - void set_param_defaults ( void ) ; <nl> - <nl> - / * * <nl> - * @ brief Read parameter values from non - volatile memory <nl> - * @ return True if successful , false otherwise <nl> - * / <nl> - bool read_params ( void ) ; <nl> - <nl> - / * * <nl> - * @ brief Write current parameter values to non - volatile memory <nl> - * @ return True if successful , false otherwise <nl> - * / <nl> - bool write_params ( void ) ; <nl> - <nl> - / * * <nl> - * @ brief Callback for executing actions that need to be taken when a parameter value changes <nl> - * @ param id The ID of the parameter that was changed <nl> - * / <nl> - void param_change_callback ( param_id_t id ) ; <nl> - <nl> - / * * <nl> - * @ brief Gets the id of a parameter from its name <nl> - * @ param name The name of the parameter <nl> - * @ return The ID of the parameter if the name is valid , PARAMS_COUNT otherwise ( invalid ID ) <nl> - * / <nl> - param_id_t lookup_param_id ( const char name [ PARAMS_NAME_LENGTH ] ) ; <nl> - <nl> - / * * <nl> - * @ brief Get the value of an integer parameter by id <nl> - * @ param id The ID of the parameter <nl> - * @ return The value of the parameter <nl> - * / <nl> - int get_param_int ( param_id_t id ) ; <nl> - <nl> - / * * <nl> - * @ brief Get the value of a floating point parameter by id <nl> - * @ param id The ID of the parameter <nl> - * @ return The value of the parameter <nl> - * / <nl> - float get_param_float ( param_id_t id ) ; <nl> - <nl> - / * * <nl> - * @ brief Get the name of a parameter <nl> - * @ param id The ID of the parameter <nl> - * @ return The name of the parameter <nl> - * / <nl> - char * get_param_name ( param_id_t id ) ; <nl> - <nl> - / * * <nl> - * @ brief Get the type of a parameter <nl> - * @ param id The ID of the parameter <nl> - * @ return The type of the parameter <nl> - * This returns one of three possible types <nl> - * PARAM_TYPE_INT32 , PARAM_TYPE_FLOAT , or PARAM_TYPE_INVALID <nl> - * See line 165 <nl> - * / <nl> - param_type_t get_param_type ( param_id_t id ) ; <nl> - <nl> - / * * <nl> - * @ brief Sets the value of a parameter by ID and calls the parameter change callback <nl> - * @ param id The ID of the parameter <nl> - * @ param value The new value <nl> - * @ return True if a parameter value was changed , false otherwise <nl> - * / <nl> - bool set_param_int ( param_id_t id , int32_t value ) ; <nl> - <nl> - / * * <nl> - * @ brief Sets the value of a floating point parameter by ID and calls the parameter callback <nl> - * @ param id The ID of the parameter <nl> - * @ param value The new value <nl> - * @ return True if a parameter was changed , false otherwise <nl> - * / <nl> - bool set_param_float ( param_id_t id , float value ) ; <nl> - <nl> - / * * <nl> - * @ brief Sets the value of a parameter by name and calls the parameter change callback <nl> - * @ param name The name of the parameter <nl> - * @ param value The new value <nl> - * @ return True if a parameter value was changed , false otherwise <nl> - * / <nl> - bool set_param_by_name_int ( const char name [ PARAMS_NAME_LENGTH ] , int32_t value ) ; <nl> - <nl> - / * * <nl> - * @ brief Sets the value of a floating point parameter by name and calls the parameter change callback <nl> - * @ param name The name of the parameter <nl> - * @ param value The new value <nl> - * @ return True if a parameter value was changed , false otherwise <nl> - * / <nl> - bool set_param_by_name_float ( const char name [ PARAMS_NAME_LENGTH ] , float value ) ; <nl> - <nl> - private : <nl> - void init_param_int ( param_id_t id , const char name [ PARAMS_NAME_LENGTH ] , int32_t value ) ; <nl> - void init_param_float ( param_id_t id , const char name [ PARAMS_NAME_LENGTH ] , float value ) ; <nl> - <nl> - <nl> - private : <nl> - / / type definitions <nl> - typedef struct <nl> - { <nl> - uint8_t version ; <nl> - uint16_t size ; <nl> - uint8_t magic_be ; / / magic number , should be 0xBE <nl> - <nl> - int32_t values [ PARAMS_COUNT ] ; <nl> - char names [ PARAMS_COUNT ] [ PARAMS_NAME_LENGTH ] ; <nl> - param_type_t types [ PARAMS_COUNT ] ; <nl> - <nl> - uint8_t magic_ef ; / / magic number , should be 0xEF <nl> - uint8_t chk ; / / XOR checksum <nl> - } params_t ; <nl> - <nl> - params_t _params ; <nl> - Board * board ; <nl> - CommLink * comm_link ; <nl> - <nl> - } ; <nl> - <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - <nl> - / / function definitions <nl> - void Params : : init ( Board * _board , CommLink * _comm_link ) <nl> - { <nl> - board = _board ; <nl> - comm_link = _comm_link ; <nl> - <nl> - for ( uint8_t i = 0 ; i < PARAMS_COUNT ; i + + ) <nl> - { <nl> - init_param_int ( static_cast < param_id_t > ( i ) , " DEFAULT " , 0 ) ; <nl> - } <nl> - board - > init_params ( ) ; <nl> - if ( ! read_params ( ) ) <nl> - { <nl> - set_param_defaults ( ) ; <nl> - write_params ( ) ; <nl> - } <nl> - <nl> - for ( uint16_t id = 0 ; id < PARAMS_COUNT ; id + + ) <nl> - param_change_callback ( ( param_id_t ) id ) ; <nl> - } <nl> - <nl> - / / local function definitions <nl> - void Params : : init_param_int ( Params : : param_id_t id , const char name [ Params : : PARAMS_NAME_LENGTH ] , int32_t value ) <nl> - { <nl> - memcpy ( _params . names [ id ] , name , PARAMS_NAME_LENGTH ) ; <nl> - _params . values [ id ] = value ; <nl> - _params . types [ id ] = PARAM_TYPE_INT32 ; <nl> - } <nl> - <nl> - void Params : : init_param_float ( Params : : param_id_t id , const char name [ Params : : PARAMS_NAME_LENGTH ] , float value ) <nl> - { <nl> - memcpy ( _params . names [ id ] , name , PARAMS_NAME_LENGTH ) ; <nl> - _params . values [ id ] = * ( ( int32_t * ) & value ) ; <nl> - _params . types [ id ] = PARAM_TYPE_FLOAT ; <nl> - } <nl> - <nl> - void Params : : set_param_defaults ( void ) <nl> - { <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * HARDWARE CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_BOARD_REVISION , " BOARD_REV " , 2 ) ; / / Major board revision of naze32 / flip32 | 1 | 6 <nl> - init_param_int ( PARAM_BAUD_RATE , " BAUD_RATE " , 921600 ) ; / / Baud rate of communication with onboard computer | 9600 | 921600 <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * MAVLINK CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_SYSTEM_ID , " SYS_ID " , 1 ) ; / / Mavlink System ID | 1 | 255 <nl> - init_param_int ( PARAM_STREAM_HEARTBEAT_RATE , " STRM_HRTBT " , 1 ) ; / / Rate of heartbeat streaming ( Hz ) | 0 | 1000 <nl> - <nl> - init_param_int ( PARAM_STREAM_ATTITUDE_RATE , " STRM_ATTITUDE " , 100 ) ; / / Rate of attitude stream ( Hz ) | 0 | 1000 <nl> - init_param_int ( PARAM_STREAM_IMU_RATE , " STRM_IMU " , 500 ) ; / / Rate of IMU stream ( Hz ) | 0 | 1000 <nl> - init_param_int ( PARAM_STREAM_MAG_RATE , " STRM_MAG " , 75 ) ; / / Rate of magnetometer stream ( Hz ) | 0 | 75 <nl> - init_param_int ( PARAM_STREAM_BARO_RATE , " STRM_BARO " , 100 ) ; / / Rate of barometer stream ( Hz ) | 0 | 100 <nl> - init_param_int ( PARAM_STREAM_AIRSPEED_RATE , " STRM_AIRSPEED " , 20 ) ; / / Rate of airspeed stream ( Hz ) | 0 | 50 <nl> - init_param_int ( PARAM_STREAM_GPS_RATE , " STRM_GPS " , 0 ) ; / / Rate of GPS stream ( Hz ) | 0 | 1 <nl> - init_param_int ( PARAM_STREAM_SONAR_RATE , " STRM_SONAR " , 40 ) ; / / Rate of sonar stream ( Hz ) | 0 | 40 <nl> - <nl> - init_param_int ( PARAM_STREAM_SERVO_OUTPUT_RAW_RATE , " STRM_SERVO " , 50 ) ; / / Rate of raw output stream | 0 | 490 <nl> - init_param_int ( PARAM_STREAM_RC_RAW_RATE , " STRM_RC " , 50 ) ; / / Rate of raw RC input stream | 0 | 50 <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * CONTROLLER CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_MAX_COMMAND , " PARAM_MAX_CMD " , 1000 ) ; / / saturation point for PID controller output | 0 | 1000 <nl> - <nl> - init_param_float ( PARAM_PID_ROLL_RATE_P , " PID_ROLL_RATE_P " , 0 . 070f ) ; / / Roll Rate Proportional Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_ROLL_RATE_I , " PID_ROLL_RATE_I " , 0 . 000f ) ; / / Roll Rate Integral Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_ROLL_RATE_D , " PID_ROLL_RATE_D " , 0 . 000f ) ; / / Rall Rate Derivative Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_ROLL_RATE_TRIM , " ROLL_RATE_TRIM " , 0 . 0f ) ; / / Roll Rate Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_MAX_ROLL_RATE , " MAX_ROLL_RATE " , 3 . 14159f ) ; / / Maximum Roll Rate command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> - <nl> - init_param_float ( PARAM_PID_PITCH_RATE_P , " PID_PITCH_RATE_P " , 0 . 070f ) ; / / Pitch Rate Proporitional Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_PITCH_RATE_I , " PID_PITCH_RATE_I " , 0 . 0000f ) ; / / Pitch Rate Integral Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_PITCH_RATE_D , " PID_PITCH_RATE_D " , 0 . 0000f ) ; / / Pitch Rate Derivative Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PITCH_RATE_TRIM , " PITCH_RATE_TRIM " , 0 . 0f ) ; / / Pitch Rate Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_MAX_PITCH_RATE , " MAX_PITCH_RATE " , 3 . 14159f ) ; / / Maximum Pitch Rate command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> - <nl> - init_param_float ( PARAM_PID_YAW_RATE_P , " PID_YAW_RATE_P " , 0 . 25f ) ; / / Yaw Rate Proporitional Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_YAW_RATE_I , " PID_YAW_RATE_I " , 0 . 0f ) ; / / Yaw Rate Integral Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_YAW_RATE_D , " PID_YAW_RATE_D " , 0 . 0f ) ; / / Yaw Rate Derivative Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_YAW_RATE_TRIM , " YAW_RATE_TRIM " , 0 . 0f ) ; / / Yaw Rate Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_MAX_YAW_RATE , " MAX_YAW_RATE " , 6 . 283f ) ; / / Maximum Yaw Rate command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> - <nl> - init_param_float ( PARAM_PID_ROLL_ANGLE_P , " PID_ROLL_ANG_P " , 0 . 15f ) ; / / Roll Angle Proporitional Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_ROLL_ANGLE_I , " PID_ROLL_ANG_I " , 0 . 0f ) ; / / Roll Angle Integral Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_ROLL_ANGLE_D , " PID_ROLL_ANG_D " , 0 . 07f ) ; / / Roll Angle Derivative Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_ROLL_ANGLE_TRIM , " ROLL_TRIM " , 0 . 0f ) ; / / Roll Angle Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_MAX_ROLL_ANGLE , " MAX_ROLL_ANG " , 0 . 786f ) ; / / Maximum Roll Angle command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> - <nl> - init_param_float ( PARAM_PID_PITCH_ANGLE_P , " PID_PITCH_ANG_P " , 0 . 15f ) ; / / Pitch Angle Proporitional Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_PITCH_ANGLE_I , " PID_PITCH_ANG_I " , 0 . 0f ) ; / / Pitch Angle Integral Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_PITCH_ANGLE_D , " PID_PITCH_ANG_D " , 0 . 07f ) ; / / Pitch Angle Derivative Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PITCH_ANGLE_TRIM , " PITCH_TRIM " , 0 . 0f ) ; / / Pitch Angle Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_MAX_PITCH_ANGLE , " MAX_PITCH_ANG " , 0 . 786f ) ; / / Maximum Pitch Angle command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> - <nl> - init_param_float ( PARAM_PID_ALT_P , " PID_ALT_P " , 0 . 0f ) ; / / Altitude Proporitional Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_ALT_I , " PID_ALT_I " , 0 . 0f ) ; / / Altitude Integral Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_PID_ALT_D , " PID_ALT_D " , 0 . 0f ) ; / / Altitude Derivative Gain | 0 . 0 | 1000 . 0 <nl> - init_param_float ( PARAM_HOVER_THROTTLE , " HOVER_THR " , 0 . 5 ) ; / / Hover Throttle - See RC calibration | 0 . 0 | 1 . 0 <nl> - <nl> - init_param_float ( PARAM_PID_TAU , " PID_TAU " , 0 . 05f ) ; / / Dirty Derivative time constant - See controller documentation | 0 . 0 | 1 . 0 <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * PWM CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_MOTOR_PWM_SEND_RATE , " MOTOR_PWM_UPDATE " , 490 ) ; / / Refresh rate of motor commands to motors - See motor documentation | 0 | 1000 <nl> - init_param_int ( PARAM_MOTOR_IDLE_PWM , " MOTOR_IDLE_PWM " , 1100 ) ; / / Idle PWM sent to motors at zero throttle ( Set above 1100 to spin when armed ) | 1000 | 2000 <nl> - init_param_int ( PARAM_SPIN_MOTORS_WHEN_ARMED , " ARM_SPIN_MOTORS " , true ) ; / / Enforce MOTOR_IDLE_PWM | 0 | 1 <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * ESTIMATOR CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_INIT_TIME , " FILTER_INIT_T " , 3000 ) ; / / Time in ms to initialize estimator | 0 | 100000 <nl> - init_param_float ( PARAM_FILTER_KP , " FILTER_KP " , 1 . 0f ) ; / / estimator proportional gain - See estimator documentation | 0 | 10 . 0 <nl> - init_param_float ( PARAM_FILTER_KI , " FILTER_KI " , 0 . 1f ) ; / / estimator integral gain - See estimator documentation | 0 | 1 . 0 <nl> - <nl> - init_param_float ( PARAM_GYRO_ALPHA , " GYRO_LPF_ALPHA " , 0 . 888f ) ; / / Low - pass filter constant - See estimator documentation | 0 | 1 . 0 <nl> - init_param_float ( PARAM_ACC_ALPHA , " ACC_LPF_ALPHA " , 0 . 888f ) ; / / Low - pass filter constant - See estimator documentation | 0 | 1 . 0 <nl> - <nl> - init_param_float ( PARAM_ACCEL_SCALE , " ACCEL_SCALE " , 1 . 0f ) ; / / Scale factor to apply to IMU measurements - Read - Only | 0 . 5 | 2 . 0 <nl> - <nl> - init_param_float ( PARAM_GYRO_X_BIAS , " GYRO_X_BIAS " , 0 . 0f ) ; / / Constant x - bias of gyroscope readings | - 1 . 0 | 1 . 0 <nl> - init_param_float ( PARAM_GYRO_Y_BIAS , " GYRO_Y_BIAS " , 0 . 0f ) ; / / Constant y - bias of gyroscope readings | - 1 . 0 | 1 . 0 <nl> - init_param_float ( PARAM_GYRO_Z_BIAS , " GYRO_Z_BIAS " , 0 . 0f ) ; / / Constant z - bias of gyroscope readings | - 1 . 0 | 1 . 0 <nl> - init_param_float ( PARAM_ACC_X_BIAS , " ACC_X_BIAS " , 0 . 0f ) ; / / Constant x - bias of accelerometer readings | - 2 . 0 | 2 . 0 <nl> - init_param_float ( PARAM_ACC_Y_BIAS , " ACC_Y_BIAS " , 0 . 0f ) ; / / Constant y - bias of accelerometer readings | - 2 . 0 | 2 . 0 <nl> - init_param_float ( PARAM_ACC_Z_BIAS , " ACC_Z_BIAS " , 0 . 0f ) ; / / Constant z - bias of accelerometer readings | - 2 . 0 | 2 . 0 <nl> - init_param_float ( PARAM_ACC_X_TEMP_COMP , " ACC_X_TEMP_COMP " , 0 . 0f ) ; / / Linear x - axis temperature compensation constant | - 2 . 0 | 2 . 0 <nl> - init_param_float ( PARAM_ACC_Y_TEMP_COMP , " ACC_Y_TEMP_COMP " , 0 . 0f ) ; / / Linear y - axis temperature compensation constant | - 2 . 0 | 2 . 0 <nl> - init_param_float ( PARAM_ACC_Z_TEMP_COMP , " ACC_Z_TEMP_COMP " , 0 . 0f ) ; / / Linear z - axis temperature compensation constant | - 2 . 0 | 2 . 0 <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * RC CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_RC_TYPE , " RC_TYPE " , 1 ) ; / / Type of RC input 0 - Parallel PWM ( PWM ) , 1 - Pulse - Position Modulation ( PPM ) | 0 | 1 <nl> - init_param_int ( PARAM_RC_X_CHANNEL , " RC_X_CHN " , 0 ) ; / / RC input channel mapped to x - axis commands [ 0 - indexed ] | 0 | 3 <nl> - init_param_int ( PARAM_RC_Y_CHANNEL , " RC_Y_CHN " , 1 ) ; / / RC input channel mapped to y - axis commands [ 0 - indexed ] | 0 | 3 <nl> - init_param_int ( PARAM_RC_Z_CHANNEL , " RC_Z_CHN " , 3 ) ; / / RC input channel mapped to z - axis commands [ 0 - indexed ] | 0 | 3 <nl> - init_param_int ( PARAM_RC_F_CHANNEL , " RC_F_CHN " , 2 ) ; / / RC input channel mapped to F - axis commands [ 0 - indexed ] | 0 | 3 <nl> - init_param_int ( PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL , " RC_ATT_OVRD_CHN " , 4 ) ; / / RC switch mapped to attitude override [ 0 - indexed ] | 4 | 7 <nl> - init_param_int ( PARAM_RC_THROTTLE_OVERRIDE_CHANNEL , " RC_THR_OVRD_CHN " , 5 ) ; / / RC switch hannel mapped to throttle override [ 0 - indexed ] | 4 | 7 <nl> - init_param_int ( PARAM_RC_ATT_CONTROL_TYPE_CHANNEL , " RC_ATT_CTRL_CHN " , 6 ) ; / / RC switch channel mapped to attitude control type [ 0 - indexed ] | 4 | 7 <nl> - init_param_int ( PARAM_RC_F_CONTROL_TYPE_CHANNEL , " RC_F_CTRL_CHN " , 7 ) ; / / RC switch channel mapped to throttle control type override [ 0 - indexed ] | 4 | 7 <nl> - init_param_int ( PARAM_RC_NUM_CHANNELS , " RC_NUM_CHN " , 9 ) ; / / number of RC input channels | 1 | 8 <nl> - <nl> - init_param_int ( PARAM_RC_X_CENTER , " RC_X_CENTER " , 1500 ) ; / / RC calibration x - axis center ( us ) | 1000 | 2000 <nl> - init_param_int ( PARAM_RC_Y_CENTER , " RC_Y_CENTER " , 1500 ) ; / / RC calibration y - axis center ( us ) | 1000 | 2000 <nl> - init_param_int ( PARAM_RC_Z_CENTER , " RC_Z_CENTER " , 1500 ) ; / / RC calibration z - axis center ( us ) | 1000 | 2000 <nl> - init_param_int ( PARAM_RC_F_BOTTOM , " RC_F_BOTTOM " , 1000 ) ; / / RC calibration F - axis center ( us ) | 1000 | 2000 <nl> - init_param_int ( PARAM_RC_X_RANGE , " RC_X_RANGE " , 1000 ) ; / / RC calibration x - axis range ( us ) | 500 | 2500 <nl> - init_param_int ( PARAM_RC_Y_RANGE , " RC_Y_RANGE " , 1000 ) ; / / RC calibration y - axis range ( us ) | 500 | 2500 <nl> - init_param_int ( PARAM_RC_Z_RANGE , " RC_Z_RANGE " , 1000 ) ; / / RC calibration z - axis range ( us ) | 500 | 2500 <nl> - init_param_int ( PARAM_RC_F_RANGE , " RC_F_RANGE " , 1000 ) ; / / RC calibration F - axis range ( us ) | 500 | 2500 <nl> - init_param_int ( PARAM_RC_SWITCH_5_DIRECTION , " SWITCH_5_DIR " , 1 ) ; / / RC switch 5 toggle direction | 0 | 1 <nl> - init_param_int ( PARAM_RC_SWITCH_6_DIRECTION , " SWITCH_6_DIR " , 1 ) ; / / RC switch 6 toggle direction | 0 | 1 <nl> - init_param_int ( PARAM_RC_SWITCH_7_DIRECTION , " SWITCH_7_DIR " , 1 ) ; / / RC switch 7 toggle direction | 0 | 1 <nl> - init_param_int ( PARAM_RC_SWITCH_8_DIRECTION , " SWITCH_8_DIR " , 1 ) ; / / RC switch 8 toggle direction | 0 | 1 <nl> - <nl> - init_param_int ( PARAM_RC_OVERRIDE_DEVIATION , " RC_OVRD_DEV " , 100 ) ; / / RC stick deviation from center for overrride ( us ) | 0 | 1000 <nl> - init_param_int ( PARAM_OVERRIDE_LAG_TIME , " OVRD_LAG_TIME " , 1000 ) ; / / RC stick deviation lag time before returning control ( ms ) | 0 | 100000 <nl> - init_param_int ( PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE , " MIN_THROTTLE " , false ) ; / / Take minimum throttle between RC and computer at all times | 0 | 1 <nl> - <nl> - init_param_float ( PARAM_RC_MAX_ROLL , " RC_MAX_ROLL " , 0 . 786f ) ; / / Maximum roll angle command sent by full deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> - init_param_float ( PARAM_RC_MAX_PITCH , " RC_MAX_PITCH " , 0 . 786f ) ; / / Maximum pitch angle command sent by full stick deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> - init_param_float ( PARAM_RC_MAX_ROLLRATE , " RC_MAX_ROLLRATE " , 3 . 14159f ) ; / / Maximum roll rate command sent by full stick deflection of RC sticks | 0 . 0 | 9 . 42477796077 <nl> - init_param_float ( PARAM_RC_MAX_PITCHRATE , " RC_MAX_PITCHRATE " , 3 . 14159f ) ; / / Maximum pitch command sent by full stick deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> - init_param_float ( PARAM_RC_MAX_YAWRATE , " RC_MAX_YAWRATE " , 0 . 786f ) ; / / Maximum pitch command sent by full stick deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * FRAME CONFIGURATION * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_MIXER , " MIXER " , 1 ) ; / / Which mixer to choose , 1 = QUADCOPTER_X - See Mixer documentation | 0 | 5 <nl> - <nl> - init_param_int ( PARAM_FIXED_WING , " FIXED_WING " , false ) ; / / switches on passthrough commands for fixedwing operation | 0 | 1 <nl> - init_param_int ( PARAM_ELEVATOR_REVERSE , " ELEVATOR_REV " , 0 ) ; / / reverses elevator servo output | 0 | 1 <nl> - init_param_int ( PARAM_AILERON_REVERSE , " AIL_REV " , 0 ) ; / / reverses aileron servo output | 0 | 1 <nl> - init_param_int ( PARAM_RUDDER_REVERSE , " RUDDER_REV " , 0 ) ; / / reverses rudder servo output | 0 | 1 <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * ARMING SETUP * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * / <nl> - init_param_int ( PARAM_ARM_STICKS , " ARM_STICKS " , false ) ; / / use RC sticks to arm vehicle ( disables arm RC switch if enabled ) | 0 | 1 <nl> - init_param_int ( PARAM_ARM_CHANNEL , " ARM_CHANNEL " , 4 ) ; / / RC switch mapped to arm / disarm [ 0 - indexed ] | 4 | 7 <nl> - init_param_int ( PARAM_ARM_THRESHOLD , " ARM_THRESHOLD " , 150 ) ; / / RC deviation from max / min in yaw and throttle for arming and disarming check ( us ) | 0 | 500 <nl> - } <nl> - <nl> - bool Params : : read_params ( void ) <nl> - { <nl> - return board - > read_params ( ) ; <nl> - } <nl> - <nl> - bool Params : : write_params ( void ) <nl> - { <nl> - return board - > write_params ( true ) ; <nl> - } <nl> - <nl> - void Params : : param_change_callback ( param_id_t id ) <nl> - { <nl> - switch ( id ) <nl> - { <nl> - case PARAM_SYSTEM_ID : <nl> - comm_link - > set_sys_id ( get_param_int ( PARAM_SYSTEM_ID ) ) ; <nl> - break ; <nl> - case PARAM_STREAM_HEARTBEAT_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_HEARTBEAT_RATE , get_param_int ( PARAM_STREAM_HEARTBEAT_RATE ) ) ; <nl> - break ; <nl> - <nl> - case PARAM_STREAM_ATTITUDE_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_ATTITUDE_RATE , get_param_int ( PARAM_STREAM_ATTITUDE_RATE ) ) ; <nl> - break ; <nl> - <nl> - case PARAM_STREAM_IMU_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_IMU_RATE , get_param_int ( PARAM_STREAM_IMU_RATE ) ) ; <nl> - break ; <nl> - case PARAM_STREAM_AIRSPEED_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_AIRSPEED_RATE , get_param_int ( PARAM_STREAM_AIRSPEED_RATE ) ) ; <nl> - break ; <nl> - case PARAM_STREAM_SONAR_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_SONAR_RATE , get_param_int ( PARAM_STREAM_SONAR_RATE ) ) ; <nl> - break ; <nl> - case PARAM_STREAM_BARO_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_BARO_RATE , get_param_int ( PARAM_STREAM_BARO_RATE ) ) ; <nl> - break ; <nl> - case PARAM_STREAM_MAG_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_MAG_RATE , get_param_int ( PARAM_STREAM_MAG_RATE ) ) ; <nl> - break ; <nl> - <nl> - case PARAM_STREAM_SERVO_OUTPUT_RAW_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_SERVO_OUTPUT_RAW_RATE , get_param_int ( PARAM_STREAM_SERVO_OUTPUT_RAW_RATE ) ) ; <nl> - break ; <nl> - case PARAM_STREAM_RC_RAW_RATE : <nl> - comm_link - > set_streaming_rate ( PARAM_STREAM_RC_RAW_RATE , get_param_int ( PARAM_STREAM_RC_RAW_RATE ) ) ; <nl> - break ; <nl> - <nl> - / / information messages <nl> - case PARAM_RC_TYPE : <nl> - comm_link - > log_message ( CommonState : : stringf ( " RC type = % i " , get_param_int ( PARAM_RC_TYPE ) ) . c_str ( ) , 0 ) ; <nl> - case PARAM_MIXER : <nl> - comm_link - > log_message ( CommonState : : stringf ( " Mixer = % i " , get_param_int ( PARAM_MIXER ) ) . c_str ( ) , 0 ) ; <nl> - case PARAM_FIXED_WING : <nl> - comm_link - > log_message ( CommonState : : stringf ( " Fixed wing = % i " , get_param_int ( PARAM_FIXED_WING ) ) . c_str ( ) , 0 ) ; <nl> - case PARAM_ARM_STICKS : <nl> - comm_link - > log_message ( CommonState : : stringf ( " Can use RC to arm = % i " , get_param_int ( PARAM_ARM_STICKS ) ) . c_str ( ) , 0 ) ; <nl> - <nl> - <nl> - / / TODO : need better design so components can listen to their param changes <nl> - / / case PARAM_RC_TYPE : <nl> - / / mixer - > init_PWM ( ) ; <nl> - / / break ; <nl> - / / case PARAM_MOTOR_PWM_SEND_RATE : <nl> - / / mixer - > init_PWM ( ) ; <nl> - / / break ; <nl> - / / case PARAM_MIXER : <nl> - / / mixer - > init ( common_state ) ; <nl> - / / break ; <nl> - <nl> - default : <nl> - / / no action needed for this parameter <nl> - break ; <nl> - } <nl> - } <nl> - <nl> - Params : : param_id_t Params : : lookup_param_id ( const char name [ PARAMS_NAME_LENGTH ] ) <nl> - { <nl> - for ( uint16_t id = 0 ; id < PARAMS_COUNT ; id + + ) <nl> - { <nl> - bool match = true ; <nl> - for ( uint8_t i = 0 ; i < PARAMS_NAME_LENGTH ; i + + ) <nl> - { <nl> - / / compare each character <nl> - if ( name [ i ] ! = _params . names [ id ] [ i ] ) <nl> - { <nl> - match = false ; <nl> - break ; <nl> - } <nl> - <nl> - / / stop comparing if end of string is reached <nl> - if ( _params . names [ id ] [ i ] = = ' \ 0 ' ) <nl> - break ; <nl> - } <nl> - <nl> - if ( match ) <nl> - return ( param_id_t ) id ; <nl> - } <nl> - <nl> - return PARAMS_COUNT ; <nl> - } <nl> - <nl> - int Params : : get_param_int ( param_id_t id ) <nl> - { <nl> - return _params . values [ id ] ; <nl> - } <nl> - <nl> - float Params : : get_param_float ( param_id_t id ) <nl> - { <nl> - return * ( float * ) & _params . values [ id ] ; <nl> - } <nl> - <nl> - char * Params : : get_param_name ( param_id_t id ) <nl> - { <nl> - return _params . names [ id ] ; <nl> - } <nl> - <nl> - Params : : param_type_t Params : : get_param_type ( param_id_t id ) <nl> - { <nl> - return _params . types [ id ] ; <nl> - } <nl> - <nl> - bool Params : : set_param_int ( param_id_t id , int32_t value ) <nl> - { <nl> - if ( id < PARAMS_COUNT & & value ! = _params . values [ id ] ) <nl> - { <nl> - _params . values [ id ] = value ; <nl> - param_change_callback ( id ) ; <nl> - comm_link - > notify_param_change ( id , value ) ; <nl> - return true ; <nl> - } <nl> - return false ; <nl> - } <nl> - <nl> - bool Params : : set_param_float ( param_id_t id , float value ) <nl> - { <nl> - return set_param_int ( id , * ( int32_t * ) & value ) ; <nl> - } <nl> - <nl> - bool Params : : set_param_by_name_int ( const char name [ PARAMS_NAME_LENGTH ] , int32_t value ) <nl> - { <nl> - param_id_t id = lookup_param_id ( name ) ; <nl> - return set_param_int ( id , value ) ; <nl> - } <nl> - <nl> - bool Params : : set_param_by_name_float ( const char name [ PARAMS_NAME_LENGTH ] , float value ) <nl> - { <nl> - return set_param_by_name_int ( name , * ( int32_t * ) & value ) ; <nl> - } <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include < cstdbool > <nl> + # include < cstdint > <nl> + # include " param . hpp " <nl> + # include " board . hpp " <nl> + # include " commlink . hpp " <nl> + # include " commonstate . hpp " <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Params { <nl> + public : <nl> + static constexpr uint8_t PARAMS_NAME_LENGTH = 15 ; <nl> + <nl> + typedef enum : uint16_t <nl> + { <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * HARDWARE CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_BOARD_REVISION = 0 , <nl> + PARAM_BAUD_RATE , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * COMM LINK CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_SYSTEM_ID , <nl> + PARAM_STREAM_HEARTBEAT_RATE , <nl> + <nl> + PARAM_STREAM_ATTITUDE_RATE , <nl> + PARAM_STREAM_IMU_RATE , <nl> + PARAM_STREAM_MAG_RATE , <nl> + PARAM_STREAM_BARO_RATE , <nl> + PARAM_STREAM_AIRSPEED_RATE , <nl> + PARAM_STREAM_GPS_RATE , <nl> + PARAM_STREAM_SONAR_RATE , <nl> + <nl> + PARAM_STREAM_SERVO_OUTPUT_RAW_RATE , <nl> + PARAM_STREAM_RC_RAW_RATE , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * CONTROLLER CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_MAX_COMMAND , <nl> + <nl> + PARAM_PID_ROLL_RATE_P , <nl> + PARAM_PID_ROLL_RATE_I , <nl> + PARAM_PID_ROLL_RATE_D , <nl> + PARAM_ROLL_RATE_TRIM , <nl> + PARAM_MAX_ROLL_RATE , <nl> + <nl> + PARAM_PID_PITCH_RATE_P , <nl> + PARAM_PID_PITCH_RATE_I , <nl> + PARAM_PID_PITCH_RATE_D , <nl> + PARAM_PITCH_RATE_TRIM , <nl> + PARAM_MAX_PITCH_RATE , <nl> + <nl> + PARAM_PID_YAW_RATE_P , <nl> + PARAM_PID_YAW_RATE_I , <nl> + PARAM_PID_YAW_RATE_D , <nl> + PARAM_YAW_RATE_TRIM , <nl> + PARAM_MAX_YAW_RATE , <nl> + <nl> + PARAM_PID_ROLL_ANGLE_P , <nl> + PARAM_PID_ROLL_ANGLE_I , <nl> + PARAM_PID_ROLL_ANGLE_D , <nl> + PARAM_ROLL_ANGLE_TRIM , <nl> + PARAM_MAX_ROLL_ANGLE , <nl> + <nl> + PARAM_PID_PITCH_ANGLE_P , <nl> + PARAM_PID_PITCH_ANGLE_I , <nl> + PARAM_PID_PITCH_ANGLE_D , <nl> + PARAM_PITCH_ANGLE_TRIM , <nl> + PARAM_MAX_PITCH_ANGLE , <nl> + <nl> + PARAM_PID_ALT_P , <nl> + PARAM_PID_ALT_I , <nl> + PARAM_PID_ALT_D , <nl> + PARAM_HOVER_THROTTLE , <nl> + <nl> + PARAM_PID_TAU , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * PWM CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_MOTOR_PWM_SEND_RATE , <nl> + PARAM_MOTOR_IDLE_PWM , <nl> + PARAM_SPIN_MOTORS_WHEN_ARMED , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * ESTIMATOR CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_INIT_TIME , <nl> + PARAM_FILTER_KP , <nl> + PARAM_FILTER_KI , <nl> + <nl> + PARAM_GYRO_ALPHA , <nl> + PARAM_ACC_ALPHA , <nl> + <nl> + PARAM_ACCEL_SCALE , <nl> + <nl> + PARAM_GYRO_X_BIAS , <nl> + PARAM_GYRO_Y_BIAS , <nl> + PARAM_GYRO_Z_BIAS , <nl> + PARAM_ACC_X_BIAS , <nl> + PARAM_ACC_Y_BIAS , <nl> + PARAM_ACC_Z_BIAS , <nl> + PARAM_ACC_X_TEMP_COMP , <nl> + PARAM_ACC_Y_TEMP_COMP , <nl> + PARAM_ACC_Z_TEMP_COMP , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * RC CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_RC_TYPE , <nl> + PARAM_RC_X_CHANNEL , <nl> + PARAM_RC_Y_CHANNEL , <nl> + PARAM_RC_Z_CHANNEL , <nl> + PARAM_RC_F_CHANNEL , <nl> + PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL , <nl> + PARAM_RC_THROTTLE_OVERRIDE_CHANNEL , <nl> + PARAM_RC_ATT_CONTROL_TYPE_CHANNEL , <nl> + PARAM_RC_F_CONTROL_TYPE_CHANNEL , <nl> + PARAM_RC_NUM_CHANNELS , <nl> + <nl> + PARAM_RC_X_CENTER , <nl> + PARAM_RC_Y_CENTER , <nl> + PARAM_RC_Z_CENTER , <nl> + PARAM_RC_F_BOTTOM , <nl> + PARAM_RC_X_RANGE , <nl> + PARAM_RC_Y_RANGE , <nl> + PARAM_RC_Z_RANGE , <nl> + PARAM_RC_F_RANGE , <nl> + PARAM_RC_SWITCH_5_DIRECTION , <nl> + PARAM_RC_SWITCH_6_DIRECTION , <nl> + PARAM_RC_SWITCH_7_DIRECTION , <nl> + PARAM_RC_SWITCH_8_DIRECTION , <nl> + <nl> + PARAM_RC_OVERRIDE_DEVIATION , <nl> + PARAM_OVERRIDE_LAG_TIME , <nl> + PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE , <nl> + <nl> + PARAM_RC_MAX_ROLL , <nl> + PARAM_RC_MAX_PITCH , <nl> + PARAM_RC_MAX_ROLLRATE , <nl> + PARAM_RC_MAX_PITCHRATE , <nl> + PARAM_RC_MAX_YAWRATE , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * FRAME CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_MIXER , <nl> + <nl> + PARAM_FIXED_WING , <nl> + PARAM_ELEVATOR_REVERSE , <nl> + PARAM_AILERON_REVERSE , <nl> + PARAM_RUDDER_REVERSE , <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * ARMING SETUP * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * / <nl> + PARAM_ARM_STICKS , <nl> + PARAM_ARM_CHANNEL , <nl> + PARAM_ARM_THRESHOLD , <nl> + <nl> + / / keep track of size of params array <nl> + PARAMS_COUNT <nl> + } param_id_t ; <nl> + <nl> + typedef enum <nl> + { <nl> + PARAM_TYPE_INT32 , <nl> + PARAM_TYPE_FLOAT , <nl> + PARAM_TYPE_INVALID <nl> + } param_type_t ; <nl> + <nl> + / / function declarations <nl> + / * * <nl> + * @ brief Initialize parameter values <nl> + * / <nl> + void init ( Board * _board , CommLink * _comm_link ) ; <nl> + <nl> + / * * <nl> + * @ brief Set all parameters to default values <nl> + * / <nl> + void set_param_defaults ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Read parameter values from non - volatile memory <nl> + * @ return True if successful , false otherwise <nl> + * / <nl> + bool read_params ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Write current parameter values to non - volatile memory <nl> + * @ return True if successful , false otherwise <nl> + * / <nl> + bool write_params ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Callback for executing actions that need to be taken when a parameter value changes <nl> + * @ param id The ID of the parameter that was changed <nl> + * / <nl> + void param_change_callback ( param_id_t id ) ; <nl> + <nl> + / * * <nl> + * @ brief Gets the id of a parameter from its name <nl> + * @ param name The name of the parameter <nl> + * @ return The ID of the parameter if the name is valid , PARAMS_COUNT otherwise ( invalid ID ) <nl> + * / <nl> + param_id_t lookup_param_id ( const char name [ PARAMS_NAME_LENGTH ] ) ; <nl> + <nl> + / * * <nl> + * @ brief Get the value of an integer parameter by id <nl> + * @ param id The ID of the parameter <nl> + * @ return The value of the parameter <nl> + * / <nl> + int get_param_int ( param_id_t id ) ; <nl> + <nl> + / * * <nl> + * @ brief Get the value of a floating point parameter by id <nl> + * @ param id The ID of the parameter <nl> + * @ return The value of the parameter <nl> + * / <nl> + float get_param_float ( param_id_t id ) ; <nl> + <nl> + / * * <nl> + * @ brief Get the name of a parameter <nl> + * @ param id The ID of the parameter <nl> + * @ return The name of the parameter <nl> + * / <nl> + char * get_param_name ( param_id_t id ) ; <nl> + <nl> + / * * <nl> + * @ brief Get the type of a parameter <nl> + * @ param id The ID of the parameter <nl> + * @ return The type of the parameter <nl> + * This returns one of three possible types <nl> + * PARAM_TYPE_INT32 , PARAM_TYPE_FLOAT , or PARAM_TYPE_INVALID <nl> + * See line 165 <nl> + * / <nl> + param_type_t get_param_type ( param_id_t id ) ; <nl> + <nl> + / * * <nl> + * @ brief Sets the value of a parameter by ID and calls the parameter change callback <nl> + * @ param id The ID of the parameter <nl> + * @ param value The new value <nl> + * @ return True if a parameter value was changed , false otherwise <nl> + * / <nl> + bool set_param_int ( param_id_t id , int32_t value ) ; <nl> + <nl> + / * * <nl> + * @ brief Sets the value of a floating point parameter by ID and calls the parameter callback <nl> + * @ param id The ID of the parameter <nl> + * @ param value The new value <nl> + * @ return True if a parameter was changed , false otherwise <nl> + * / <nl> + bool set_param_float ( param_id_t id , float value ) ; <nl> + <nl> + / * * <nl> + * @ brief Sets the value of a parameter by name and calls the parameter change callback <nl> + * @ param name The name of the parameter <nl> + * @ param value The new value <nl> + * @ return True if a parameter value was changed , false otherwise <nl> + * / <nl> + bool set_param_by_name_int ( const char name [ PARAMS_NAME_LENGTH ] , int32_t value ) ; <nl> + <nl> + / * * <nl> + * @ brief Sets the value of a floating point parameter by name and calls the parameter change callback <nl> + * @ param name The name of the parameter <nl> + * @ param value The new value <nl> + * @ return True if a parameter value was changed , false otherwise <nl> + * / <nl> + bool set_param_by_name_float ( const char name [ PARAMS_NAME_LENGTH ] , float value ) ; <nl> + <nl> + private : <nl> + void init_param_int ( param_id_t id , const char name [ PARAMS_NAME_LENGTH ] , int32_t value ) ; <nl> + void init_param_float ( param_id_t id , const char name [ PARAMS_NAME_LENGTH ] , float value ) ; <nl> + <nl> + <nl> + private : <nl> + / / type definitions <nl> + typedef struct <nl> + { <nl> + uint8_t version ; <nl> + uint16_t size ; <nl> + uint8_t magic_be ; / / magic number , should be 0xBE <nl> + <nl> + int32_t values [ PARAMS_COUNT ] ; <nl> + char names [ PARAMS_COUNT ] [ PARAMS_NAME_LENGTH ] ; <nl> + param_type_t types [ PARAMS_COUNT ] ; <nl> + <nl> + uint8_t magic_ef ; / / magic number , should be 0xEF <nl> + uint8_t chk ; / / XOR checksum <nl> + } params_t ; <nl> + <nl> + params_t _params ; <nl> + Board * board ; <nl> + CommLink * comm_link ; <nl> + <nl> + } ; <nl> + <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + <nl> + / / function definitions <nl> + void Params : : init ( Board * _board , CommLink * _comm_link ) <nl> + { <nl> + board = _board ; <nl> + comm_link = _comm_link ; <nl> + <nl> + for ( uint8_t i = 0 ; i < PARAMS_COUNT ; i + + ) <nl> + { <nl> + init_param_int ( static_cast < param_id_t > ( i ) , " DEFAULT " , 0 ) ; <nl> + } <nl> + board - > init_params ( ) ; <nl> + if ( ! read_params ( ) ) <nl> + { <nl> + set_param_defaults ( ) ; <nl> + write_params ( ) ; <nl> + } <nl> + <nl> + for ( uint16_t id = 0 ; id < PARAMS_COUNT ; id + + ) <nl> + param_change_callback ( ( param_id_t ) id ) ; <nl> + } <nl> + <nl> + / / local function definitions <nl> + void Params : : init_param_int ( Params : : param_id_t id , const char name [ Params : : PARAMS_NAME_LENGTH ] , int32_t value ) <nl> + { <nl> + memcpy ( _params . names [ id ] , name , PARAMS_NAME_LENGTH ) ; <nl> + _params . values [ id ] = value ; <nl> + _params . types [ id ] = PARAM_TYPE_INT32 ; <nl> + } <nl> + <nl> + void Params : : init_param_float ( Params : : param_id_t id , const char name [ Params : : PARAMS_NAME_LENGTH ] , float value ) <nl> + { <nl> + memcpy ( _params . names [ id ] , name , PARAMS_NAME_LENGTH ) ; <nl> + _params . values [ id ] = * ( ( int32_t * ) & value ) ; <nl> + _params . types [ id ] = PARAM_TYPE_FLOAT ; <nl> + } <nl> + <nl> + void Params : : set_param_defaults ( void ) <nl> + { <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * HARDWARE CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_BOARD_REVISION , " BOARD_REV " , 2 ) ; / / Major board revision of naze32 / flip32 | 1 | 6 <nl> + init_param_int ( PARAM_BAUD_RATE , " BAUD_RATE " , 921600 ) ; / / Baud rate of communication with onboard computer | 9600 | 921600 <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * MAVLINK CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_SYSTEM_ID , " SYS_ID " , 1 ) ; / / Mavlink System ID | 1 | 255 <nl> + init_param_int ( PARAM_STREAM_HEARTBEAT_RATE , " STRM_HRTBT " , 1 ) ; / / Rate of heartbeat streaming ( Hz ) | 0 | 1000 <nl> + <nl> + init_param_int ( PARAM_STREAM_ATTITUDE_RATE , " STRM_ATTITUDE " , 100 ) ; / / Rate of attitude stream ( Hz ) | 0 | 1000 <nl> + init_param_int ( PARAM_STREAM_IMU_RATE , " STRM_IMU " , 500 ) ; / / Rate of IMU stream ( Hz ) | 0 | 1000 <nl> + init_param_int ( PARAM_STREAM_MAG_RATE , " STRM_MAG " , 75 ) ; / / Rate of magnetometer stream ( Hz ) | 0 | 75 <nl> + init_param_int ( PARAM_STREAM_BARO_RATE , " STRM_BARO " , 100 ) ; / / Rate of barometer stream ( Hz ) | 0 | 100 <nl> + init_param_int ( PARAM_STREAM_AIRSPEED_RATE , " STRM_AIRSPEED " , 20 ) ; / / Rate of airspeed stream ( Hz ) | 0 | 50 <nl> + init_param_int ( PARAM_STREAM_GPS_RATE , " STRM_GPS " , 0 ) ; / / Rate of GPS stream ( Hz ) | 0 | 1 <nl> + init_param_int ( PARAM_STREAM_SONAR_RATE , " STRM_SONAR " , 40 ) ; / / Rate of sonar stream ( Hz ) | 0 | 40 <nl> + <nl> + init_param_int ( PARAM_STREAM_SERVO_OUTPUT_RAW_RATE , " STRM_SERVO " , 50 ) ; / / Rate of raw output stream | 0 | 490 <nl> + init_param_int ( PARAM_STREAM_RC_RAW_RATE , " STRM_RC " , 50 ) ; / / Rate of raw RC input stream | 0 | 50 <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * CONTROLLER CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_MAX_COMMAND , " PARAM_MAX_CMD " , 1000 ) ; / / saturation point for PID controller output | 0 | 1000 <nl> + <nl> + init_param_float ( PARAM_PID_ROLL_RATE_P , " PID_ROLL_RATE_P " , 0 . 070f ) ; / / Roll Rate Proportional Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_ROLL_RATE_I , " PID_ROLL_RATE_I " , 0 . 000f ) ; / / Roll Rate Integral Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_ROLL_RATE_D , " PID_ROLL_RATE_D " , 0 . 000f ) ; / / Rall Rate Derivative Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_ROLL_RATE_TRIM , " ROLL_RATE_TRIM " , 0 . 0f ) ; / / Roll Rate Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_MAX_ROLL_RATE , " MAX_ROLL_RATE " , 3 . 14159f ) ; / / Maximum Roll Rate command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> + <nl> + init_param_float ( PARAM_PID_PITCH_RATE_P , " PID_PITCH_RATE_P " , 0 . 070f ) ; / / Pitch Rate Proporitional Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_PITCH_RATE_I , " PID_PITCH_RATE_I " , 0 . 0000f ) ; / / Pitch Rate Integral Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_PITCH_RATE_D , " PID_PITCH_RATE_D " , 0 . 0000f ) ; / / Pitch Rate Derivative Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PITCH_RATE_TRIM , " PITCH_RATE_TRIM " , 0 . 0f ) ; / / Pitch Rate Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_MAX_PITCH_RATE , " MAX_PITCH_RATE " , 3 . 14159f ) ; / / Maximum Pitch Rate command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> + <nl> + init_param_float ( PARAM_PID_YAW_RATE_P , " PID_YAW_RATE_P " , 0 . 25f ) ; / / Yaw Rate Proporitional Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_YAW_RATE_I , " PID_YAW_RATE_I " , 0 . 0f ) ; / / Yaw Rate Integral Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_YAW_RATE_D , " PID_YAW_RATE_D " , 0 . 0f ) ; / / Yaw Rate Derivative Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_YAW_RATE_TRIM , " YAW_RATE_TRIM " , 0 . 0f ) ; / / Yaw Rate Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_MAX_YAW_RATE , " MAX_YAW_RATE " , 6 . 283f ) ; / / Maximum Yaw Rate command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> + <nl> + init_param_float ( PARAM_PID_ROLL_ANGLE_P , " PID_ROLL_ANG_P " , 0 . 15f ) ; / / Roll Angle Proporitional Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_ROLL_ANGLE_I , " PID_ROLL_ANG_I " , 0 . 0f ) ; / / Roll Angle Integral Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_ROLL_ANGLE_D , " PID_ROLL_ANG_D " , 0 . 07f ) ; / / Roll Angle Derivative Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_ROLL_ANGLE_TRIM , " ROLL_TRIM " , 0 . 0f ) ; / / Roll Angle Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_MAX_ROLL_ANGLE , " MAX_ROLL_ANG " , 0 . 786f ) ; / / Maximum Roll Angle command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> + <nl> + init_param_float ( PARAM_PID_PITCH_ANGLE_P , " PID_PITCH_ANG_P " , 0 . 15f ) ; / / Pitch Angle Proporitional Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_PITCH_ANGLE_I , " PID_PITCH_ANG_I " , 0 . 0f ) ; / / Pitch Angle Integral Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_PITCH_ANGLE_D , " PID_PITCH_ANG_D " , 0 . 07f ) ; / / Pitch Angle Derivative Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PITCH_ANGLE_TRIM , " PITCH_TRIM " , 0 . 0f ) ; / / Pitch Angle Trim - See RC calibration | - 1000 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_MAX_PITCH_ANGLE , " MAX_PITCH_ANG " , 0 . 786f ) ; / / Maximum Pitch Angle command accepted into PID controllers | 0 . 0 | 1000 . 0 <nl> + <nl> + init_param_float ( PARAM_PID_ALT_P , " PID_ALT_P " , 0 . 0f ) ; / / Altitude Proporitional Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_ALT_I , " PID_ALT_I " , 0 . 0f ) ; / / Altitude Integral Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_PID_ALT_D , " PID_ALT_D " , 0 . 0f ) ; / / Altitude Derivative Gain | 0 . 0 | 1000 . 0 <nl> + init_param_float ( PARAM_HOVER_THROTTLE , " HOVER_THR " , 0 . 5 ) ; / / Hover Throttle - See RC calibration | 0 . 0 | 1 . 0 <nl> + <nl> + init_param_float ( PARAM_PID_TAU , " PID_TAU " , 0 . 05f ) ; / / Dirty Derivative time constant - See controller documentation | 0 . 0 | 1 . 0 <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * PWM CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_MOTOR_PWM_SEND_RATE , " MOTOR_PWM_UPDATE " , 490 ) ; / / Refresh rate of motor commands to motors - See motor documentation | 0 | 1000 <nl> + init_param_int ( PARAM_MOTOR_IDLE_PWM , " MOTOR_IDLE_PWM " , 1100 ) ; / / Idle PWM sent to motors at zero throttle ( Set above 1100 to spin when armed ) | 1000 | 2000 <nl> + init_param_int ( PARAM_SPIN_MOTORS_WHEN_ARMED , " ARM_SPIN_MOTORS " , true ) ; / / Enforce MOTOR_IDLE_PWM | 0 | 1 <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * ESTIMATOR CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_INIT_TIME , " FILTER_INIT_T " , 3000 ) ; / / Time in ms to initialize estimator | 0 | 100000 <nl> + init_param_float ( PARAM_FILTER_KP , " FILTER_KP " , 1 . 0f ) ; / / estimator proportional gain - See estimator documentation | 0 | 10 . 0 <nl> + init_param_float ( PARAM_FILTER_KI , " FILTER_KI " , 0 . 1f ) ; / / estimator integral gain - See estimator documentation | 0 | 1 . 0 <nl> + <nl> + init_param_float ( PARAM_GYRO_ALPHA , " GYRO_LPF_ALPHA " , 0 . 888f ) ; / / Low - pass filter constant - See estimator documentation | 0 | 1 . 0 <nl> + init_param_float ( PARAM_ACC_ALPHA , " ACC_LPF_ALPHA " , 0 . 888f ) ; / / Low - pass filter constant - See estimator documentation | 0 | 1 . 0 <nl> + <nl> + init_param_float ( PARAM_ACCEL_SCALE , " ACCEL_SCALE " , 1 . 0f ) ; / / Scale factor to apply to IMU measurements - Read - Only | 0 . 5 | 2 . 0 <nl> + <nl> + init_param_float ( PARAM_GYRO_X_BIAS , " GYRO_X_BIAS " , 0 . 0f ) ; / / Constant x - bias of gyroscope readings | - 1 . 0 | 1 . 0 <nl> + init_param_float ( PARAM_GYRO_Y_BIAS , " GYRO_Y_BIAS " , 0 . 0f ) ; / / Constant y - bias of gyroscope readings | - 1 . 0 | 1 . 0 <nl> + init_param_float ( PARAM_GYRO_Z_BIAS , " GYRO_Z_BIAS " , 0 . 0f ) ; / / Constant z - bias of gyroscope readings | - 1 . 0 | 1 . 0 <nl> + init_param_float ( PARAM_ACC_X_BIAS , " ACC_X_BIAS " , 0 . 0f ) ; / / Constant x - bias of accelerometer readings | - 2 . 0 | 2 . 0 <nl> + init_param_float ( PARAM_ACC_Y_BIAS , " ACC_Y_BIAS " , 0 . 0f ) ; / / Constant y - bias of accelerometer readings | - 2 . 0 | 2 . 0 <nl> + init_param_float ( PARAM_ACC_Z_BIAS , " ACC_Z_BIAS " , 0 . 0f ) ; / / Constant z - bias of accelerometer readings | - 2 . 0 | 2 . 0 <nl> + init_param_float ( PARAM_ACC_X_TEMP_COMP , " ACC_X_TEMP_COMP " , 0 . 0f ) ; / / Linear x - axis temperature compensation constant | - 2 . 0 | 2 . 0 <nl> + init_param_float ( PARAM_ACC_Y_TEMP_COMP , " ACC_Y_TEMP_COMP " , 0 . 0f ) ; / / Linear y - axis temperature compensation constant | - 2 . 0 | 2 . 0 <nl> + init_param_float ( PARAM_ACC_Z_TEMP_COMP , " ACC_Z_TEMP_COMP " , 0 . 0f ) ; / / Linear z - axis temperature compensation constant | - 2 . 0 | 2 . 0 <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * RC CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_RC_TYPE , " RC_TYPE " , 1 ) ; / / Type of RC input 0 - Parallel PWM ( PWM ) , 1 - Pulse - Position Modulation ( PPM ) | 0 | 1 <nl> + init_param_int ( PARAM_RC_X_CHANNEL , " RC_X_CHN " , 0 ) ; / / RC input channel mapped to x - axis commands [ 0 - indexed ] | 0 | 3 <nl> + init_param_int ( PARAM_RC_Y_CHANNEL , " RC_Y_CHN " , 1 ) ; / / RC input channel mapped to y - axis commands [ 0 - indexed ] | 0 | 3 <nl> + init_param_int ( PARAM_RC_Z_CHANNEL , " RC_Z_CHN " , 3 ) ; / / RC input channel mapped to z - axis commands [ 0 - indexed ] | 0 | 3 <nl> + init_param_int ( PARAM_RC_F_CHANNEL , " RC_F_CHN " , 2 ) ; / / RC input channel mapped to F - axis commands [ 0 - indexed ] | 0 | 3 <nl> + init_param_int ( PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL , " RC_ATT_OVRD_CHN " , 4 ) ; / / RC switch mapped to attitude override [ 0 - indexed ] | 4 | 7 <nl> + init_param_int ( PARAM_RC_THROTTLE_OVERRIDE_CHANNEL , " RC_THR_OVRD_CHN " , 5 ) ; / / RC switch hannel mapped to throttle override [ 0 - indexed ] | 4 | 7 <nl> + init_param_int ( PARAM_RC_ATT_CONTROL_TYPE_CHANNEL , " RC_ATT_CTRL_CHN " , 6 ) ; / / RC switch channel mapped to attitude control type [ 0 - indexed ] | 4 | 7 <nl> + init_param_int ( PARAM_RC_F_CONTROL_TYPE_CHANNEL , " RC_F_CTRL_CHN " , 7 ) ; / / RC switch channel mapped to throttle control type override [ 0 - indexed ] | 4 | 7 <nl> + init_param_int ( PARAM_RC_NUM_CHANNELS , " RC_NUM_CHN " , 9 ) ; / / number of RC input channels | 1 | 8 <nl> + <nl> + init_param_int ( PARAM_RC_X_CENTER , " RC_X_CENTER " , 1500 ) ; / / RC calibration x - axis center ( us ) | 1000 | 2000 <nl> + init_param_int ( PARAM_RC_Y_CENTER , " RC_Y_CENTER " , 1500 ) ; / / RC calibration y - axis center ( us ) | 1000 | 2000 <nl> + init_param_int ( PARAM_RC_Z_CENTER , " RC_Z_CENTER " , 1500 ) ; / / RC calibration z - axis center ( us ) | 1000 | 2000 <nl> + init_param_int ( PARAM_RC_F_BOTTOM , " RC_F_BOTTOM " , 1000 ) ; / / RC calibration F - axis center ( us ) | 1000 | 2000 <nl> + init_param_int ( PARAM_RC_X_RANGE , " RC_X_RANGE " , 1000 ) ; / / RC calibration x - axis range ( us ) | 500 | 2500 <nl> + init_param_int ( PARAM_RC_Y_RANGE , " RC_Y_RANGE " , 1000 ) ; / / RC calibration y - axis range ( us ) | 500 | 2500 <nl> + init_param_int ( PARAM_RC_Z_RANGE , " RC_Z_RANGE " , 1000 ) ; / / RC calibration z - axis range ( us ) | 500 | 2500 <nl> + init_param_int ( PARAM_RC_F_RANGE , " RC_F_RANGE " , 1000 ) ; / / RC calibration F - axis range ( us ) | 500 | 2500 <nl> + init_param_int ( PARAM_RC_SWITCH_5_DIRECTION , " SWITCH_5_DIR " , 1 ) ; / / RC switch 5 toggle direction | 0 | 1 <nl> + init_param_int ( PARAM_RC_SWITCH_6_DIRECTION , " SWITCH_6_DIR " , 1 ) ; / / RC switch 6 toggle direction | 0 | 1 <nl> + init_param_int ( PARAM_RC_SWITCH_7_DIRECTION , " SWITCH_7_DIR " , 1 ) ; / / RC switch 7 toggle direction | 0 | 1 <nl> + init_param_int ( PARAM_RC_SWITCH_8_DIRECTION , " SWITCH_8_DIR " , 1 ) ; / / RC switch 8 toggle direction | 0 | 1 <nl> + <nl> + init_param_int ( PARAM_RC_OVERRIDE_DEVIATION , " RC_OVRD_DEV " , 100 ) ; / / RC stick deviation from center for overrride ( us ) | 0 | 1000 <nl> + init_param_int ( PARAM_OVERRIDE_LAG_TIME , " OVRD_LAG_TIME " , 1000 ) ; / / RC stick deviation lag time before returning control ( ms ) | 0 | 100000 <nl> + init_param_int ( PARAM_RC_OVERRIDE_TAKE_MIN_THROTTLE , " MIN_THROTTLE " , false ) ; / / Take minimum throttle between RC and computer at all times | 0 | 1 <nl> + <nl> + init_param_float ( PARAM_RC_MAX_ROLL , " RC_MAX_ROLL " , 0 . 786f ) ; / / Maximum roll angle command sent by full deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> + init_param_float ( PARAM_RC_MAX_PITCH , " RC_MAX_PITCH " , 0 . 786f ) ; / / Maximum pitch angle command sent by full stick deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> + init_param_float ( PARAM_RC_MAX_ROLLRATE , " RC_MAX_ROLLRATE " , 3 . 14159f ) ; / / Maximum roll rate command sent by full stick deflection of RC sticks | 0 . 0 | 9 . 42477796077 <nl> + init_param_float ( PARAM_RC_MAX_PITCHRATE , " RC_MAX_PITCHRATE " , 3 . 14159f ) ; / / Maximum pitch command sent by full stick deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> + init_param_float ( PARAM_RC_MAX_YAWRATE , " RC_MAX_YAWRATE " , 0 . 786f ) ; / / Maximum pitch command sent by full stick deflection of RC sticks | 0 . 0 | 3 . 14159 <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * FRAME CONFIGURATION * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_MIXER , " MIXER " , 1 ) ; / / Which mixer to choose , 1 = QUADCOPTER_X - See Mixer documentation | 0 | 5 <nl> + <nl> + init_param_int ( PARAM_FIXED_WING , " FIXED_WING " , false ) ; / / switches on passthrough commands for fixedwing operation | 0 | 1 <nl> + init_param_int ( PARAM_ELEVATOR_REVERSE , " ELEVATOR_REV " , 0 ) ; / / reverses elevator servo output | 0 | 1 <nl> + init_param_int ( PARAM_AILERON_REVERSE , " AIL_REV " , 0 ) ; / / reverses aileron servo output | 0 | 1 <nl> + init_param_int ( PARAM_RUDDER_REVERSE , " RUDDER_REV " , 0 ) ; / / reverses rudder servo output | 0 | 1 <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * ARMING SETUP * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * / <nl> + init_param_int ( PARAM_ARM_STICKS , " ARM_STICKS " , false ) ; / / use RC sticks to arm vehicle ( disables arm RC switch if enabled ) | 0 | 1 <nl> + init_param_int ( PARAM_ARM_CHANNEL , " ARM_CHANNEL " , 4 ) ; / / RC switch mapped to arm / disarm [ 0 - indexed ] | 4 | 7 <nl> + init_param_int ( PARAM_ARM_THRESHOLD , " ARM_THRESHOLD " , 150 ) ; / / RC deviation from max / min in yaw and throttle for arming and disarming check ( us ) | 0 | 500 <nl> + } <nl> + <nl> + bool Params : : read_params ( void ) <nl> + { <nl> + return board - > read_params ( ) ; <nl> + } <nl> + <nl> + bool Params : : write_params ( void ) <nl> + { <nl> + return board - > write_params ( true ) ; <nl> + } <nl> + <nl> + void Params : : param_change_callback ( param_id_t id ) <nl> + { <nl> + switch ( id ) <nl> + { <nl> + case PARAM_SYSTEM_ID : <nl> + comm_link - > set_sys_id ( get_param_int ( PARAM_SYSTEM_ID ) ) ; <nl> + break ; <nl> + case PARAM_STREAM_HEARTBEAT_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_HEARTBEAT_RATE , get_param_int ( PARAM_STREAM_HEARTBEAT_RATE ) ) ; <nl> + break ; <nl> + <nl> + case PARAM_STREAM_ATTITUDE_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_ATTITUDE_RATE , get_param_int ( PARAM_STREAM_ATTITUDE_RATE ) ) ; <nl> + break ; <nl> + <nl> + case PARAM_STREAM_IMU_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_IMU_RATE , get_param_int ( PARAM_STREAM_IMU_RATE ) ) ; <nl> + break ; <nl> + case PARAM_STREAM_AIRSPEED_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_AIRSPEED_RATE , get_param_int ( PARAM_STREAM_AIRSPEED_RATE ) ) ; <nl> + break ; <nl> + case PARAM_STREAM_SONAR_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_SONAR_RATE , get_param_int ( PARAM_STREAM_SONAR_RATE ) ) ; <nl> + break ; <nl> + case PARAM_STREAM_BARO_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_BARO_RATE , get_param_int ( PARAM_STREAM_BARO_RATE ) ) ; <nl> + break ; <nl> + case PARAM_STREAM_MAG_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_MAG_RATE , get_param_int ( PARAM_STREAM_MAG_RATE ) ) ; <nl> + break ; <nl> + <nl> + case PARAM_STREAM_SERVO_OUTPUT_RAW_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_SERVO_OUTPUT_RAW_RATE , get_param_int ( PARAM_STREAM_SERVO_OUTPUT_RAW_RATE ) ) ; <nl> + break ; <nl> + case PARAM_STREAM_RC_RAW_RATE : <nl> + comm_link - > set_streaming_rate ( PARAM_STREAM_RC_RAW_RATE , get_param_int ( PARAM_STREAM_RC_RAW_RATE ) ) ; <nl> + break ; <nl> + <nl> + / / information messages <nl> + case PARAM_RC_TYPE : <nl> + comm_link - > log_message ( CommonState : : stringf ( " RC type = % i " , get_param_int ( PARAM_RC_TYPE ) ) . c_str ( ) , 0 ) ; <nl> + case PARAM_MIXER : <nl> + comm_link - > log_message ( CommonState : : stringf ( " Mixer = % i " , get_param_int ( PARAM_MIXER ) ) . c_str ( ) , 0 ) ; <nl> + case PARAM_FIXED_WING : <nl> + comm_link - > log_message ( CommonState : : stringf ( " Fixed wing = % i " , get_param_int ( PARAM_FIXED_WING ) ) . c_str ( ) , 0 ) ; <nl> + case PARAM_ARM_STICKS : <nl> + comm_link - > log_message ( CommonState : : stringf ( " Can use RC to arm = % i " , get_param_int ( PARAM_ARM_STICKS ) ) . c_str ( ) , 0 ) ; <nl> + <nl> + <nl> + / / TODO : need better design so components can listen to their param changes <nl> + / / case PARAM_RC_TYPE : <nl> + / / mixer - > init_PWM ( ) ; <nl> + / / break ; <nl> + / / case PARAM_MOTOR_PWM_SEND_RATE : <nl> + / / mixer - > init_PWM ( ) ; <nl> + / / break ; <nl> + / / case PARAM_MIXER : <nl> + / / mixer - > init ( common_state ) ; <nl> + / / break ; <nl> + <nl> + default : <nl> + / / no action needed for this parameter <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + Params : : param_id_t Params : : lookup_param_id ( const char name [ PARAMS_NAME_LENGTH ] ) <nl> + { <nl> + for ( uint16_t id = 0 ; id < PARAMS_COUNT ; id + + ) <nl> + { <nl> + bool match = true ; <nl> + for ( uint8_t i = 0 ; i < PARAMS_NAME_LENGTH ; i + + ) <nl> + { <nl> + / / compare each character <nl> + if ( name [ i ] ! = _params . names [ id ] [ i ] ) <nl> + { <nl> + match = false ; <nl> + break ; <nl> + } <nl> + <nl> + / / stop comparing if end of string is reached <nl> + if ( _params . names [ id ] [ i ] = = ' \ 0 ' ) <nl> + break ; <nl> + } <nl> + <nl> + if ( match ) <nl> + return ( param_id_t ) id ; <nl> + } <nl> + <nl> + return PARAMS_COUNT ; <nl> + } <nl> + <nl> + int Params : : get_param_int ( param_id_t id ) <nl> + { <nl> + return _params . values [ id ] ; <nl> + } <nl> + <nl> + float Params : : get_param_float ( param_id_t id ) <nl> + { <nl> + return * ( float * ) & _params . values [ id ] ; <nl> + } <nl> + <nl> + char * Params : : get_param_name ( param_id_t id ) <nl> + { <nl> + return _params . names [ id ] ; <nl> + } <nl> + <nl> + Params : : param_type_t Params : : get_param_type ( param_id_t id ) <nl> + { <nl> + return _params . types [ id ] ; <nl> + } <nl> + <nl> + bool Params : : set_param_int ( param_id_t id , int32_t value ) <nl> + { <nl> + if ( id < PARAMS_COUNT & & value ! = _params . values [ id ] ) <nl> + { <nl> + _params . values [ id ] = value ; <nl> + param_change_callback ( id ) ; <nl> + comm_link - > notify_param_change ( id , value ) ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + bool Params : : set_param_float ( param_id_t id , float value ) <nl> + { <nl> + return set_param_int ( id , * ( int32_t * ) & value ) ; <nl> + } <nl> + <nl> + bool Params : : set_param_by_name_int ( const char name [ PARAMS_NAME_LENGTH ] , int32_t value ) <nl> + { <nl> + param_id_t id = lookup_param_id ( name ) ; <nl> + return set_param_int ( id , value ) ; <nl> + } <nl> + <nl> + bool Params : : set_param_by_name_float ( const char name [ PARAMS_NAME_LENGTH ] , float value ) <nl> + { <nl> + return set_param_by_name_int ( name , * ( int32_t * ) & value ) ; <nl> + } <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 97 % <nl> rename from AirLib / include / controllers / rosflight / firmware / rc . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / rc . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / rc . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / rc . hpp <nl> <nl> - # ifndef RC_H_ <nl> - # define RC_H_ <nl> - <nl> - # include " mux . hpp " <nl> - # include " param . hpp " <nl> - # include " board . hpp " <nl> - # include " commlink . hpp " <nl> - <nl> - namespace rosflight { <nl> - <nl> - class RC { <nl> - public : <nl> - void init ( CommonState * _common_state , Board * _board , Mux * _mux , Params * _params , CommLink * _comm_link ) ; <nl> - bool rc_switch ( int16_t channel ) ; <nl> - bool receive_rc ( uint64_t now ) ; <nl> - <nl> - private : <nl> - void calibrate_rc ( ) ; <nl> - void convertPWMtoRad ( ) ; <nl> - <nl> - private : <nl> - typedef struct <nl> - { <nl> - int16_t channel ; <nl> - int16_t direction ; <nl> - } rc_switch_t ; <nl> - <nl> - typedef enum <nl> - { <nl> - PARALLEL_PWM , <nl> - CPPM , <nl> - } rc_type_t ; <nl> - <nl> - <nl> - bool _calibrate_rc ; <nl> - rc_switch_t switches [ 4 ] ; <nl> - <nl> - CommonState * common_state ; <nl> - Mux * mux ; <nl> - Params * params ; <nl> - Board * board ; <nl> - CommLink * comm_link ; <nl> - <nl> - uint64_t last_rc_receive_time = 0 ; / / receive_rc <nl> - uint64_t time_of_last_stick_deviation = 0 ; / / receive_rc <nl> - int32_t calib_max [ 4 ] = { 0 , 0 , 0 , 0 } ; <nl> - int32_t calib_min [ 4 ] = { 10000 , 10000 , 10000 , 10000 } ; <nl> - int32_t calib_sum [ 4 ] = { 0 , 0 , 0 , 0 } ; <nl> - int32_t calib_count [ 4 ] = { 0 , 0 , 0 , 0 } ; <nl> - <nl> - bool last_is_angle_control , last_is_altitude_control ; <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - void RC : : init ( CommonState * _common_state , Board * _board , Mux * _mux , Params * _params , CommLink * _comm_link ) <nl> - { <nl> - common_state = _common_state ; <nl> - mux = _mux ; <nl> - params = _params ; <nl> - board = _board ; <nl> - comm_link = _comm_link ; <nl> - <nl> - _calibrate_rc = false ; <nl> - <nl> - Mux : : control_t & rc_control = mux - > rc_control ( ) ; <nl> - rc_control . x . type = Mux : : control_type_t : : ANGLE ; <nl> - rc_control . y . type = Mux : : control_type_t : : ANGLE ; <nl> - rc_control . z . type = Mux : : control_type_t : : RATE ; <nl> - rc_control . F . type = Mux : : control_type_t : : THROTTLE ; <nl> - <nl> - rc_control . x . value = 0 ; <nl> - rc_control . y . value = 0 ; <nl> - rc_control . z . value = 0 ; <nl> - rc_control . F . value = 0 ; <nl> - <nl> - Mux : : control_t & offboard_control = mux - > offboard_control ( ) ; <nl> - offboard_control . x . active = false ; <nl> - offboard_control . y . active = false ; <nl> - offboard_control . z . active = false ; <nl> - offboard_control . F . active = false ; <nl> - <nl> - switches [ 0 ] . channel = 4 ; <nl> - switches [ 0 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_5_DIRECTION ) ; <nl> - switches [ 1 ] . channel = 5 ; <nl> - switches [ 1 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_6_DIRECTION ) ; <nl> - switches [ 2 ] . channel = 6 ; <nl> - switches [ 2 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_7_DIRECTION ) ; <nl> - switches [ 3 ] . channel = 7 ; <nl> - switches [ 3 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_8_DIRECTION ) ; <nl> - <nl> - bool is_angle_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATT_CONTROL_TYPE_CHANNEL ) ) ; <nl> - bool is_altitude_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_F_CONTROL_TYPE_CHANNEL ) ) ; <nl> - comm_link - > log_message ( CommonState : : stringf ( " Is angle / rate control = % i " , is_angle_control ) . c_str ( ) , 0 ) ; <nl> - last_is_angle_control = is_angle_control ; <nl> - comm_link - > log_message ( CommonState : : stringf ( " Is altitude / throttle control = % i " , is_altitude_control ) . c_str ( ) , 0 ) ; <nl> - last_is_altitude_control = is_altitude_control ; <nl> - } <nl> - <nl> - bool RC : : rc_switch ( int16_t channel ) <nl> - { <nl> - if ( channel < 4 | | channel > 8 ) <nl> - { <nl> - return false ; <nl> - } <nl> - if ( switches [ channel - 4 ] . direction < 0 ) <nl> - { <nl> - return board - > pwmRead ( channel ) < 1500 ; <nl> - } <nl> - else <nl> - { <nl> - return board - > pwmRead ( channel ) > 1500 ; <nl> - } <nl> - } <nl> - <nl> - void RC : : convertPWMtoRad ( ) <nl> - { <nl> - Mux : : control_t & rc_control = mux - > rc_control ( ) ; <nl> - <nl> - / / Get Roll control command out of RC <nl> - if ( rc_control . x . type = = Mux : : control_type_t : : ANGLE ) <nl> - { <nl> - rc_control . x . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - 1500 ) <nl> - * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLL ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ; <nl> - } <nl> - else if ( rc_control . x . type = = Mux : : control_type_t : : RATE ) <nl> - { <nl> - rc_control . x . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - 1500 ) <nl> - * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLLRATE ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ; <nl> - } <nl> - else if ( rc_control . x . type = = Mux : : control_type_t : : MOTOR_DIRECT ) <nl> - { <nl> - rc_control . x . value = static_cast < float > ( <nl> - board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) <nl> - ) ; <nl> - } <nl> - <nl> - / / Get Pitch control command out of RC <nl> - if ( rc_control . y . type = = Mux : : control_type_t : : ANGLE ) <nl> - { <nl> - rc_control . y . value = ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - 1500 ) <nl> - * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCH ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ; <nl> - } <nl> - else if ( rc_control . y . type = = Mux : : control_type_t : : RATE ) <nl> - { <nl> - rc_control . y . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - 1500 ) <nl> - * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCHRATE ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ; <nl> - } <nl> - else if ( rc_control . y . type = = Mux : : control_type_t : : MOTOR_DIRECT ) <nl> - { <nl> - rc_control . y . value = static_cast < float > ( <nl> - board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - 1500 <nl> - ) ; <nl> - } <nl> - <nl> - / / Get the Yaw control command type out of RC <nl> - if ( rc_control . z . type = = Mux : : control_type_t : : RATE ) <nl> - { <nl> - rc_control . z . value = ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) - 1500 ) <nl> - * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_YAWRATE ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) ; <nl> - } <nl> - else if ( rc_control . z . type = = Mux : : control_type_t : : MOTOR_DIRECT ) <nl> - { <nl> - rc_control . z . value = static_cast < float > ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) - 1500 ) ; <nl> - } <nl> - <nl> - / / Finally , the Mux : : control_type_t : : THROTTLE command <nl> - rc_control . F . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_F_BOTTOM ) ) ) <nl> - / ( float ) params - > get_param_int ( Params : : PARAM_RC_F_RANGE ) ; <nl> - } <nl> - <nl> - <nl> - bool RC : : receive_rc ( uint64_t now ) <nl> - { <nl> - if ( _calibrate_rc ) <nl> - { <nl> - calibrate_rc ( ) ; <nl> - } <nl> - <nl> - / / if it has been more than 20ms then look for new RC values and parse them <nl> - if ( now - last_rc_receive_time < 20000 ) <nl> - { <nl> - return false ; <nl> - } <nl> - last_rc_receive_time = now ; <nl> - <nl> - / / Get timestamp for deadband control lag <nl> - Mux : : control_t & rc_control = mux - > rc_control ( ) ; <nl> - <nl> - / / Figure out the desired control type from the switches and params <nl> - if ( params - > get_param_int ( Params : : PARAM_FIXED_WING ) ) <nl> - { <nl> - / / for using fixedwings <nl> - rc_control . x . type = rc_control . y . type = rc_control . z . type = Mux : : control_type_t : : MOTOR_DIRECT ; <nl> - rc_control . F . type = Mux : : control_type_t : : THROTTLE ; <nl> - } <nl> - else <nl> - { <nl> - bool is_angle_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATT_CONTROL_TYPE_CHANNEL ) ) ; <nl> - bool is_altitude_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_F_CONTROL_TYPE_CHANNEL ) ) ; <nl> - <nl> - if ( last_is_angle_control ! = is_angle_control | | last_is_altitude_control ! = is_altitude_control ) { <nl> - comm_link - > log_message ( CommonState : : stringf ( " Is angle or rate control = % i " , is_angle_control ) . c_str ( ) , 0 ) ; <nl> - last_is_angle_control = is_angle_control ; <nl> - } <nl> - if ( last_is_altitude_control ! = is_altitude_control ) { <nl> - comm_link - > log_message ( CommonState : : stringf ( " Is altitude or throttle control = % i " , is_altitude_control ) . c_str ( ) , 0 ) ; <nl> - last_is_altitude_control = is_altitude_control ; <nl> - } <nl> - <nl> - rc_control . x . type = rc_control . y . type = is_angle_control ? Mux : : control_type_t : : ANGLE : Mux : : control_type_t : : RATE ; <nl> - rc_control . z . type = Mux : : control_type_t : : RATE ; <nl> - rc_control . F . type = is_altitude_control ? Mux : : control_type_t : : ALTITUDE : Mux : : control_type_t : : THROTTLE ; <nl> - } <nl> - <nl> - / / Interpret PWM Values from RC <nl> - convertPWMtoRad ( ) ; <nl> - <nl> - / / Set flags for attitude channels <nl> - if ( rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL ) ) <nl> - | | now - time_of_last_stick_deviation < ( uint32_t ) ( params - > get_param_int ( Params : : PARAM_OVERRIDE_LAG_TIME ) ) * 1000 ) <nl> - { <nl> - / / Pilot is in full control <nl> - rc_control . x . active = true ; <nl> - rc_control . y . active = true ; <nl> - rc_control . z . active = true ; <nl> - } <nl> - else <nl> - { <nl> - / / Check for stick deviation - if so , then the channel is active <nl> - rc_control . x . active = rc_control . y . active = rc_control . z . active = <nl> - abs ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) ) > <nl> - params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_DEVIATION ) <nl> - | | abs ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_Y_CENTER ) ) > <nl> - params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_DEVIATION ) <nl> - | | abs ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) ) > <nl> - params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_DEVIATION ) ; <nl> - if ( rc_control . x . active ) <nl> - { <nl> - / / reset override lag <nl> - time_of_last_stick_deviation = now ; <nl> - } <nl> - } <nl> - <nl> - <nl> - / / Set flags for Mux : : control_type_t : : THROTTLE channel <nl> - if ( rc_switch ( params - > get_param_int ( Params : : PARAM_RC_THROTTLE_OVERRIDE_CHANNEL ) ) ) <nl> - { <nl> - / / RC Pilot is in full control <nl> - rc_control . F . active = true ; <nl> - } <nl> - else <nl> - { <nl> - / / Onboard Control - min Mux : : control_type_t : : THROTTLE Checking will be done in mux and in the controller . <nl> - rc_control . F . active = false ; <nl> - } <nl> - <nl> - mux - > set_new_command ( true ) ; <nl> - return true ; <nl> - } <nl> - <nl> - void RC : : calibrate_rc ( ) <nl> - { <nl> - if ( common_state - > is_armed ( ) ) <nl> - { <nl> - comm_link - > log_message ( " Cannot calibrate RC when FCU is armed " , 5 ) ; <nl> - } <nl> - else <nl> - { <nl> - / / Calibrate Extents of RC Transmitter <nl> - comm_link - > log_message ( " Calibrating RC , move sticks to full extents " , 1 ) ; <nl> - comm_link - > log_message ( " in the next 10s " , 1 ) ; <nl> - uint64_t now = board - > micros ( ) ; <nl> - <nl> - while ( board - > micros ( ) - now < 1e7 ) <nl> - { <nl> - for ( int16_t i = 0 ; i < 4 ; i + + ) <nl> - { <nl> - int32_t read_value = ( int32_t ) board - > pwmRead ( i ) ; <nl> - if ( read_value > calib_max [ i ] ) <nl> - { <nl> - calib_max [ i ] = read_value ; <nl> - } <nl> - if ( read_value < calib_min [ i ] ) <nl> - { <nl> - calib_min [ i ] = read_value ; <nl> - } <nl> - } <nl> - board - > delay_millis ( 10 ) ; <nl> - } <nl> - params - > set_param_int ( Params : : PARAM_RC_X_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] ) ; <nl> - params - > set_param_int ( Params : : PARAM_RC_Y_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] ) ; <nl> - params - > set_param_int ( Params : : PARAM_RC_Z_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] ) ; <nl> - params - > set_param_int ( Params : : PARAM_RC_F_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] ) ; <nl> - <nl> - / / Calibrate Trimmed Centers <nl> - comm_link - > log_message ( " Calibrating RC , leave sticks at center " , 1 ) ; <nl> - comm_link - > log_message ( " and Mux : : control_type_t : : THROTTLE low for next 10 seconds " , 1 ) ; <nl> - board - > delay_millis ( 5000 ) ; <nl> - now = board - > micros ( ) ; <nl> - <nl> - while ( board - > micros ( ) - now < 5e6 ) <nl> - { <nl> - for ( int16_t i = 0 ; i < 4 ; i + + ) <nl> - { <nl> - int32_t read_value = ( int32_t ) board - > pwmRead ( i ) ; <nl> - calib_sum [ i ] = calib_sum [ i ] + read_value ; <nl> - calib_count [ i ] = calib_count [ i ] + 1 ; <nl> - } <nl> - board - > delay_millis ( 20 ) ; / / RC is updated at 50 Hz <nl> - } <nl> - <nl> - params - > set_param_int ( Params : : PARAM_RC_X_CENTER , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] ) ; <nl> - params - > set_param_int ( Params : : PARAM_RC_Y_CENTER , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] ) ; <nl> - params - > set_param_int ( Params : : PARAM_RC_Z_CENTER , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] ) ; <nl> - params - > set_param_int ( Params : : PARAM_RC_F_BOTTOM , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] ) ; <nl> - } <nl> - <nl> - / / calculate Trim values ( in terms of SI units ) <nl> - if ( rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATT_CONTROL_TYPE_CHANNEL ) ) ) <nl> - { <nl> - / / in angle mode <nl> - params - > set_param_float ( Params : : PARAM_ROLL_ANGLE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLL ) <nl> - / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ) ; <nl> - params - > set_param_float ( Params : : PARAM_PITCH_ANGLE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_Y_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCH ) <nl> - / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ) ; <nl> - } <nl> - else <nl> - { <nl> - / / in rate mode <nl> - params - > set_param_float ( Params : : PARAM_ROLL_RATE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLLRATE ) <nl> - / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ) ; <nl> - params - > set_param_float ( Params : : PARAM_PITCH_RATE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_Y_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCHRATE ) <nl> - / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ) ; <nl> - } <nl> - params - > set_param_float ( Params : : PARAM_YAW_RATE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_YAWRATE ) <nl> - / ( float ) params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) ) ; <nl> - <nl> - params - > write_params ( ) ; <nl> - <nl> - comm_link - > log_message ( " Completed RC calibration " , 0 ) ; <nl> - _calibrate_rc = false ; <nl> - } <nl> - <nl> - <nl> - <nl> - } / / namespace <nl> - # endif <nl> + # ifndef RC_H_ <nl> + # define RC_H_ <nl> + <nl> + # include " mux . hpp " <nl> + # include " param . hpp " <nl> + # include " board . hpp " <nl> + # include " commlink . hpp " <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class RC { <nl> + public : <nl> + void init ( CommonState * _common_state , Board * _board , Mux * _mux , Params * _params , CommLink * _comm_link ) ; <nl> + bool rc_switch ( int16_t channel ) ; <nl> + bool receive_rc ( uint64_t now ) ; <nl> + <nl> + private : <nl> + void calibrate_rc ( ) ; <nl> + void convertPWMtoRad ( ) ; <nl> + <nl> + private : <nl> + typedef struct <nl> + { <nl> + int16_t channel ; <nl> + int16_t direction ; <nl> + } rc_switch_t ; <nl> + <nl> + typedef enum <nl> + { <nl> + PARALLEL_PWM , <nl> + CPPM , <nl> + } rc_type_t ; <nl> + <nl> + <nl> + bool _calibrate_rc ; <nl> + rc_switch_t switches [ 4 ] ; <nl> + <nl> + CommonState * common_state ; <nl> + Mux * mux ; <nl> + Params * params ; <nl> + Board * board ; <nl> + CommLink * comm_link ; <nl> + <nl> + uint64_t last_rc_receive_time = 0 ; / / receive_rc <nl> + uint64_t time_of_last_stick_deviation = 0 ; / / receive_rc <nl> + int32_t calib_max [ 4 ] = { 0 , 0 , 0 , 0 } ; <nl> + int32_t calib_min [ 4 ] = { 10000 , 10000 , 10000 , 10000 } ; <nl> + int32_t calib_sum [ 4 ] = { 0 , 0 , 0 , 0 } ; <nl> + int32_t calib_count [ 4 ] = { 0 , 0 , 0 , 0 } ; <nl> + <nl> + bool last_is_angle_control , last_is_altitude_control ; <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + void RC : : init ( CommonState * _common_state , Board * _board , Mux * _mux , Params * _params , CommLink * _comm_link ) <nl> + { <nl> + common_state = _common_state ; <nl> + mux = _mux ; <nl> + params = _params ; <nl> + board = _board ; <nl> + comm_link = _comm_link ; <nl> + <nl> + _calibrate_rc = false ; <nl> + <nl> + Mux : : control_t & rc_control = mux - > rc_control ( ) ; <nl> + rc_control . x . type = Mux : : control_type_t : : ANGLE ; <nl> + rc_control . y . type = Mux : : control_type_t : : ANGLE ; <nl> + rc_control . z . type = Mux : : control_type_t : : RATE ; <nl> + rc_control . F . type = Mux : : control_type_t : : THROTTLE ; <nl> + <nl> + rc_control . x . value = 0 ; <nl> + rc_control . y . value = 0 ; <nl> + rc_control . z . value = 0 ; <nl> + rc_control . F . value = 0 ; <nl> + <nl> + Mux : : control_t & offboard_control = mux - > offboard_control ( ) ; <nl> + offboard_control . x . active = false ; <nl> + offboard_control . y . active = false ; <nl> + offboard_control . z . active = false ; <nl> + offboard_control . F . active = false ; <nl> + <nl> + switches [ 0 ] . channel = 4 ; <nl> + switches [ 0 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_5_DIRECTION ) ; <nl> + switches [ 1 ] . channel = 5 ; <nl> + switches [ 1 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_6_DIRECTION ) ; <nl> + switches [ 2 ] . channel = 6 ; <nl> + switches [ 2 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_7_DIRECTION ) ; <nl> + switches [ 3 ] . channel = 7 ; <nl> + switches [ 3 ] . direction = params - > get_param_int ( Params : : PARAM_RC_SWITCH_8_DIRECTION ) ; <nl> + <nl> + bool is_angle_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATT_CONTROL_TYPE_CHANNEL ) ) ; <nl> + bool is_altitude_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_F_CONTROL_TYPE_CHANNEL ) ) ; <nl> + comm_link - > log_message ( CommonState : : stringf ( " Is angle / rate control = % i " , is_angle_control ) . c_str ( ) , 0 ) ; <nl> + last_is_angle_control = is_angle_control ; <nl> + comm_link - > log_message ( CommonState : : stringf ( " Is altitude / throttle control = % i " , is_altitude_control ) . c_str ( ) , 0 ) ; <nl> + last_is_altitude_control = is_altitude_control ; <nl> + } <nl> + <nl> + bool RC : : rc_switch ( int16_t channel ) <nl> + { <nl> + if ( channel < 4 | | channel > 8 ) <nl> + { <nl> + return false ; <nl> + } <nl> + if ( switches [ channel - 4 ] . direction < 0 ) <nl> + { <nl> + return board - > pwmRead ( channel ) < 1500 ; <nl> + } <nl> + else <nl> + { <nl> + return board - > pwmRead ( channel ) > 1500 ; <nl> + } <nl> + } <nl> + <nl> + void RC : : convertPWMtoRad ( ) <nl> + { <nl> + Mux : : control_t & rc_control = mux - > rc_control ( ) ; <nl> + <nl> + / / Get Roll control command out of RC <nl> + if ( rc_control . x . type = = Mux : : control_type_t : : ANGLE ) <nl> + { <nl> + rc_control . x . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - 1500 ) <nl> + * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLL ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ; <nl> + } <nl> + else if ( rc_control . x . type = = Mux : : control_type_t : : RATE ) <nl> + { <nl> + rc_control . x . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - 1500 ) <nl> + * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLLRATE ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ; <nl> + } <nl> + else if ( rc_control . x . type = = Mux : : control_type_t : : MOTOR_DIRECT ) <nl> + { <nl> + rc_control . x . value = static_cast < float > ( <nl> + board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) <nl> + ) ; <nl> + } <nl> + <nl> + / / Get Pitch control command out of RC <nl> + if ( rc_control . y . type = = Mux : : control_type_t : : ANGLE ) <nl> + { <nl> + rc_control . y . value = ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - 1500 ) <nl> + * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCH ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ; <nl> + } <nl> + else if ( rc_control . y . type = = Mux : : control_type_t : : RATE ) <nl> + { <nl> + rc_control . y . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - 1500 ) <nl> + * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCHRATE ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ; <nl> + } <nl> + else if ( rc_control . y . type = = Mux : : control_type_t : : MOTOR_DIRECT ) <nl> + { <nl> + rc_control . y . value = static_cast < float > ( <nl> + board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - 1500 <nl> + ) ; <nl> + } <nl> + <nl> + / / Get the Yaw control command type out of RC <nl> + if ( rc_control . z . type = = Mux : : control_type_t : : RATE ) <nl> + { <nl> + rc_control . z . value = ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) - 1500 ) <nl> + * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_YAWRATE ) ) / ( float ) params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) ; <nl> + } <nl> + else if ( rc_control . z . type = = Mux : : control_type_t : : MOTOR_DIRECT ) <nl> + { <nl> + rc_control . z . value = static_cast < float > ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) - 1500 ) ; <nl> + } <nl> + <nl> + / / Finally , the Mux : : control_type_t : : THROTTLE command <nl> + rc_control . F . value = ( float ) ( ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_F_BOTTOM ) ) ) <nl> + / ( float ) params - > get_param_int ( Params : : PARAM_RC_F_RANGE ) ; <nl> + } <nl> + <nl> + <nl> + bool RC : : receive_rc ( uint64_t now ) <nl> + { <nl> + if ( _calibrate_rc ) <nl> + { <nl> + calibrate_rc ( ) ; <nl> + } <nl> + <nl> + / / if it has been more than 20ms then look for new RC values and parse them <nl> + if ( now - last_rc_receive_time < 20000 ) <nl> + { <nl> + return false ; <nl> + } <nl> + last_rc_receive_time = now ; <nl> + <nl> + / / Get timestamp for deadband control lag <nl> + Mux : : control_t & rc_control = mux - > rc_control ( ) ; <nl> + <nl> + / / Figure out the desired control type from the switches and params <nl> + if ( params - > get_param_int ( Params : : PARAM_FIXED_WING ) ) <nl> + { <nl> + / / for using fixedwings <nl> + rc_control . x . type = rc_control . y . type = rc_control . z . type = Mux : : control_type_t : : MOTOR_DIRECT ; <nl> + rc_control . F . type = Mux : : control_type_t : : THROTTLE ; <nl> + } <nl> + else <nl> + { <nl> + bool is_angle_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATT_CONTROL_TYPE_CHANNEL ) ) ; <nl> + bool is_altitude_control = rc_switch ( params - > get_param_int ( Params : : PARAM_RC_F_CONTROL_TYPE_CHANNEL ) ) ; <nl> + <nl> + if ( last_is_angle_control ! = is_angle_control | | last_is_altitude_control ! = is_altitude_control ) { <nl> + comm_link - > log_message ( CommonState : : stringf ( " Is angle or rate control = % i " , is_angle_control ) . c_str ( ) , 0 ) ; <nl> + last_is_angle_control = is_angle_control ; <nl> + } <nl> + if ( last_is_altitude_control ! = is_altitude_control ) { <nl> + comm_link - > log_message ( CommonState : : stringf ( " Is altitude or throttle control = % i " , is_altitude_control ) . c_str ( ) , 0 ) ; <nl> + last_is_altitude_control = is_altitude_control ; <nl> + } <nl> + <nl> + rc_control . x . type = rc_control . y . type = is_angle_control ? Mux : : control_type_t : : ANGLE : Mux : : control_type_t : : RATE ; <nl> + rc_control . z . type = Mux : : control_type_t : : RATE ; <nl> + rc_control . F . type = is_altitude_control ? Mux : : control_type_t : : ALTITUDE : Mux : : control_type_t : : THROTTLE ; <nl> + } <nl> + <nl> + / / Interpret PWM Values from RC <nl> + convertPWMtoRad ( ) ; <nl> + <nl> + / / Set flags for attitude channels <nl> + if ( rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATTITUDE_OVERRIDE_CHANNEL ) ) <nl> + | | now - time_of_last_stick_deviation < ( uint32_t ) ( params - > get_param_int ( Params : : PARAM_OVERRIDE_LAG_TIME ) ) * 1000 ) <nl> + { <nl> + / / Pilot is in full control <nl> + rc_control . x . active = true ; <nl> + rc_control . y . active = true ; <nl> + rc_control . z . active = true ; <nl> + } <nl> + else <nl> + { <nl> + / / Check for stick deviation - if so , then the channel is active <nl> + rc_control . x . active = rc_control . y . active = rc_control . z . active = <nl> + abs ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) ) > <nl> + params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_DEVIATION ) <nl> + | | abs ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_Y_CENTER ) ) > <nl> + params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_DEVIATION ) <nl> + | | abs ( board - > pwmRead ( params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ) - params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) ) > <nl> + params - > get_param_int ( Params : : PARAM_RC_OVERRIDE_DEVIATION ) ; <nl> + if ( rc_control . x . active ) <nl> + { <nl> + / / reset override lag <nl> + time_of_last_stick_deviation = now ; <nl> + } <nl> + } <nl> + <nl> + <nl> + / / Set flags for Mux : : control_type_t : : THROTTLE channel <nl> + if ( rc_switch ( params - > get_param_int ( Params : : PARAM_RC_THROTTLE_OVERRIDE_CHANNEL ) ) ) <nl> + { <nl> + / / RC Pilot is in full control <nl> + rc_control . F . active = true ; <nl> + } <nl> + else <nl> + { <nl> + / / Onboard Control - min Mux : : control_type_t : : THROTTLE Checking will be done in mux and in the controller . <nl> + rc_control . F . active = false ; <nl> + } <nl> + <nl> + mux - > set_new_command ( true ) ; <nl> + return true ; <nl> + } <nl> + <nl> + void RC : : calibrate_rc ( ) <nl> + { <nl> + if ( common_state - > is_armed ( ) ) <nl> + { <nl> + comm_link - > log_message ( " Cannot calibrate RC when FCU is armed " , 5 ) ; <nl> + } <nl> + else <nl> + { <nl> + / / Calibrate Extents of RC Transmitter <nl> + comm_link - > log_message ( " Calibrating RC , move sticks to full extents " , 1 ) ; <nl> + comm_link - > log_message ( " in the next 10s " , 1 ) ; <nl> + uint64_t now = board - > micros ( ) ; <nl> + <nl> + while ( board - > micros ( ) - now < 1e7 ) <nl> + { <nl> + for ( int16_t i = 0 ; i < 4 ; i + + ) <nl> + { <nl> + int32_t read_value = ( int32_t ) board - > pwmRead ( i ) ; <nl> + if ( read_value > calib_max [ i ] ) <nl> + { <nl> + calib_max [ i ] = read_value ; <nl> + } <nl> + if ( read_value < calib_min [ i ] ) <nl> + { <nl> + calib_min [ i ] = read_value ; <nl> + } <nl> + } <nl> + board - > delay_millis ( 10 ) ; <nl> + } <nl> + params - > set_param_int ( Params : : PARAM_RC_X_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] ) ; <nl> + params - > set_param_int ( Params : : PARAM_RC_Y_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] ) ; <nl> + params - > set_param_int ( Params : : PARAM_RC_Z_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] ) ; <nl> + params - > set_param_int ( Params : : PARAM_RC_F_RANGE , calib_max [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] - calib_min [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] ) ; <nl> + <nl> + / / Calibrate Trimmed Centers <nl> + comm_link - > log_message ( " Calibrating RC , leave sticks at center " , 1 ) ; <nl> + comm_link - > log_message ( " and Mux : : control_type_t : : THROTTLE low for next 10 seconds " , 1 ) ; <nl> + board - > delay_millis ( 5000 ) ; <nl> + now = board - > micros ( ) ; <nl> + <nl> + while ( board - > micros ( ) - now < 5e6 ) <nl> + { <nl> + for ( int16_t i = 0 ; i < 4 ; i + + ) <nl> + { <nl> + int32_t read_value = ( int32_t ) board - > pwmRead ( i ) ; <nl> + calib_sum [ i ] = calib_sum [ i ] + read_value ; <nl> + calib_count [ i ] = calib_count [ i ] + 1 ; <nl> + } <nl> + board - > delay_millis ( 20 ) ; / / RC is updated at 50 Hz <nl> + } <nl> + <nl> + params - > set_param_int ( Params : : PARAM_RC_X_CENTER , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_X_CHANNEL ) ] ) ; <nl> + params - > set_param_int ( Params : : PARAM_RC_Y_CENTER , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_Y_CHANNEL ) ] ) ; <nl> + params - > set_param_int ( Params : : PARAM_RC_Z_CENTER , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_Z_CHANNEL ) ] ) ; <nl> + params - > set_param_int ( Params : : PARAM_RC_F_BOTTOM , calib_sum [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] / calib_count [ params - > get_param_int ( Params : : PARAM_RC_F_CHANNEL ) ] ) ; <nl> + } <nl> + <nl> + / / calculate Trim values ( in terms of SI units ) <nl> + if ( rc_switch ( params - > get_param_int ( Params : : PARAM_RC_ATT_CONTROL_TYPE_CHANNEL ) ) ) <nl> + { <nl> + / / in angle mode <nl> + params - > set_param_float ( Params : : PARAM_ROLL_ANGLE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLL ) <nl> + / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ) ; <nl> + params - > set_param_float ( Params : : PARAM_PITCH_ANGLE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_Y_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCH ) <nl> + / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ) ; <nl> + } <nl> + else <nl> + { <nl> + / / in rate mode <nl> + params - > set_param_float ( Params : : PARAM_ROLL_RATE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_X_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_ROLLRATE ) <nl> + / ( float ) params - > get_param_int ( Params : : PARAM_RC_X_RANGE ) ) ; <nl> + params - > set_param_float ( Params : : PARAM_PITCH_RATE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_Y_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_PITCHRATE ) <nl> + / ( float ) params - > get_param_int ( Params : : PARAM_RC_Y_RANGE ) ) ; <nl> + } <nl> + params - > set_param_float ( Params : : PARAM_YAW_RATE_TRIM , ( float ) ( params - > get_param_int ( Params : : PARAM_RC_Z_CENTER ) - 1500 ) * 2 . 0f * params - > get_param_float ( Params : : PARAM_RC_MAX_YAWRATE ) <nl> + / ( float ) params - > get_param_int ( Params : : PARAM_RC_Z_RANGE ) ) ; <nl> + <nl> + params - > write_params ( ) ; <nl> + <nl> + comm_link - > log_message ( " Completed RC calibration " , 0 ) ; <nl> + _calibrate_rc = false ; <nl> + } <nl> + <nl> + <nl> + <nl> + } / / namespace <nl> + # endif <nl> similarity index 96 % <nl> rename from AirLib / include / controllers / rosflight / firmware / sensors . hpp <nl> rename to AirLib / include / controllers / ros_flight / firmware / sensors . hpp <nl> mmm a / AirLib / include / controllers / rosflight / firmware / sensors . hpp <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / sensors . hpp <nl> <nl> - # pragma once <nl> - <nl> - # include " turbotrig / turbovec . h " <nl> - # include < cstdint > <nl> - # include < cstdbool > <nl> - # include " estimator . hpp " <nl> - # include " commonstate . hpp " <nl> - # include " param . hpp " <nl> - # include " board . hpp " <nl> - # include " commlink . hpp " <nl> - <nl> - namespace rosflight { <nl> - <nl> - class Sensors { <nl> - public : <nl> - / / function declarations <nl> - void init ( CommonState * _common_state , Board * _board , Estimator * _estimator , Params * _params , CommLink * _comm_link ) ; <nl> - bool update_sensors ( ) ; <nl> - <nl> - bool start_imu_calibration ( void ) ; <nl> - bool start_gyro_calibration ( void ) ; <nl> - bool gyro_calibration_complete ( void ) ; <nl> - <nl> - void get_imu_measurements ( vector_t & accel , vector_t & gyro , uint64_t & imu_time ) ; <nl> - <nl> - private : <nl> - volatile uint8_t accel_status , gyro_status , temp_status ; <nl> - float accel_scale ; <nl> - float gyro_scale ; <nl> - bool calibrating_acc_flag ; <nl> - bool calibrating_gyro_flag ; <nl> - void calibrate_accel ( void ) ; <nl> - void calibrate_gyro ( void ) ; <nl> - void correct_imu ( void ) ; <nl> - void imu_ISR ( void ) ; <nl> - bool update_imu ( void ) ; <nl> - <nl> - private : <nl> - / / IMU <nl> - vector_t _accel ; <nl> - vector_t _gyro ; <nl> - float _imu_temperature ; <nl> - uint64_t _imu_time ; <nl> - bool new_imu_data = false ; <nl> - <nl> - / / Airspeed <nl> - bool _diff_pressure_present = false ; <nl> - float _pitot_velocity , _pitot_diff_pressure , _pitot_temp ; <nl> - <nl> - / / Barometer <nl> - bool _baro_present = false ; <nl> - float _baro_altitude ; <nl> - float _baro_pressure ; <nl> - float _baro_temperature ; <nl> - <nl> - / / Sonar <nl> - bool _sonar_present = false ; <nl> - float _sonar_range ; <nl> - <nl> - / / Magnetometer <nl> - bool _mag_present = false ; <nl> - vector_t _mag ; <nl> - <nl> - / / IMU stuff <nl> - int16_t accel_raw [ 3 ] ; <nl> - int16_t gyro_raw [ 3 ] ; <nl> - int16_t temp_raw ; <nl> - <nl> - Estimator * estimator ; <nl> - CommonState * common_state ; <nl> - Params * params ; <nl> - Board * board ; <nl> - CommLink * comm_link ; <nl> - <nl> - uint32_t last_time_look_for_disarmed_sensors = 0 ; <nl> - uint32_t last_imu_update_ms = 0 ; <nl> - uint16_t calib_gyro_count = 0 ; <nl> - vector_t calib_gyro_sum = { 0 . 0f , 0 . 0f , 0 . 0f } ; <nl> - uint16_t calib_accel_count = 0 ; <nl> - vector_t calib_accel_sum = { 0 . 0f , 0 . 0f , 0 . 0f } ; <nl> - vector_t gravity = { 0 . 0f , 0 . 0f , 9 . 80665f } ; <nl> - float acc_temp_sum = 0 . 0f ; <nl> - } ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - <nl> - void Sensors : : init ( CommonState * _common_state , Board * _board , Estimator * _estimator , Params * _params , CommLink * _comm_link ) <nl> - { <nl> - common_state = _common_state ; <nl> - estimator = _estimator ; <nl> - params = _params ; <nl> - board = _board ; <nl> - comm_link = _comm_link ; <nl> - <nl> - uint16_t acc1G ; <nl> - board - > init_sensors ( acc1G , gyro_scale , params - > get_param_int ( Params : : PARAM_BOARD_REVISION ) , std : : bind ( & Sensors : : imu_ISR , this ) ) ; <nl> - accel_scale = 9 . 80665f / acc1G * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> - } <nl> - <nl> - void Sensors : : get_imu_measurements ( vector_t & accel , vector_t & gyro , uint64_t & imu_time ) <nl> - { <nl> - accel = _accel ; <nl> - gyro = _gyro ; <nl> - imu_time = _imu_time ; <nl> - } <nl> - <nl> - bool Sensors : : update_sensors ( ) <nl> - { <nl> - / / Look for disabled sensors while disarmed ( poll every 10 seconds ) <nl> - / / These sensors need power to respond , so they might not have been <nl> - / / detected on startup , but will be detected whenever power is applied <nl> - / / to the 5V rail . <nl> - if ( common_state - > is_disarmed ( ) & & ( ! _sonar_present ) ) / / | | ! _diff_pressure_present ) ) <nl> - { <nl> - uint32_t now = board - > millis ( ) ; <nl> - if ( now > ( last_time_look_for_disarmed_sensors + 500 ) ) <nl> - { <nl> - last_time_look_for_disarmed_sensors = now ; <nl> - if ( ! _sonar_present ) <nl> - { <nl> - _sonar_present = board - > is_sensor_present ( board - > SensorType : : Sonar ) ; <nl> - if ( _sonar_present ) <nl> - { <nl> - comm_link - > log_message ( " FOUND SONAR " , 0 ) ; <nl> - } <nl> - } <nl> - if ( ! _diff_pressure_present ) <nl> - { <nl> - _diff_pressure_present = board - > is_sensor_present ( board - > SensorType : : DiffPressure ) ; <nl> - if ( _diff_pressure_present ) <nl> - { <nl> - comm_link - > log_message ( " FOUND DIFF PRESS " , 0 ) ; <nl> - } <nl> - } <nl> - } <nl> - } <nl> - <nl> - if ( _baro_present ) <nl> - { <nl> - board - > read_baro ( _baro_altitude , _baro_pressure , _baro_temperature ) ; <nl> - } <nl> - <nl> - if ( _diff_pressure_present ) <nl> - { <nl> - board - > read_diff_pressure ( _pitot_diff_pressure , _pitot_temp , _pitot_velocity ) ; <nl> - } <nl> - <nl> - if ( _sonar_present ) <nl> - { <nl> - _sonar_range = board - > read_sonar ( ) ; <nl> - } <nl> - <nl> - if ( _mag_present ) <nl> - { <nl> - int16_t raw_mag [ 3 ] = { 0 , 0 , 0 } ; <nl> - board - > read_mag ( raw_mag ) ; <nl> - _mag . x = ( float ) raw_mag [ 0 ] ; <nl> - _mag . y = ( float ) raw_mag [ 1 ] ; <nl> - _mag . z = ( float ) raw_mag [ 2 ] ; <nl> - } <nl> - <nl> - / / Return whether or not we got new IMU data <nl> - return update_imu ( ) ; <nl> - } <nl> - <nl> - <nl> - bool Sensors : : start_imu_calibration ( void ) <nl> - { <nl> - comm_link - > log_message ( " Starting IMU calibration . . . " , 0 ) ; <nl> - <nl> - start_gyro_calibration ( ) ; <nl> - <nl> - calibrating_acc_flag = true ; <nl> - params - > set_param_float ( Params : : PARAM_ACC_X_BIAS , 0 . 0 ) ; <nl> - params - > set_param_float ( Params : : PARAM_ACC_Y_BIAS , 0 . 0 ) ; <nl> - params - > set_param_float ( Params : : PARAM_ACC_Z_BIAS , 0 . 0 ) ; <nl> - return true ; <nl> - } <nl> - <nl> - bool Sensors : : start_gyro_calibration ( void ) <nl> - { <nl> - comm_link - > log_message ( " Starting gyro calibration . . . " , 0 ) ; <nl> - <nl> - calibrating_gyro_flag = true ; <nl> - params - > set_param_float ( Params : : PARAM_GYRO_X_BIAS , 0 . 0 ) ; <nl> - params - > set_param_float ( Params : : PARAM_GYRO_Y_BIAS , 0 . 0 ) ; <nl> - params - > set_param_float ( Params : : PARAM_GYRO_Z_BIAS , 0 . 0 ) ; <nl> - return true ; <nl> - } <nl> - <nl> - bool Sensors : : gyro_calibration_complete ( void ) <nl> - { <nl> - return ! calibrating_gyro_flag ; <nl> - } <nl> - <nl> - <nl> - void Sensors : : imu_ISR ( void ) <nl> - { <nl> - _imu_time = board - > micros ( ) ; <nl> - new_imu_data = true ; <nl> - } <nl> - <nl> - <nl> - bool Sensors : : update_imu ( void ) <nl> - { <nl> - if ( new_imu_data ) <nl> - { <nl> - last_imu_update_ms = board - > millis ( ) ; <nl> - board - > read_accel ( accel_raw ) ; <nl> - board - > read_gyro ( gyro_raw ) ; <nl> - board - > read_temperature ( temp_raw ) ; <nl> - new_imu_data = false ; <nl> - <nl> - / / convert temperature SI units ( degC , m / s ^ 2 , rad / s ) <nl> - _imu_temperature = temp_raw / 340 . 0f + 36 . 53f ; <nl> - <nl> - / / convert to NED and SI units <nl> - _accel . x = accel_raw [ 0 ] * accel_scale ; <nl> - _accel . y = - accel_raw [ 1 ] * accel_scale ; <nl> - _accel . z = - accel_raw [ 2 ] * accel_scale ; <nl> - <nl> - _gyro . x = gyro_raw [ 0 ] * gyro_scale ; <nl> - _gyro . y = - gyro_raw [ 1 ] * gyro_scale ; <nl> - _gyro . z = - gyro_raw [ 2 ] * gyro_scale ; <nl> - <nl> - if ( calibrating_acc_flag = = true ) <nl> - calibrate_accel ( ) ; <nl> - if ( calibrating_gyro_flag ) <nl> - calibrate_gyro ( ) ; <nl> - <nl> - correct_imu ( ) ; <nl> - return true ; <nl> - } else <nl> - { <nl> - / / if we have lost 1000 IMU messages something is wrong <nl> - if ( board - > millis ( ) > last_imu_update_ms + 1000 ) <nl> - { <nl> - comm_link - > log_message ( " Lost too many IMU messages ! Reinitializing IMU . . . " , 1 ) ; <nl> - <nl> - / / change board revision and reset IMU <nl> - last_imu_update_ms = board - > millis ( ) ; <nl> - params - > set_param_int ( Params : : PARAM_BOARD_REVISION , ( params - > get_param_int ( Params : : PARAM_BOARD_REVISION ) > = 4 ) ? 5 : 2 ) ; <nl> - uint16_t acc1G ; <nl> - board - > init_imu ( acc1G , gyro_scale , params - > get_param_int ( Params : : PARAM_BOARD_REVISION ) ) ; <nl> - accel_scale = 9 . 80665f / acc1G * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> - } <nl> - return false ; <nl> - } <nl> - } <nl> - <nl> - <nl> - void Sensors : : calibrate_gyro ( ) <nl> - { <nl> - calib_gyro_sum = vector_add ( calib_gyro_sum , _gyro ) ; <nl> - calib_gyro_count + + ; <nl> - <nl> - if ( calib_gyro_count > 100 ) <nl> - { <nl> - / / Gyros are simple . Just find the average during the calibration <nl> - vector_t gyro_bias = scalar_multiply ( 1 . 0f / ( float ) calib_gyro_count , calib_gyro_sum ) ; <nl> - <nl> - if ( sqrd_norm ( gyro_bias ) < 1 . 0 ) <nl> - { <nl> - params - > set_param_float ( Params : : PARAM_GYRO_X_BIAS , gyro_bias . x ) ; <nl> - params - > set_param_float ( Params : : PARAM_GYRO_Y_BIAS , gyro_bias . y ) ; <nl> - params - > set_param_float ( Params : : PARAM_GYRO_Z_BIAS , gyro_bias . z ) ; <nl> - <nl> - / / Tell the estimator to reset it ' s bias estimate , because it should be zero now <nl> - estimator - > reset_adaptive_bias ( ) ; <nl> - } else <nl> - { <nl> - comm_link - > log_message ( " Too much movement for gyro cal " , 3 ) ; <nl> - } <nl> - <nl> - / / reset calibration in case we do it again <nl> - calibrating_gyro_flag = false ; <nl> - calib_gyro_count = 0 ; <nl> - calib_gyro_sum . x = 0 . 0f ; <nl> - calib_gyro_sum . y = 0 . 0f ; <nl> - calib_gyro_sum . z = 0 . 0f ; <nl> - } <nl> - } <nl> - <nl> - <nl> - void Sensors : : calibrate_accel ( void ) <nl> - { <nl> - calib_accel_sum = vector_add ( vector_add ( calib_accel_sum , _accel ) , gravity ) ; <nl> - acc_temp_sum + = _imu_temperature ; <nl> - calib_accel_count + + ; <nl> - <nl> - if ( calib_accel_count > 1000 ) <nl> - { <nl> - / / The temperature bias is calculated using a least - squares regression . <nl> - / / This is computationally intensive , so it is done by the onboard computer in <nl> - / / fcu_io and shipped over to the flight controller . <nl> - vector_t accel_temp_bias = { <nl> - params - > get_param_float ( Params : : PARAM_ACC_X_TEMP_COMP ) , <nl> - params - > get_param_float ( Params : : PARAM_ACC_Y_TEMP_COMP ) , <nl> - params - > get_param_float ( Params : : PARAM_ACC_Z_TEMP_COMP ) <nl> - } ; <nl> - <nl> - / / Figure out the proper accel bias . <nl> - / / We have to consider the contribution of temperature during the calibration , <nl> - / / Which is why this line is so confusing . What we are doing , is first removing <nl> - / / the contribution of temperature to the measurements during the calibration , <nl> - / / Then we are dividing by the number of measurements . <nl> - vector_t accel_bias = scalar_multiply ( 1 . 0f / ( float ) calib_accel_count , vector_sub ( calib_accel_sum , scalar_multiply ( acc_temp_sum , accel_temp_bias ) ) ) ; <nl> - <nl> - / / Sanity Check - <nl> - / / If the accelerometer is upside down or being spun around during the calibration , <nl> - / / then don ' t do anything <nl> - if ( sqrd_norm ( accel_bias ) < 4 . 5 ) <nl> - { <nl> - params - > set_param_float ( Params : : PARAM_ACC_X_BIAS , accel_bias . x ) ; <nl> - params - > set_param_float ( Params : : PARAM_ACC_Y_BIAS , accel_bias . y ) ; <nl> - params - > set_param_float ( Params : : PARAM_ACC_Z_BIAS , accel_bias . z ) ; <nl> - comm_link - > log_message ( " IMU offsets captured " , 0 ) ; <nl> - <nl> - / / reset the estimated state <nl> - estimator - > reset_state ( ) ; <nl> - calibrating_acc_flag = false ; <nl> - } else <nl> - { <nl> - / / check for bad _accel_scale <nl> - if ( sqrd_norm ( accel_bias ) > 4 . 5 * 4 . 5 & & sqrd_norm ( accel_bias ) < 5 . 5 * 5 . 5 ) <nl> - { <nl> - comm_link - > log_message ( " Detected bad IMU accel scale value " , 4 ) ; <nl> - params - > set_param_float ( Params : : PARAM_ACCEL_SCALE , 2 . 0f * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ) ; <nl> - accel_scale * = params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> - params - > write_params ( ) ; <nl> - } else if ( sqrd_norm ( accel_bias ) > 9 . 0f * 9 . 0f & & sqrd_norm ( accel_bias ) < 11 . 0 * 11 . 0 ) <nl> - { <nl> - comm_link - > log_message ( " Detected bad IMU accel scale value " , 4 ) ; <nl> - params - > set_param_float ( Params : : PARAM_ACCEL_SCALE , 0 . 5f * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ) ; <nl> - accel_scale * = params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> - params - > write_params ( ) ; <nl> - } else <nl> - { <nl> - comm_link - > log_message ( " Too much movement for IMU cal " , 2 ) ; <nl> - calibrating_acc_flag = false ; <nl> - } <nl> - } <nl> - <nl> - / / reset calibration in case we do it again <nl> - calib_accel_count = 0 ; <nl> - calib_accel_sum . x = 0 . 0f ; <nl> - calib_accel_sum . y = 0 . 0f ; <nl> - calib_accel_sum . z = 0 . 0f ; <nl> - acc_temp_sum = 0 . 0f ; <nl> - } <nl> - } <nl> - <nl> - <nl> - void Sensors : : correct_imu ( void ) <nl> - { <nl> - / / correct according to known biases and temperature compensation <nl> - _accel . x - = params - > get_param_float ( Params : : PARAM_ACC_X_TEMP_COMP ) * _imu_temperature + params - > get_param_float ( Params : : PARAM_ACC_X_BIAS ) ; <nl> - _accel . y - = params - > get_param_float ( Params : : PARAM_ACC_Y_TEMP_COMP ) * _imu_temperature + params - > get_param_float ( Params : : PARAM_ACC_Y_BIAS ) ; <nl> - _accel . z - = params - > get_param_float ( Params : : PARAM_ACC_Z_TEMP_COMP ) * _imu_temperature + params - > get_param_float ( Params : : PARAM_ACC_Z_BIAS ) ; <nl> - <nl> - _gyro . x - = params - > get_param_float ( Params : : PARAM_GYRO_X_BIAS ) ; <nl> - _gyro . y - = params - > get_param_float ( Params : : PARAM_GYRO_Y_BIAS ) ; <nl> - _gyro . z - = params - > get_param_float ( Params : : PARAM_GYRO_Z_BIAS ) ; <nl> - } <nl> - <nl> - <nl> - <nl> + # pragma once <nl> + <nl> + # include " turbotrig / turbovec . h " <nl> + # include < cstdint > <nl> + # include < cstdbool > <nl> + # include " estimator . hpp " <nl> + # include " commonstate . hpp " <nl> + # include " param . hpp " <nl> + # include " board . hpp " <nl> + # include " commlink . hpp " <nl> + <nl> + namespace ros_flight { <nl> + <nl> + class Sensors { <nl> + public : <nl> + / / function declarations <nl> + void init ( CommonState * _common_state , Board * _board , Estimator * _estimator , Params * _params , CommLink * _comm_link ) ; <nl> + bool update_sensors ( ) ; <nl> + <nl> + bool start_imu_calibration ( void ) ; <nl> + bool start_gyro_calibration ( void ) ; <nl> + bool gyro_calibration_complete ( void ) ; <nl> + <nl> + void get_imu_measurements ( vector_t & accel , vector_t & gyro , uint64_t & imu_time ) ; <nl> + <nl> + private : <nl> + volatile uint8_t accel_status , gyro_status , temp_status ; <nl> + float accel_scale ; <nl> + float gyro_scale ; <nl> + bool calibrating_acc_flag ; <nl> + bool calibrating_gyro_flag ; <nl> + void calibrate_accel ( void ) ; <nl> + void calibrate_gyro ( void ) ; <nl> + void correct_imu ( void ) ; <nl> + void imu_ISR ( void ) ; <nl> + bool update_imu ( void ) ; <nl> + <nl> + private : <nl> + / / IMU <nl> + vector_t _accel ; <nl> + vector_t _gyro ; <nl> + float _imu_temperature ; <nl> + uint64_t _imu_time ; <nl> + bool new_imu_data = false ; <nl> + <nl> + / / Airspeed <nl> + bool _diff_pressure_present = false ; <nl> + float _pitot_velocity , _pitot_diff_pressure , _pitot_temp ; <nl> + <nl> + / / Barometer <nl> + bool _baro_present = false ; <nl> + float _baro_altitude ; <nl> + float _baro_pressure ; <nl> + float _baro_temperature ; <nl> + <nl> + / / Sonar <nl> + bool _sonar_present = false ; <nl> + float _sonar_range ; <nl> + <nl> + / / Magnetometer <nl> + bool _mag_present = false ; <nl> + vector_t _mag ; <nl> + <nl> + / / IMU stuff <nl> + int16_t accel_raw [ 3 ] ; <nl> + int16_t gyro_raw [ 3 ] ; <nl> + int16_t temp_raw ; <nl> + <nl> + Estimator * estimator ; <nl> + CommonState * common_state ; <nl> + Params * params ; <nl> + Board * board ; <nl> + CommLink * comm_link ; <nl> + <nl> + uint32_t last_time_look_for_disarmed_sensors = 0 ; <nl> + uint32_t last_imu_update_ms = 0 ; <nl> + uint16_t calib_gyro_count = 0 ; <nl> + vector_t calib_gyro_sum = { 0 . 0f , 0 . 0f , 0 . 0f } ; <nl> + uint16_t calib_accel_count = 0 ; <nl> + vector_t calib_accel_sum = { 0 . 0f , 0 . 0f , 0 . 0f } ; <nl> + vector_t gravity = { 0 . 0f , 0 . 0f , 9 . 80665f } ; <nl> + float acc_temp_sum = 0 . 0f ; <nl> + } ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + <nl> + void Sensors : : init ( CommonState * _common_state , Board * _board , Estimator * _estimator , Params * _params , CommLink * _comm_link ) <nl> + { <nl> + common_state = _common_state ; <nl> + estimator = _estimator ; <nl> + params = _params ; <nl> + board = _board ; <nl> + comm_link = _comm_link ; <nl> + <nl> + uint16_t acc1G ; <nl> + board - > init_sensors ( acc1G , gyro_scale , params - > get_param_int ( Params : : PARAM_BOARD_REVISION ) , std : : bind ( & Sensors : : imu_ISR , this ) ) ; <nl> + accel_scale = 9 . 80665f / acc1G * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> + } <nl> + <nl> + void Sensors : : get_imu_measurements ( vector_t & accel , vector_t & gyro , uint64_t & imu_time ) <nl> + { <nl> + accel = _accel ; <nl> + gyro = _gyro ; <nl> + imu_time = _imu_time ; <nl> + } <nl> + <nl> + bool Sensors : : update_sensors ( ) <nl> + { <nl> + / / Look for disabled sensors while disarmed ( poll every 10 seconds ) <nl> + / / These sensors need power to respond , so they might not have been <nl> + / / detected on startup , but will be detected whenever power is applied <nl> + / / to the 5V rail . <nl> + if ( common_state - > is_disarmed ( ) & & ( ! _sonar_present ) ) / / | | ! _diff_pressure_present ) ) <nl> + { <nl> + uint32_t now = board - > millis ( ) ; <nl> + if ( now > ( last_time_look_for_disarmed_sensors + 500 ) ) <nl> + { <nl> + last_time_look_for_disarmed_sensors = now ; <nl> + if ( ! _sonar_present ) <nl> + { <nl> + _sonar_present = board - > is_sensor_present ( board - > SensorType : : Sonar ) ; <nl> + if ( _sonar_present ) <nl> + { <nl> + comm_link - > log_message ( " FOUND SONAR " , 0 ) ; <nl> + } <nl> + } <nl> + if ( ! _diff_pressure_present ) <nl> + { <nl> + _diff_pressure_present = board - > is_sensor_present ( board - > SensorType : : DiffPressure ) ; <nl> + if ( _diff_pressure_present ) <nl> + { <nl> + comm_link - > log_message ( " FOUND DIFF PRESS " , 0 ) ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + if ( _baro_present ) <nl> + { <nl> + board - > read_baro ( _baro_altitude , _baro_pressure , _baro_temperature ) ; <nl> + } <nl> + <nl> + if ( _diff_pressure_present ) <nl> + { <nl> + board - > read_diff_pressure ( _pitot_diff_pressure , _pitot_temp , _pitot_velocity ) ; <nl> + } <nl> + <nl> + if ( _sonar_present ) <nl> + { <nl> + _sonar_range = board - > read_sonar ( ) ; <nl> + } <nl> + <nl> + if ( _mag_present ) <nl> + { <nl> + int16_t raw_mag [ 3 ] = { 0 , 0 , 0 } ; <nl> + board - > read_mag ( raw_mag ) ; <nl> + _mag . x = ( float ) raw_mag [ 0 ] ; <nl> + _mag . y = ( float ) raw_mag [ 1 ] ; <nl> + _mag . z = ( float ) raw_mag [ 2 ] ; <nl> + } <nl> + <nl> + / / Return whether or not we got new IMU data <nl> + return update_imu ( ) ; <nl> + } <nl> + <nl> + <nl> + bool Sensors : : start_imu_calibration ( void ) <nl> + { <nl> + comm_link - > log_message ( " Starting IMU calibration . . . " , 0 ) ; <nl> + <nl> + start_gyro_calibration ( ) ; <nl> + <nl> + calibrating_acc_flag = true ; <nl> + params - > set_param_float ( Params : : PARAM_ACC_X_BIAS , 0 . 0 ) ; <nl> + params - > set_param_float ( Params : : PARAM_ACC_Y_BIAS , 0 . 0 ) ; <nl> + params - > set_param_float ( Params : : PARAM_ACC_Z_BIAS , 0 . 0 ) ; <nl> + return true ; <nl> + } <nl> + <nl> + bool Sensors : : start_gyro_calibration ( void ) <nl> + { <nl> + comm_link - > log_message ( " Starting gyro calibration . . . " , 0 ) ; <nl> + <nl> + calibrating_gyro_flag = true ; <nl> + params - > set_param_float ( Params : : PARAM_GYRO_X_BIAS , 0 . 0 ) ; <nl> + params - > set_param_float ( Params : : PARAM_GYRO_Y_BIAS , 0 . 0 ) ; <nl> + params - > set_param_float ( Params : : PARAM_GYRO_Z_BIAS , 0 . 0 ) ; <nl> + return true ; <nl> + } <nl> + <nl> + bool Sensors : : gyro_calibration_complete ( void ) <nl> + { <nl> + return ! calibrating_gyro_flag ; <nl> + } <nl> + <nl> + <nl> + void Sensors : : imu_ISR ( void ) <nl> + { <nl> + _imu_time = board - > micros ( ) ; <nl> + new_imu_data = true ; <nl> + } <nl> + <nl> + <nl> + bool Sensors : : update_imu ( void ) <nl> + { <nl> + if ( new_imu_data ) <nl> + { <nl> + last_imu_update_ms = board - > millis ( ) ; <nl> + board - > read_accel ( accel_raw ) ; <nl> + board - > read_gyro ( gyro_raw ) ; <nl> + board - > read_temperature ( temp_raw ) ; <nl> + new_imu_data = false ; <nl> + <nl> + / / convert temperature SI units ( degC , m / s ^ 2 , rad / s ) <nl> + _imu_temperature = temp_raw / 340 . 0f + 36 . 53f ; <nl> + <nl> + / / convert to NED and SI units <nl> + _accel . x = accel_raw [ 0 ] * accel_scale ; <nl> + _accel . y = - accel_raw [ 1 ] * accel_scale ; <nl> + _accel . z = - accel_raw [ 2 ] * accel_scale ; <nl> + <nl> + _gyro . x = gyro_raw [ 0 ] * gyro_scale ; <nl> + _gyro . y = - gyro_raw [ 1 ] * gyro_scale ; <nl> + _gyro . z = - gyro_raw [ 2 ] * gyro_scale ; <nl> + <nl> + if ( calibrating_acc_flag = = true ) <nl> + calibrate_accel ( ) ; <nl> + if ( calibrating_gyro_flag ) <nl> + calibrate_gyro ( ) ; <nl> + <nl> + correct_imu ( ) ; <nl> + return true ; <nl> + } else <nl> + { <nl> + / / if we have lost 1000 IMU messages something is wrong <nl> + if ( board - > millis ( ) > last_imu_update_ms + 1000 ) <nl> + { <nl> + comm_link - > log_message ( " Lost too many IMU messages ! Reinitializing IMU . . . " , 1 ) ; <nl> + <nl> + / / change board revision and reset IMU <nl> + last_imu_update_ms = board - > millis ( ) ; <nl> + params - > set_param_int ( Params : : PARAM_BOARD_REVISION , ( params - > get_param_int ( Params : : PARAM_BOARD_REVISION ) > = 4 ) ? 5 : 2 ) ; <nl> + uint16_t acc1G ; <nl> + board - > init_imu ( acc1G , gyro_scale , params - > get_param_int ( Params : : PARAM_BOARD_REVISION ) ) ; <nl> + accel_scale = 9 . 80665f / acc1G * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> + } <nl> + return false ; <nl> + } <nl> + } <nl> + <nl> + <nl> + void Sensors : : calibrate_gyro ( ) <nl> + { <nl> + calib_gyro_sum = vector_add ( calib_gyro_sum , _gyro ) ; <nl> + calib_gyro_count + + ; <nl> + <nl> + if ( calib_gyro_count > 100 ) <nl> + { <nl> + / / Gyros are simple . Just find the average during the calibration <nl> + vector_t gyro_bias = scalar_multiply ( 1 . 0f / ( float ) calib_gyro_count , calib_gyro_sum ) ; <nl> + <nl> + if ( sqrd_norm ( gyro_bias ) < 1 . 0 ) <nl> + { <nl> + params - > set_param_float ( Params : : PARAM_GYRO_X_BIAS , gyro_bias . x ) ; <nl> + params - > set_param_float ( Params : : PARAM_GYRO_Y_BIAS , gyro_bias . y ) ; <nl> + params - > set_param_float ( Params : : PARAM_GYRO_Z_BIAS , gyro_bias . z ) ; <nl> + <nl> + / / Tell the estimator to reset it ' s bias estimate , because it should be zero now <nl> + estimator - > reset_adaptive_bias ( ) ; <nl> + } else <nl> + { <nl> + comm_link - > log_message ( " Too much movement for gyro cal " , 3 ) ; <nl> + } <nl> + <nl> + / / reset calibration in case we do it again <nl> + calibrating_gyro_flag = false ; <nl> + calib_gyro_count = 0 ; <nl> + calib_gyro_sum . x = 0 . 0f ; <nl> + calib_gyro_sum . y = 0 . 0f ; <nl> + calib_gyro_sum . z = 0 . 0f ; <nl> + } <nl> + } <nl> + <nl> + <nl> + void Sensors : : calibrate_accel ( void ) <nl> + { <nl> + calib_accel_sum = vector_add ( vector_add ( calib_accel_sum , _accel ) , gravity ) ; <nl> + acc_temp_sum + = _imu_temperature ; <nl> + calib_accel_count + + ; <nl> + <nl> + if ( calib_accel_count > 1000 ) <nl> + { <nl> + / / The temperature bias is calculated using a least - squares regression . <nl> + / / This is computationally intensive , so it is done by the onboard computer in <nl> + / / fcu_io and shipped over to the flight controller . <nl> + vector_t accel_temp_bias = { <nl> + params - > get_param_float ( Params : : PARAM_ACC_X_TEMP_COMP ) , <nl> + params - > get_param_float ( Params : : PARAM_ACC_Y_TEMP_COMP ) , <nl> + params - > get_param_float ( Params : : PARAM_ACC_Z_TEMP_COMP ) <nl> + } ; <nl> + <nl> + / / Figure out the proper accel bias . <nl> + / / We have to consider the contribution of temperature during the calibration , <nl> + / / Which is why this line is so confusing . What we are doing , is first removing <nl> + / / the contribution of temperature to the measurements during the calibration , <nl> + / / Then we are dividing by the number of measurements . <nl> + vector_t accel_bias = scalar_multiply ( 1 . 0f / ( float ) calib_accel_count , vector_sub ( calib_accel_sum , scalar_multiply ( acc_temp_sum , accel_temp_bias ) ) ) ; <nl> + <nl> + / / Sanity Check - <nl> + / / If the accelerometer is upside down or being spun around during the calibration , <nl> + / / then don ' t do anything <nl> + if ( sqrd_norm ( accel_bias ) < 4 . 5 ) <nl> + { <nl> + params - > set_param_float ( Params : : PARAM_ACC_X_BIAS , accel_bias . x ) ; <nl> + params - > set_param_float ( Params : : PARAM_ACC_Y_BIAS , accel_bias . y ) ; <nl> + params - > set_param_float ( Params : : PARAM_ACC_Z_BIAS , accel_bias . z ) ; <nl> + comm_link - > log_message ( " IMU offsets captured " , 0 ) ; <nl> + <nl> + / / reset the estimated state <nl> + estimator - > reset_state ( ) ; <nl> + calibrating_acc_flag = false ; <nl> + } else <nl> + { <nl> + / / check for bad _accel_scale <nl> + if ( sqrd_norm ( accel_bias ) > 4 . 5 * 4 . 5 & & sqrd_norm ( accel_bias ) < 5 . 5 * 5 . 5 ) <nl> + { <nl> + comm_link - > log_message ( " Detected bad IMU accel scale value " , 4 ) ; <nl> + params - > set_param_float ( Params : : PARAM_ACCEL_SCALE , 2 . 0f * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ) ; <nl> + accel_scale * = params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> + params - > write_params ( ) ; <nl> + } else if ( sqrd_norm ( accel_bias ) > 9 . 0f * 9 . 0f & & sqrd_norm ( accel_bias ) < 11 . 0 * 11 . 0 ) <nl> + { <nl> + comm_link - > log_message ( " Detected bad IMU accel scale value " , 4 ) ; <nl> + params - > set_param_float ( Params : : PARAM_ACCEL_SCALE , 0 . 5f * params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ) ; <nl> + accel_scale * = params - > get_param_float ( Params : : PARAM_ACCEL_SCALE ) ; <nl> + params - > write_params ( ) ; <nl> + } else <nl> + { <nl> + comm_link - > log_message ( " Too much movement for IMU cal " , 2 ) ; <nl> + calibrating_acc_flag = false ; <nl> + } <nl> + } <nl> + <nl> + / / reset calibration in case we do it again <nl> + calib_accel_count = 0 ; <nl> + calib_accel_sum . x = 0 . 0f ; <nl> + calib_accel_sum . y = 0 . 0f ; <nl> + calib_accel_sum . z = 0 . 0f ; <nl> + acc_temp_sum = 0 . 0f ; <nl> + } <nl> + } <nl> + <nl> + <nl> + void Sensors : : correct_imu ( void ) <nl> + { <nl> + / / correct according to known biases and temperature compensation <nl> + _accel . x - = params - > get_param_float ( Params : : PARAM_ACC_X_TEMP_COMP ) * _imu_temperature + params - > get_param_float ( Params : : PARAM_ACC_X_BIAS ) ; <nl> + _accel . y - = params - > get_param_float ( Params : : PARAM_ACC_Y_TEMP_COMP ) * _imu_temperature + params - > get_param_float ( Params : : PARAM_ACC_Y_BIAS ) ; <nl> + _accel . z - = params - > get_param_float ( Params : : PARAM_ACC_Z_TEMP_COMP ) * _imu_temperature + params - > get_param_float ( Params : : PARAM_ACC_Z_BIAS ) ; <nl> + <nl> + _gyro . x - = params - > get_param_float ( Params : : PARAM_GYRO_X_BIAS ) ; <nl> + _gyro . y - = params - > get_param_float ( Params : : PARAM_GYRO_Y_BIAS ) ; <nl> + _gyro . z - = params - > get_param_float ( Params : : PARAM_GYRO_Z_BIAS ) ; <nl> + } <nl> + <nl> + <nl> + <nl> } / / namespace <nl> \ No newline at end of file <nl> similarity index 97 % <nl> rename from AirLib / include / controllers / rosflight / firmware / turbotrig / turbotrig . h <nl> rename to AirLib / include / controllers / ros_flight / firmware / turbotrig / turbotrig . h <nl> mmm a / AirLib / include / controllers / rosflight / firmware / turbotrig / turbotrig . h <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / turbotrig / turbotrig . h <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdint > <nl> - <nl> - / / float - based wrappers <nl> - float atan2_approx ( float y , float x ) ; <nl> - float asin_approx ( float x ) ; <nl> - <nl> - / / turbo - speed trig approximation <nl> - int32_t turboatan2 ( int32_t y , int32_t x ) ; <nl> - int32_t turboatan ( int32_t x ) ; <nl> - int32_t turboasin ( int32_t x ) ; <nl> - int32_t turbocos ( int32_t x ) ; <nl> - int32_t turbosin ( int32_t x ) ; <nl> - int32_t sign ( int32_t y ) ; <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - int16_t atan_lookup_table [ 1001 ] = <nl> - { <nl> - 0 , 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , <nl> - 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , 59 , 60 , 61 , 62 , 63 , 64 , 65 , 66 , 67 , 68 , <nl> - 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100 , <nl> - 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , 123 , 124 , 125 , <nl> - 126 , 127 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , <nl> - 150 , 151 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , <nl> - 175 , 176 , 177 , 178 , 179 , 180 , 180 , 181 , 182 , 183 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 192 , 193 , 194 , 195 , 196 , 197 , 198 , <nl> - 199 , 200 , 201 , 202 , 203 , 204 , 205 , 206 , 206 , 207 , 208 , 209 , 210 , 211 , 212 , 213 , 214 , 215 , 216 , 217 , 218 , 219 , 220 , 221 , 222 , <nl> - 223 , 224 , 225 , 226 , 227 , 227 , 228 , 229 , 230 , 231 , 232 , 233 , 234 , 235 , 236 , 237 , 238 , 239 , 240 , 241 , 242 , 243 , 244 , 244 , 245 , <nl> - 246 , 247 , 248 , 249 , 250 , 251 , 252 , 253 , 254 , 255 , 256 , 257 , 258 , 259 , 259 , 260 , 261 , 262 , 263 , 264 , 265 , 266 , 267 , 268 , 269 , <nl> - 270 , 271 , 272 , 273 , 273 , 274 , 275 , 276 , 277 , 278 , 279 , 280 , 281 , 282 , 283 , 284 , 285 , 285 , 286 , 287 , 288 , 289 , 290 , 291 , 292 , <nl> - 293 , 294 , 295 , 296 , 296 , 297 , 298 , 299 , 300 , 301 , 302 , 303 , 304 , 305 , 306 , 306 , 307 , 308 , 309 , 310 , 311 , 312 , 313 , 314 , 315 , <nl> - 316 , 316 , 317 , 318 , 319 , 320 , 321 , 322 , 323 , 324 , 325 , 325 , 326 , 327 , 328 , 329 , 330 , 331 , 332 , 333 , 333 , 334 , 335 , 336 , 337 , <nl> - 338 , 339 , 340 , 341 , 342 , 342 , 343 , 344 , 345 , 346 , 347 , 348 , 349 , 349 , 350 , 351 , 352 , 353 , 354 , 355 , 356 , 357 , 357 , 358 , 359 , <nl> - 360 , 361 , 362 , 363 , 364 , 364 , 365 , 366 , 367 , 368 , 369 , 370 , 370 , 371 , 372 , 373 , 374 , 375 , 376 , 377 , 377 , 378 , 379 , 380 , 381 , <nl> - 382 , 383 , 383 , 384 , 385 , 386 , 387 , 388 , 389 , 389 , 390 , 391 , 392 , 393 , 394 , 395 , 395 , 396 , 397 , 398 , 399 , 400 , 401 , 401 , 402 , <nl> - 403 , 404 , 405 , 406 , 406 , 407 , 408 , 409 , 410 , 411 , 411 , 412 , 413 , 414 , 415 , 416 , 417 , 417 , 418 , 419 , 420 , 421 , 422 , 422 , 423 , <nl> - 424 , 425 , 426 , 427 , 427 , 428 , 429 , 430 , 431 , 431 , 432 , 433 , 434 , 435 , 436 , 436 , 437 , 438 , 439 , 440 , 440 , 441 , 442 , 443 , 444 , <nl> - 445 , 445 , 446 , 447 , 448 , 449 , 449 , 450 , 451 , 452 , 453 , 454 , 454 , 455 , 456 , 457 , 458 , 458 , 459 , 460 , 461 , 462 , 462 , 463 , 464 , <nl> - 465 , 466 , 466 , 467 , 468 , 469 , 470 , 470 , 471 , 472 , 473 , 473 , 474 , 475 , 476 , 477 , 477 , 478 , 479 , 480 , 481 , 481 , 482 , 483 , 484 , <nl> - 485 , 485 , 486 , 487 , 488 , 488 , 489 , 490 , 491 , 492 , 492 , 493 , 494 , 495 , 495 , 496 , 497 , 498 , 498 , 499 , 500 , 501 , 502 , 502 , 503 , <nl> - 504 , 505 , 505 , 506 , 507 , 508 , 508 , 509 , 510 , 511 , 512 , 512 , 513 , 514 , 515 , 515 , 516 , 517 , 518 , 518 , 519 , 520 , 521 , 521 , 522 , <nl> - 523 , 524 , 524 , 525 , 526 , 527 , 527 , 528 , 529 , 530 , 530 , 531 , 532 , 533 , 533 , 534 , 535 , 535 , 536 , 537 , 538 , 538 , 539 , 540 , 541 , <nl> - 541 , 542 , 543 , 544 , 544 , 545 , 546 , 547 , 547 , 548 , 549 , 549 , 550 , 551 , 552 , 552 , 553 , 554 , 554 , 555 , 556 , 557 , 557 , 558 , 559 , <nl> - 560 , 560 , 561 , 562 , 562 , 563 , 564 , 565 , 565 , 566 , 567 , 567 , 568 , 569 , 570 , 570 , 571 , 572 , 572 , 573 , 574 , 574 , 575 , 576 , 577 , <nl> - 577 , 578 , 579 , 579 , 580 , 581 , 581 , 582 , 583 , 584 , 584 , 585 , 586 , 586 , 587 , 588 , 588 , 589 , 590 , 590 , 591 , 592 , 593 , 593 , 594 , <nl> - 595 , 595 , 596 , 597 , 597 , 598 , 599 , 599 , 600 , 601 , 601 , 602 , 603 , 603 , 604 , 605 , 606 , 606 , 607 , 608 , 608 , 609 , 610 , 610 , 611 , <nl> - 612 , 612 , 613 , 614 , 614 , 615 , 616 , 616 , 617 , 618 , 618 , 619 , 620 , 620 , 621 , 622 , 622 , 623 , 624 , 624 , 625 , 625 , 626 , 627 , 627 , <nl> - 628 , 629 , 629 , 630 , 631 , 631 , 632 , 633 , 633 , 634 , 635 , 635 , 636 , 637 , 637 , 638 , 639 , 639 , 640 , 640 , 641 , 642 , 642 , 643 , 644 , <nl> - 644 , 645 , 646 , 646 , 647 , 647 , 648 , 649 , 649 , 650 , 651 , 651 , 652 , 653 , 653 , 654 , 654 , 655 , 656 , 656 , 657 , 658 , 658 , 659 , 659 , <nl> - 660 , 661 , 661 , 662 , 663 , 663 , 664 , 664 , 665 , 666 , 666 , 667 , 667 , 668 , 669 , 669 , 670 , 671 , 671 , 672 , 672 , 673 , 674 , 674 , 675 , <nl> - 675 , 676 , 677 , 677 , 678 , 678 , 679 , 680 , 680 , 681 , 682 , 682 , 683 , 683 , 684 , 685 , 685 , 686 , 686 , 687 , 688 , 688 , 689 , 689 , 690 , <nl> - 690 , 691 , 692 , 692 , 693 , 693 , 694 , 695 , 695 , 696 , 696 , 697 , 698 , 698 , 699 , 699 , 700 , 701 , 701 , 702 , 702 , 703 , 703 , 704 , 705 , <nl> - 705 , 706 , 706 , 707 , 707 , 708 , 709 , 709 , 710 , 710 , 711 , 711 , 712 , 713 , 713 , 714 , 714 , 715 , 715 , 716 , 717 , 717 , 718 , 718 , 719 , <nl> - 719 , 720 , 721 , 721 , 722 , 722 , 723 , 723 , 724 , 725 , 725 , 726 , 726 , 727 , 727 , 728 , 728 , 729 , 730 , 730 , 731 , 731 , 732 , 732 , 733 , <nl> - 733 , 734 , 735 , 735 , 736 , 736 , 737 , 737 , 738 , 738 , 739 , 739 , 740 , 741 , 741 , 742 , 742 , 743 , 743 , 744 , 744 , 745 , 745 , 746 , 746 , <nl> - 747 , 748 , 748 , 749 , 749 , 750 , 750 , 751 , 751 , 752 , 752 , 753 , 753 , 754 , 755 , 755 , 756 , 756 , 757 , 757 , 758 , 758 , 759 , 759 , 760 , <nl> - 760 , 761 , 761 , 762 , 762 , 763 , 763 , 764 , 764 , 765 , 766 , 766 , 767 , 767 , 768 , 768 , 769 , 769 , 770 , 770 , 771 , 771 , 772 , 772 , 773 , <nl> - 773 , 774 , 774 , 775 , 775 , 776 , 776 , 777 , 777 , 778 , 778 , 779 , 779 , 780 , 780 , 781 , 781 , 782 , 782 , 783 , 783 , 784 , 784 , 785 <nl> - } ; <nl> - <nl> - int16_t asin_lookup_table [ 1000 ] = <nl> - { <nl> - 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , <nl> - 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , <nl> - 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , 59 , 60 , 61 , 62 , 63 , 64 , <nl> - 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , <nl> - 86 , 87 , 88 , 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , <nl> - 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , <nl> - 123 , 124 , 125 , 126 , 127 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , <nl> - 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , 151 , 152 , 153 , 154 , 155 , 156 , <nl> - 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , <nl> - 174 , 175 , 176 , 177 , 178 , 179 , 180 , 182 , 183 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , <nl> - 192 , 193 , 194 , 195 , 196 , 197 , 198 , 199 , 200 , 201 , 202 , 203 , 204 , 205 , 206 , 207 , 208 , <nl> - 209 , 210 , 211 , 212 , 213 , 214 , 215 , 216 , 217 , 218 , 219 , 220 , 221 , 222 , 223 , 224 , 225 , <nl> - 226 , 227 , 228 , 230 , 231 , 232 , 233 , 234 , 235 , 236 , 237 , 238 , 239 , 240 , 241 , 242 , 243 , <nl> - 244 , 245 , 246 , 247 , 248 , 249 , 250 , 251 , 252 , 253 , 254 , 255 , 256 , 257 , 258 , 259 , 260 , <nl> - 261 , 263 , 264 , 265 , 266 , 267 , 268 , 269 , 270 , 271 , 272 , 273 , 274 , 275 , 276 , 277 , 278 , <nl> - 279 , 280 , 281 , 282 , 283 , 284 , 285 , 286 , 287 , 289 , 290 , 291 , 292 , 293 , 294 , 295 , 296 , <nl> - 297 , 298 , 299 , 300 , 301 , 302 , 303 , 304 , 305 , 306 , 307 , 308 , 309 , 310 , 312 , 313 , 314 , <nl> - 315 , 316 , 317 , 318 , 319 , 320 , 321 , 322 , 323 , 324 , 325 , 326 , 327 , 328 , 329 , 331 , 332 , <nl> - 333 , 334 , 335 , 336 , 337 , 338 , 339 , 340 , 341 , 342 , 343 , 344 , 345 , 346 , 347 , 349 , 350 , <nl> - 351 , 352 , 353 , 354 , 355 , 356 , 357 , 358 , 359 , 360 , 361 , 362 , 363 , 365 , 366 , 367 , 368 , <nl> - 369 , 370 , 371 , 372 , 373 , 374 , 375 , 376 , 377 , 379 , 380 , 381 , 382 , 383 , 384 , 385 , 386 , <nl> - 387 , 388 , 389 , 390 , 391 , 393 , 394 , 395 , 396 , 397 , 398 , 399 , 400 , 401 , 402 , 403 , 404 , <nl> - 406 , 407 , 408 , 409 , 410 , 411 , 412 , 413 , 414 , 415 , 416 , 418 , 419 , 420 , 421 , 422 , 423 , <nl> - 424 , 425 , 426 , 427 , 429 , 430 , 431 , 432 , 433 , 434 , 435 , 436 , 437 , 438 , 440 , 441 , 442 , <nl> - 443 , 444 , 445 , 446 , 447 , 448 , 450 , 451 , 452 , 453 , 454 , 455 , 456 , 457 , 458 , 460 , 461 , <nl> - 462 , 463 , 464 , 465 , 466 , 467 , 469 , 470 , 471 , 472 , 473 , 474 , 475 , 476 , 477 , 479 , 480 , <nl> - 481 , 482 , 483 , 484 , 485 , 487 , 488 , 489 , 490 , 491 , 492 , 493 , 494 , 496 , 497 , 498 , 499 , <nl> - 500 , 501 , 502 , 504 , 505 , 506 , 507 , 508 , 509 , 510 , 512 , 513 , 514 , 515 , 516 , 517 , 518 , <nl> - 520 , 521 , 522 , 523 , 524 , 525 , 527 , 528 , 529 , 530 , 531 , 532 , 534 , 535 , 536 , 537 , 538 , <nl> - 539 , 541 , 542 , 543 , 544 , 545 , 546 , 548 , 549 , 550 , 551 , 552 , 553 , 555 , 556 , 557 , 558 , <nl> - 559 , 560 , 562 , 563 , 564 , 565 , 566 , 568 , 569 , 570 , 571 , 572 , 574 , 575 , 576 , 577 , 578 , <nl> - 579 , 581 , 582 , 583 , 584 , 585 , 587 , 588 , 589 , 590 , 591 , 593 , 594 , 595 , 596 , 598 , 599 , <nl> - 600 , 601 , 602 , 604 , 605 , 606 , 607 , 608 , 610 , 611 , 612 , 613 , 615 , 616 , 617 , 618 , 619 , <nl> - 621 , 622 , 623 , 624 , 626 , 627 , 628 , 629 , 631 , 632 , 633 , 634 , 636 , 637 , 638 , 639 , 641 , <nl> - 642 , 643 , 644 , 646 , 647 , 648 , 649 , 651 , 652 , 653 , 654 , 656 , 657 , 658 , 659 , 661 , 662 , <nl> - 663 , 664 , 666 , 667 , 668 , 670 , 671 , 672 , 673 , 675 , 676 , 677 , 678 , 680 , 681 , 682 , 684 , <nl> - 685 , 686 , 688 , 689 , 690 , 691 , 693 , 694 , 695 , 697 , 698 , 699 , 701 , 702 , 703 , 704 , 706 , <nl> - 707 , 708 , 710 , 711 , 712 , 714 , 715 , 716 , 718 , 719 , 720 , 722 , 723 , 724 , 726 , 727 , 728 , <nl> - 730 , 731 , 732 , 734 , 735 , 736 , 738 , 739 , 740 , 742 , 743 , 745 , 746 , 747 , 749 , 750 , 751 , <nl> - 753 , 754 , 755 , 757 , 758 , 760 , 761 , 762 , 764 , 765 , 767 , 768 , 769 , 771 , 772 , 773 , 775 , <nl> - 776 , 778 , 779 , 781 , 782 , 783 , 785 , 786 , 788 , 789 , 790 , 792 , 793 , 795 , 796 , 798 , 799 , <nl> - 800 , 802 , 803 , 805 , 806 , 808 , 809 , 811 , 812 , 813 , 815 , 816 , 818 , 819 , 821 , 822 , 824 , <nl> - 825 , 827 , 828 , 830 , 831 , 833 , 834 , 836 , 837 , 839 , 840 , 842 , 843 , 845 , 846 , 848 , 849 , <nl> - 851 , 852 , 854 , 855 , 857 , 858 , 860 , 861 , 863 , 864 , 866 , 867 , 869 , 871 , 872 , 874 , 875 , <nl> - 877 , 878 , 880 , 881 , 883 , 885 , 886 , 888 , 889 , 891 , 893 , 894 , 896 , 897 , 899 , 901 , 902 , <nl> - 904 , 905 , 907 , 909 , 910 , 912 , 914 , 915 , 917 , 919 , 920 , 922 , 923 , 925 , 927 , 928 , 930 , <nl> - 932 , 933 , 935 , 937 , 939 , 940 , 942 , 944 , 945 , 947 , 949 , 951 , 952 , 954 , 956 , 957 , 959 , <nl> - 961 , 963 , 964 , 966 , 968 , 970 , 971 , 973 , 975 , 977 , 979 , 980 , 982 , 984 , 986 , 988 , 989 , <nl> - 991 , 993 , 995 , 997 , 999 , 1000 , 1002 , 1004 , 1006 , 1008 , 1010 , 1012 , 1014 , 1015 , 1017 , <nl> - 1019 , 1021 , 1023 , 1025 , 1027 , 1029 , 1031 , 1033 , 1035 , 1037 , 1039 , 1041 , 1043 , 1045 , <nl> - 1047 , 1049 , 1051 , 1053 , 1055 , 1057 , 1059 , 1061 , 1063 , 1065 , 1067 , 1069 , 1071 , 1073 , <nl> - 1075 , 1077 , 1080 , 1082 , 1084 , 1086 , 1088 , 1090 , 1092 , 1095 , 1097 , 1099 , 1101 , 1103 , <nl> - 1106 , 1108 , 1110 , 1112 , 1115 , 1117 , 1119 , 1122 , 1124 , 1126 , 1129 , 1131 , 1133 , 1136 , <nl> - 1138 , 1140 , 1143 , 1145 , 1148 , 1150 , 1153 , 1155 , 1157 , 1160 , 1163 , 1165 , 1168 , 1170 , <nl> - 1173 , 1175 , 1178 , 1181 , 1183 , 1186 , 1189 , 1191 , 1194 , 1197 , 1199 , 1202 , 1205 , 1208 , <nl> - 1211 , 1213 , 1216 , 1219 , 1222 , 1225 , 1228 , 1231 , 1234 , 1237 , 1240 , 1243 , 1246 , 1250 , <nl> - 1253 , 1256 , 1259 , 1262 , 1266 , 1269 , 1273 , 1276 , 1279 , 1283 , 1287 , 1290 , 1294 , 1297 , <nl> - 1301 , 1305 , 1309 , 1313 , 1317 , 1321 , 1325 , 1329 , 1333 , 1337 , 1342 , 1346 , 1351 , 1355 , <nl> - 1360 , 1365 , 1370 , 1375 , 1380 , 1386 , 1391 , 1397 , 1403 , 1409 , 1415 , 1422 , 1429 , 1436 , <nl> - 1444 , 1452 , 1461 , 1470 , 1481 , 1493 , 1507 , 1526 <nl> - } ; <nl> - <nl> - <nl> - int32_t sign ( int32_t y ) <nl> - { <nl> - return ( 0 < y ) - ( y < 0 ) ; <nl> - } <nl> - <nl> - float atan2_approx ( float y , float x ) <nl> - { <nl> - int32_t x_int , y_int ; <nl> - x_int = ( int32_t ) ( 1000 * x ) ; <nl> - y_int = ( int32_t ) ( 1000 * y ) ; <nl> - float out = ( ( float ) turboatan2 ( y_int , x_int ) ) / 1000 . 0f ; <nl> - return out ; <nl> - } <nl> - <nl> - float asin_approx ( float x ) <nl> - { <nl> - int32_t x_int = ( int32_t ) ( 1000 * x ) ; <nl> - float out = ( ( float ) turboasin ( x_int ) ) / 1000 . 0f ; <nl> - return out ; <nl> - } <nl> - <nl> - <nl> - int32_t turboatan ( int32_t x ) <nl> - { <nl> - if ( x < 0 ) <nl> - { <nl> - return - 1 * turboatan ( - 1 * x ) ; <nl> - } <nl> - if ( x > 1000 ) <nl> - { <nl> - return 1571 - turboatan ( 1000000 / x ) ; <nl> - } <nl> - <nl> - return atan_lookup_table [ x ] ; <nl> - } <nl> - <nl> - <nl> - int32_t turboatan2 ( int32_t y , int32_t x ) <nl> - { <nl> - if ( y = = 0 ) <nl> - { <nl> - if ( x < 0 ) <nl> - { <nl> - return 3142 ; <nl> - } <nl> - else <nl> - { <nl> - return 0 ; <nl> - } <nl> - } <nl> - <nl> - else if ( x = = 0 ) <nl> - { <nl> - return 1572 * sign ( y ) ; <nl> - } <nl> - <nl> - else <nl> - { <nl> - int32_t arctan = turboatan ( ( 1000 * x ) / y ) ; <nl> - <nl> - if ( y > 0 ) <nl> - { <nl> - return 1571 - arctan ; <nl> - } <nl> - else if ( y < 0 ) <nl> - { <nl> - return - 1571 - arctan ; <nl> - } <nl> - else if ( x < 0 ) <nl> - { <nl> - return arctan + 3142 ; <nl> - } <nl> - else <nl> - { <nl> - return arctan ; <nl> - } <nl> - } <nl> - } <nl> - <nl> - <nl> - int32_t turboatan_taylor ( int32_t x ) <nl> - { <nl> - if ( x > 1000 ) <nl> - { <nl> - return 1571 - turboatan ( 1000000 / x ) ; <nl> - } <nl> - <nl> - return ( 972 * x / 1000 ) - ( ( ( 191 * x * x ) / 1000 ) * x ) / ( 1000 * 1000 ) ; / / the weird order of operations is to prevent overflow <nl> - } <nl> - <nl> - <nl> - int32_t turbocos ( int32_t x ) <nl> - { <nl> - return turbosin ( x + 1571 ) ; <nl> - } <nl> - <nl> - <nl> - int32_t turbosin ( int32_t x ) <nl> - { <nl> - / / wrap to + / - PI <nl> - if ( x < - 3142 ) <nl> - x + = 6283 ; <nl> - else if ( x > 3142 ) <nl> - x - = 6283 ; <nl> - <nl> - if ( x < 0 ) <nl> - { <nl> - return ( 1273 * x ) / 1000 + ( 405 * x * x ) / ( 1000000 ) ; <nl> - } <nl> - else <nl> - { <nl> - return ( 1273 * x ) / 1000 - ( 405 * x * x ) / ( 1000000 ) ; <nl> - } <nl> - <nl> - / / return x ; <nl> - } <nl> - <nl> - <nl> - int32_t turboasin ( int32_t x ) <nl> - { <nl> - if ( x < 0 ) <nl> - { <nl> - return - 1 * turboasin ( - 1 * x ) ; <nl> - } <nl> - else if ( x > 999 ) <nl> - { <nl> - return 1ul ; <nl> - } <nl> - return asin_lookup_table [ x ] ; <nl> - } <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + <nl> + / / float - based wrappers <nl> + float atan2_approx ( float y , float x ) ; <nl> + float asin_approx ( float x ) ; <nl> + <nl> + / / turbo - speed trig approximation <nl> + int32_t turboatan2 ( int32_t y , int32_t x ) ; <nl> + int32_t turboatan ( int32_t x ) ; <nl> + int32_t turboasin ( int32_t x ) ; <nl> + int32_t turbocos ( int32_t x ) ; <nl> + int32_t turbosin ( int32_t x ) ; <nl> + int32_t sign ( int32_t y ) ; <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + int16_t atan_lookup_table [ 1001 ] = <nl> + { <nl> + 0 , 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , <nl> + 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , 59 , 60 , 61 , 62 , 63 , 64 , 65 , 66 , 67 , 68 , <nl> + 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100 , <nl> + 101 , 102 , 103 , 104 , 105 , 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , 123 , 124 , 125 , <nl> + 126 , 127 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , <nl> + 150 , 151 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , <nl> + 175 , 176 , 177 , 178 , 179 , 180 , 180 , 181 , 182 , 183 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 192 , 193 , 194 , 195 , 196 , 197 , 198 , <nl> + 199 , 200 , 201 , 202 , 203 , 204 , 205 , 206 , 206 , 207 , 208 , 209 , 210 , 211 , 212 , 213 , 214 , 215 , 216 , 217 , 218 , 219 , 220 , 221 , 222 , <nl> + 223 , 224 , 225 , 226 , 227 , 227 , 228 , 229 , 230 , 231 , 232 , 233 , 234 , 235 , 236 , 237 , 238 , 239 , 240 , 241 , 242 , 243 , 244 , 244 , 245 , <nl> + 246 , 247 , 248 , 249 , 250 , 251 , 252 , 253 , 254 , 255 , 256 , 257 , 258 , 259 , 259 , 260 , 261 , 262 , 263 , 264 , 265 , 266 , 267 , 268 , 269 , <nl> + 270 , 271 , 272 , 273 , 273 , 274 , 275 , 276 , 277 , 278 , 279 , 280 , 281 , 282 , 283 , 284 , 285 , 285 , 286 , 287 , 288 , 289 , 290 , 291 , 292 , <nl> + 293 , 294 , 295 , 296 , 296 , 297 , 298 , 299 , 300 , 301 , 302 , 303 , 304 , 305 , 306 , 306 , 307 , 308 , 309 , 310 , 311 , 312 , 313 , 314 , 315 , <nl> + 316 , 316 , 317 , 318 , 319 , 320 , 321 , 322 , 323 , 324 , 325 , 325 , 326 , 327 , 328 , 329 , 330 , 331 , 332 , 333 , 333 , 334 , 335 , 336 , 337 , <nl> + 338 , 339 , 340 , 341 , 342 , 342 , 343 , 344 , 345 , 346 , 347 , 348 , 349 , 349 , 350 , 351 , 352 , 353 , 354 , 355 , 356 , 357 , 357 , 358 , 359 , <nl> + 360 , 361 , 362 , 363 , 364 , 364 , 365 , 366 , 367 , 368 , 369 , 370 , 370 , 371 , 372 , 373 , 374 , 375 , 376 , 377 , 377 , 378 , 379 , 380 , 381 , <nl> + 382 , 383 , 383 , 384 , 385 , 386 , 387 , 388 , 389 , 389 , 390 , 391 , 392 , 393 , 394 , 395 , 395 , 396 , 397 , 398 , 399 , 400 , 401 , 401 , 402 , <nl> + 403 , 404 , 405 , 406 , 406 , 407 , 408 , 409 , 410 , 411 , 411 , 412 , 413 , 414 , 415 , 416 , 417 , 417 , 418 , 419 , 420 , 421 , 422 , 422 , 423 , <nl> + 424 , 425 , 426 , 427 , 427 , 428 , 429 , 430 , 431 , 431 , 432 , 433 , 434 , 435 , 436 , 436 , 437 , 438 , 439 , 440 , 440 , 441 , 442 , 443 , 444 , <nl> + 445 , 445 , 446 , 447 , 448 , 449 , 449 , 450 , 451 , 452 , 453 , 454 , 454 , 455 , 456 , 457 , 458 , 458 , 459 , 460 , 461 , 462 , 462 , 463 , 464 , <nl> + 465 , 466 , 466 , 467 , 468 , 469 , 470 , 470 , 471 , 472 , 473 , 473 , 474 , 475 , 476 , 477 , 477 , 478 , 479 , 480 , 481 , 481 , 482 , 483 , 484 , <nl> + 485 , 485 , 486 , 487 , 488 , 488 , 489 , 490 , 491 , 492 , 492 , 493 , 494 , 495 , 495 , 496 , 497 , 498 , 498 , 499 , 500 , 501 , 502 , 502 , 503 , <nl> + 504 , 505 , 505 , 506 , 507 , 508 , 508 , 509 , 510 , 511 , 512 , 512 , 513 , 514 , 515 , 515 , 516 , 517 , 518 , 518 , 519 , 520 , 521 , 521 , 522 , <nl> + 523 , 524 , 524 , 525 , 526 , 527 , 527 , 528 , 529 , 530 , 530 , 531 , 532 , 533 , 533 , 534 , 535 , 535 , 536 , 537 , 538 , 538 , 539 , 540 , 541 , <nl> + 541 , 542 , 543 , 544 , 544 , 545 , 546 , 547 , 547 , 548 , 549 , 549 , 550 , 551 , 552 , 552 , 553 , 554 , 554 , 555 , 556 , 557 , 557 , 558 , 559 , <nl> + 560 , 560 , 561 , 562 , 562 , 563 , 564 , 565 , 565 , 566 , 567 , 567 , 568 , 569 , 570 , 570 , 571 , 572 , 572 , 573 , 574 , 574 , 575 , 576 , 577 , <nl> + 577 , 578 , 579 , 579 , 580 , 581 , 581 , 582 , 583 , 584 , 584 , 585 , 586 , 586 , 587 , 588 , 588 , 589 , 590 , 590 , 591 , 592 , 593 , 593 , 594 , <nl> + 595 , 595 , 596 , 597 , 597 , 598 , 599 , 599 , 600 , 601 , 601 , 602 , 603 , 603 , 604 , 605 , 606 , 606 , 607 , 608 , 608 , 609 , 610 , 610 , 611 , <nl> + 612 , 612 , 613 , 614 , 614 , 615 , 616 , 616 , 617 , 618 , 618 , 619 , 620 , 620 , 621 , 622 , 622 , 623 , 624 , 624 , 625 , 625 , 626 , 627 , 627 , <nl> + 628 , 629 , 629 , 630 , 631 , 631 , 632 , 633 , 633 , 634 , 635 , 635 , 636 , 637 , 637 , 638 , 639 , 639 , 640 , 640 , 641 , 642 , 642 , 643 , 644 , <nl> + 644 , 645 , 646 , 646 , 647 , 647 , 648 , 649 , 649 , 650 , 651 , 651 , 652 , 653 , 653 , 654 , 654 , 655 , 656 , 656 , 657 , 658 , 658 , 659 , 659 , <nl> + 660 , 661 , 661 , 662 , 663 , 663 , 664 , 664 , 665 , 666 , 666 , 667 , 667 , 668 , 669 , 669 , 670 , 671 , 671 , 672 , 672 , 673 , 674 , 674 , 675 , <nl> + 675 , 676 , 677 , 677 , 678 , 678 , 679 , 680 , 680 , 681 , 682 , 682 , 683 , 683 , 684 , 685 , 685 , 686 , 686 , 687 , 688 , 688 , 689 , 689 , 690 , <nl> + 690 , 691 , 692 , 692 , 693 , 693 , 694 , 695 , 695 , 696 , 696 , 697 , 698 , 698 , 699 , 699 , 700 , 701 , 701 , 702 , 702 , 703 , 703 , 704 , 705 , <nl> + 705 , 706 , 706 , 707 , 707 , 708 , 709 , 709 , 710 , 710 , 711 , 711 , 712 , 713 , 713 , 714 , 714 , 715 , 715 , 716 , 717 , 717 , 718 , 718 , 719 , <nl> + 719 , 720 , 721 , 721 , 722 , 722 , 723 , 723 , 724 , 725 , 725 , 726 , 726 , 727 , 727 , 728 , 728 , 729 , 730 , 730 , 731 , 731 , 732 , 732 , 733 , <nl> + 733 , 734 , 735 , 735 , 736 , 736 , 737 , 737 , 738 , 738 , 739 , 739 , 740 , 741 , 741 , 742 , 742 , 743 , 743 , 744 , 744 , 745 , 745 , 746 , 746 , <nl> + 747 , 748 , 748 , 749 , 749 , 750 , 750 , 751 , 751 , 752 , 752 , 753 , 753 , 754 , 755 , 755 , 756 , 756 , 757 , 757 , 758 , 758 , 759 , 759 , 760 , <nl> + 760 , 761 , 761 , 762 , 762 , 763 , 763 , 764 , 764 , 765 , 766 , 766 , 767 , 767 , 768 , 768 , 769 , 769 , 770 , 770 , 771 , 771 , 772 , 772 , 773 , <nl> + 773 , 774 , 774 , 775 , 775 , 776 , 776 , 777 , 777 , 778 , 778 , 779 , 779 , 780 , 780 , 781 , 781 , 782 , 782 , 783 , 783 , 784 , 784 , 785 <nl> + } ; <nl> + <nl> + int16_t asin_lookup_table [ 1000 ] = <nl> + { <nl> + 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , <nl> + 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , <nl> + 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , 59 , 60 , 61 , 62 , 63 , 64 , <nl> + 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , <nl> + 86 , 87 , 88 , 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100 , 101 , 102 , 103 , 104 , 105 , <nl> + 106 , 107 , 108 , 109 , 110 , 111 , 112 , 113 , 114 , 115 , 116 , 117 , 118 , 119 , 120 , 121 , 122 , <nl> + 123 , 124 , 125 , 126 , 127 , 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , <nl> + 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , 151 , 152 , 153 , 154 , 155 , 156 , <nl> + 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , <nl> + 174 , 175 , 176 , 177 , 178 , 179 , 180 , 182 , 183 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , <nl> + 192 , 193 , 194 , 195 , 196 , 197 , 198 , 199 , 200 , 201 , 202 , 203 , 204 , 205 , 206 , 207 , 208 , <nl> + 209 , 210 , 211 , 212 , 213 , 214 , 215 , 216 , 217 , 218 , 219 , 220 , 221 , 222 , 223 , 224 , 225 , <nl> + 226 , 227 , 228 , 230 , 231 , 232 , 233 , 234 , 235 , 236 , 237 , 238 , 239 , 240 , 241 , 242 , 243 , <nl> + 244 , 245 , 246 , 247 , 248 , 249 , 250 , 251 , 252 , 253 , 254 , 255 , 256 , 257 , 258 , 259 , 260 , <nl> + 261 , 263 , 264 , 265 , 266 , 267 , 268 , 269 , 270 , 271 , 272 , 273 , 274 , 275 , 276 , 277 , 278 , <nl> + 279 , 280 , 281 , 282 , 283 , 284 , 285 , 286 , 287 , 289 , 290 , 291 , 292 , 293 , 294 , 295 , 296 , <nl> + 297 , 298 , 299 , 300 , 301 , 302 , 303 , 304 , 305 , 306 , 307 , 308 , 309 , 310 , 312 , 313 , 314 , <nl> + 315 , 316 , 317 , 318 , 319 , 320 , 321 , 322 , 323 , 324 , 325 , 326 , 327 , 328 , 329 , 331 , 332 , <nl> + 333 , 334 , 335 , 336 , 337 , 338 , 339 , 340 , 341 , 342 , 343 , 344 , 345 , 346 , 347 , 349 , 350 , <nl> + 351 , 352 , 353 , 354 , 355 , 356 , 357 , 358 , 359 , 360 , 361 , 362 , 363 , 365 , 366 , 367 , 368 , <nl> + 369 , 370 , 371 , 372 , 373 , 374 , 375 , 376 , 377 , 379 , 380 , 381 , 382 , 383 , 384 , 385 , 386 , <nl> + 387 , 388 , 389 , 390 , 391 , 393 , 394 , 395 , 396 , 397 , 398 , 399 , 400 , 401 , 402 , 403 , 404 , <nl> + 406 , 407 , 408 , 409 , 410 , 411 , 412 , 413 , 414 , 415 , 416 , 418 , 419 , 420 , 421 , 422 , 423 , <nl> + 424 , 425 , 426 , 427 , 429 , 430 , 431 , 432 , 433 , 434 , 435 , 436 , 437 , 438 , 440 , 441 , 442 , <nl> + 443 , 444 , 445 , 446 , 447 , 448 , 450 , 451 , 452 , 453 , 454 , 455 , 456 , 457 , 458 , 460 , 461 , <nl> + 462 , 463 , 464 , 465 , 466 , 467 , 469 , 470 , 471 , 472 , 473 , 474 , 475 , 476 , 477 , 479 , 480 , <nl> + 481 , 482 , 483 , 484 , 485 , 487 , 488 , 489 , 490 , 491 , 492 , 493 , 494 , 496 , 497 , 498 , 499 , <nl> + 500 , 501 , 502 , 504 , 505 , 506 , 507 , 508 , 509 , 510 , 512 , 513 , 514 , 515 , 516 , 517 , 518 , <nl> + 520 , 521 , 522 , 523 , 524 , 525 , 527 , 528 , 529 , 530 , 531 , 532 , 534 , 535 , 536 , 537 , 538 , <nl> + 539 , 541 , 542 , 543 , 544 , 545 , 546 , 548 , 549 , 550 , 551 , 552 , 553 , 555 , 556 , 557 , 558 , <nl> + 559 , 560 , 562 , 563 , 564 , 565 , 566 , 568 , 569 , 570 , 571 , 572 , 574 , 575 , 576 , 577 , 578 , <nl> + 579 , 581 , 582 , 583 , 584 , 585 , 587 , 588 , 589 , 590 , 591 , 593 , 594 , 595 , 596 , 598 , 599 , <nl> + 600 , 601 , 602 , 604 , 605 , 606 , 607 , 608 , 610 , 611 , 612 , 613 , 615 , 616 , 617 , 618 , 619 , <nl> + 621 , 622 , 623 , 624 , 626 , 627 , 628 , 629 , 631 , 632 , 633 , 634 , 636 , 637 , 638 , 639 , 641 , <nl> + 642 , 643 , 644 , 646 , 647 , 648 , 649 , 651 , 652 , 653 , 654 , 656 , 657 , 658 , 659 , 661 , 662 , <nl> + 663 , 664 , 666 , 667 , 668 , 670 , 671 , 672 , 673 , 675 , 676 , 677 , 678 , 680 , 681 , 682 , 684 , <nl> + 685 , 686 , 688 , 689 , 690 , 691 , 693 , 694 , 695 , 697 , 698 , 699 , 701 , 702 , 703 , 704 , 706 , <nl> + 707 , 708 , 710 , 711 , 712 , 714 , 715 , 716 , 718 , 719 , 720 , 722 , 723 , 724 , 726 , 727 , 728 , <nl> + 730 , 731 , 732 , 734 , 735 , 736 , 738 , 739 , 740 , 742 , 743 , 745 , 746 , 747 , 749 , 750 , 751 , <nl> + 753 , 754 , 755 , 757 , 758 , 760 , 761 , 762 , 764 , 765 , 767 , 768 , 769 , 771 , 772 , 773 , 775 , <nl> + 776 , 778 , 779 , 781 , 782 , 783 , 785 , 786 , 788 , 789 , 790 , 792 , 793 , 795 , 796 , 798 , 799 , <nl> + 800 , 802 , 803 , 805 , 806 , 808 , 809 , 811 , 812 , 813 , 815 , 816 , 818 , 819 , 821 , 822 , 824 , <nl> + 825 , 827 , 828 , 830 , 831 , 833 , 834 , 836 , 837 , 839 , 840 , 842 , 843 , 845 , 846 , 848 , 849 , <nl> + 851 , 852 , 854 , 855 , 857 , 858 , 860 , 861 , 863 , 864 , 866 , 867 , 869 , 871 , 872 , 874 , 875 , <nl> + 877 , 878 , 880 , 881 , 883 , 885 , 886 , 888 , 889 , 891 , 893 , 894 , 896 , 897 , 899 , 901 , 902 , <nl> + 904 , 905 , 907 , 909 , 910 , 912 , 914 , 915 , 917 , 919 , 920 , 922 , 923 , 925 , 927 , 928 , 930 , <nl> + 932 , 933 , 935 , 937 , 939 , 940 , 942 , 944 , 945 , 947 , 949 , 951 , 952 , 954 , 956 , 957 , 959 , <nl> + 961 , 963 , 964 , 966 , 968 , 970 , 971 , 973 , 975 , 977 , 979 , 980 , 982 , 984 , 986 , 988 , 989 , <nl> + 991 , 993 , 995 , 997 , 999 , 1000 , 1002 , 1004 , 1006 , 1008 , 1010 , 1012 , 1014 , 1015 , 1017 , <nl> + 1019 , 1021 , 1023 , 1025 , 1027 , 1029 , 1031 , 1033 , 1035 , 1037 , 1039 , 1041 , 1043 , 1045 , <nl> + 1047 , 1049 , 1051 , 1053 , 1055 , 1057 , 1059 , 1061 , 1063 , 1065 , 1067 , 1069 , 1071 , 1073 , <nl> + 1075 , 1077 , 1080 , 1082 , 1084 , 1086 , 1088 , 1090 , 1092 , 1095 , 1097 , 1099 , 1101 , 1103 , <nl> + 1106 , 1108 , 1110 , 1112 , 1115 , 1117 , 1119 , 1122 , 1124 , 1126 , 1129 , 1131 , 1133 , 1136 , <nl> + 1138 , 1140 , 1143 , 1145 , 1148 , 1150 , 1153 , 1155 , 1157 , 1160 , 1163 , 1165 , 1168 , 1170 , <nl> + 1173 , 1175 , 1178 , 1181 , 1183 , 1186 , 1189 , 1191 , 1194 , 1197 , 1199 , 1202 , 1205 , 1208 , <nl> + 1211 , 1213 , 1216 , 1219 , 1222 , 1225 , 1228 , 1231 , 1234 , 1237 , 1240 , 1243 , 1246 , 1250 , <nl> + 1253 , 1256 , 1259 , 1262 , 1266 , 1269 , 1273 , 1276 , 1279 , 1283 , 1287 , 1290 , 1294 , 1297 , <nl> + 1301 , 1305 , 1309 , 1313 , 1317 , 1321 , 1325 , 1329 , 1333 , 1337 , 1342 , 1346 , 1351 , 1355 , <nl> + 1360 , 1365 , 1370 , 1375 , 1380 , 1386 , 1391 , 1397 , 1403 , 1409 , 1415 , 1422 , 1429 , 1436 , <nl> + 1444 , 1452 , 1461 , 1470 , 1481 , 1493 , 1507 , 1526 <nl> + } ; <nl> + <nl> + <nl> + int32_t sign ( int32_t y ) <nl> + { <nl> + return ( 0 < y ) - ( y < 0 ) ; <nl> + } <nl> + <nl> + float atan2_approx ( float y , float x ) <nl> + { <nl> + int32_t x_int , y_int ; <nl> + x_int = ( int32_t ) ( 1000 * x ) ; <nl> + y_int = ( int32_t ) ( 1000 * y ) ; <nl> + float out = ( ( float ) turboatan2 ( y_int , x_int ) ) / 1000 . 0f ; <nl> + return out ; <nl> + } <nl> + <nl> + float asin_approx ( float x ) <nl> + { <nl> + int32_t x_int = ( int32_t ) ( 1000 * x ) ; <nl> + float out = ( ( float ) turboasin ( x_int ) ) / 1000 . 0f ; <nl> + return out ; <nl> + } <nl> + <nl> + <nl> + int32_t turboatan ( int32_t x ) <nl> + { <nl> + if ( x < 0 ) <nl> + { <nl> + return - 1 * turboatan ( - 1 * x ) ; <nl> + } <nl> + if ( x > 1000 ) <nl> + { <nl> + return 1571 - turboatan ( 1000000 / x ) ; <nl> + } <nl> + <nl> + return atan_lookup_table [ x ] ; <nl> + } <nl> + <nl> + <nl> + int32_t turboatan2 ( int32_t y , int32_t x ) <nl> + { <nl> + if ( y = = 0 ) <nl> + { <nl> + if ( x < 0 ) <nl> + { <nl> + return 3142 ; <nl> + } <nl> + else <nl> + { <nl> + return 0 ; <nl> + } <nl> + } <nl> + <nl> + else if ( x = = 0 ) <nl> + { <nl> + return 1572 * sign ( y ) ; <nl> + } <nl> + <nl> + else <nl> + { <nl> + int32_t arctan = turboatan ( ( 1000 * x ) / y ) ; <nl> + <nl> + if ( y > 0 ) <nl> + { <nl> + return 1571 - arctan ; <nl> + } <nl> + else if ( y < 0 ) <nl> + { <nl> + return - 1571 - arctan ; <nl> + } <nl> + else if ( x < 0 ) <nl> + { <nl> + return arctan + 3142 ; <nl> + } <nl> + else <nl> + { <nl> + return arctan ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + <nl> + int32_t turboatan_taylor ( int32_t x ) <nl> + { <nl> + if ( x > 1000 ) <nl> + { <nl> + return 1571 - turboatan ( 1000000 / x ) ; <nl> + } <nl> + <nl> + return ( 972 * x / 1000 ) - ( ( ( 191 * x * x ) / 1000 ) * x ) / ( 1000 * 1000 ) ; / / the weird order of operations is to prevent overflow <nl> + } <nl> + <nl> + <nl> + int32_t turbocos ( int32_t x ) <nl> + { <nl> + return turbosin ( x + 1571 ) ; <nl> + } <nl> + <nl> + <nl> + int32_t turbosin ( int32_t x ) <nl> + { <nl> + / / wrap to + / - PI <nl> + if ( x < - 3142 ) <nl> + x + = 6283 ; <nl> + else if ( x > 3142 ) <nl> + x - = 6283 ; <nl> + <nl> + if ( x < 0 ) <nl> + { <nl> + return ( 1273 * x ) / 1000 + ( 405 * x * x ) / ( 1000000 ) ; <nl> + } <nl> + else <nl> + { <nl> + return ( 1273 * x ) / 1000 - ( 405 * x * x ) / ( 1000000 ) ; <nl> + } <nl> + <nl> + / / return x ; <nl> + } <nl> + <nl> + <nl> + int32_t turboasin ( int32_t x ) <nl> + { <nl> + if ( x < 0 ) <nl> + { <nl> + return - 1 * turboasin ( - 1 * x ) ; <nl> + } <nl> + else if ( x > 999 ) <nl> + { <nl> + return 1ul ; <nl> + } <nl> + return asin_lookup_table [ x ] ; <nl> + } <nl> similarity index 95 % <nl> rename from AirLib / include / controllers / rosflight / firmware / turbotrig / turbovec . h <nl> rename to AirLib / include / controllers / ros_flight / firmware / turbotrig / turbovec . h <nl> mmm a / AirLib / include / controllers / rosflight / firmware / turbotrig / turbovec . h <nl> ppp b / AirLib / include / controllers / ros_flight / firmware / turbotrig / turbovec . h <nl> <nl> - # pragma once <nl> - <nl> - # include < cstdlib > <nl> - # include < cstdint > <nl> - # include < cmath > <nl> - <nl> - # ifdef __GNUC__ <nl> - _Pragma ( " GCC diagnostic push " ) <nl> - _Pragma ( " GCC diagnostic ignored \ " - Wstrict - aliasing \ " " ) <nl> - # endif <nl> - <nl> - # if defined ( _MSC_VER ) <nl> - __pragma ( warning ( push ) ) <nl> - __pragma ( warning ( disable : 4100 4028 4189 4204 4244 4245 4239 4464 4456 4505 4514 4571 4624 4626 4267 4710 4820 5027 5031 ) ) <nl> - # endif <nl> - <nl> - typedef struct <nl> - { <nl> - float x ; <nl> - float y ; <nl> - float z ; <nl> - } vector_t ; <nl> - <nl> - typedef struct <nl> - { <nl> - float w ; <nl> - float x ; <nl> - float y ; <nl> - float z ; <nl> - } quaternion_t ; <nl> - <nl> - typedef struct <nl> - { <nl> - int32_t x ; <nl> - int32_t y ; <nl> - int32_t z ; <nl> - } intvec_t ; <nl> - <nl> - typedef struct <nl> - { <nl> - int32_t w ; <nl> - int32_t x ; <nl> - int32_t y ; <nl> - int32_t z ; <nl> - } intquat_t ; <nl> - <nl> - int32_t int_dot ( intvec_t v1 , intvec_t v2 ) ; <nl> - intvec_t int_cross ( intvec_t u , intvec_t v ) ; <nl> - intvec_t int_scalar_multiply ( int32_t s , intvec_t v ) ; <nl> - intvec_t int_vector_add ( intvec_t u , intvec_t v ) ; <nl> - intvec_t int_vector_sub ( intvec_t u , intvec_t v ) ; <nl> - int32_t int_sqrd_norm ( intvec_t v ) ; <nl> - intvec_t int_vector_normalize ( intvec_t v ) ; <nl> - intquat_t int_quaternion_normalize ( intquat_t q ) ; <nl> - intquat_t int_quaternion_multiply ( const intquat_t q1 , const intquat_t q2 ) ; <nl> - intquat_t int_quaternion_inverse ( intquat_t q ) ; <nl> - intquat_t int_quaternion_from_two_vectors ( intvec_t u , intvec_t v ) ; <nl> - <nl> - float dot ( vector_t v1 , vector_t v2 ) ; <nl> - vector_t cross ( vector_t u , vector_t v ) ; <nl> - vector_t scalar_multiply ( float s , vector_t v ) ; <nl> - vector_t vector_add ( vector_t u , vector_t v ) ; <nl> - vector_t vector_sub ( vector_t u , vector_t v ) ; <nl> - float sqrd_norm ( vector_t v ) ; <nl> - vector_t vector_normalize ( vector_t v ) ; <nl> - quaternion_t quaternion_normalize ( quaternion_t q ) ; <nl> - quaternion_t quaternion_multiply ( quaternion_t q1 , quaternion_t q2 ) ; <nl> - quaternion_t quaternion_inverse ( quaternion_t q ) ; <nl> - quaternion_t quat_from_two_vectors ( vector_t u , vector_t v ) ; <nl> - <nl> - void euler_from_quat ( quaternion_t q , float * phi , float * theta , float * psi ) ; <nl> - void euler_from_int_quat ( intquat_t q , int32_t phi , int32_t theta , int32_t psi ) ; <nl> - <nl> - float turboInvSqrt ( float x ) ; <nl> - <nl> - float fsat ( float value , float max ) ; <nl> - int32_t sat ( int32_t value , int32_t max ) ; <nl> - float fsign ( float y ) ; <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - <nl> - <nl> - / / void pfquat ( ) __attribute__ ( ( unused ) ) ; <nl> - void pfquat ( ) { } <nl> - <nl> - int32_t int_dot ( intvec_t v1 , intvec_t v2 ) <nl> - { <nl> - return ( v1 . x * v2 . x + v1 . y * v2 . y + v1 . z * v2 . z ) / 1000 ; <nl> - } <nl> - <nl> - intvec_t int_cross ( intvec_t u , intvec_t v ) <nl> - { <nl> - intvec_t out ; <nl> - out . x = ( u . y * v . z - u . z * v . y ) / 1000 ; <nl> - out . y = ( u . z * v . x - u . x * v . z ) / 1000 ; <nl> - out . z = ( u . x * v . y - u . y * v . x ) / 1000 ; <nl> - return out ; <nl> - } <nl> - <nl> - intvec_t int_scalar_multiply ( int32_t s , intvec_t v ) <nl> - { <nl> - intvec_t out ; <nl> - out . x = ( s * v . x ) / 1000 ; <nl> - out . y = ( s * v . y ) / 1000 ; <nl> - out . z = ( s * v . z ) / 1000 ; <nl> - return out ; <nl> - } <nl> - <nl> - intvec_t int_vector_add ( intvec_t u , intvec_t v ) <nl> - { <nl> - intvec_t out ; <nl> - out . x = u . x + v . x ; <nl> - out . y = u . y + v . y ; <nl> - out . z = u . z + v . z ; <nl> - return out ; <nl> - } <nl> - <nl> - intvec_t int_vector_sub ( intvec_t u , intvec_t v ) <nl> - { <nl> - intvec_t out ; <nl> - out . x = u . x - v . x ; <nl> - out . y = u . y - v . y ; <nl> - out . z = u . z - v . z ; <nl> - return out ; <nl> - } <nl> - <nl> - int32_t int_sqrd_norm ( intvec_t v ) <nl> - { <nl> - return v . x * v . x + v . y * v . y + v . z * v . z ; <nl> - } <nl> - <nl> - intvec_t int_vector_normalize ( intvec_t v ) <nl> - { <nl> - float recipNorm = turboInvSqrt ( ( v . x * v . x + v . y * v . y + v . z * v . z ) / 1000000 . 0f ) ; <nl> - return int_scalar_multiply ( ( int32_t ) ( 1000 * recipNorm ) , v ) ; <nl> - } <nl> - <nl> - intquat_t int_quaternion_normalize ( intquat_t q ) <nl> - { <nl> - float recipNorm = turboInvSqrt ( ( q . w * q . w + q . x * q . x + q . y * q . y + q . z * q . z ) / 1000000 . 0f ) ; <nl> - int32_t intRecipNorm = ( int32_t ) ( recipNorm * 1000 ) ; <nl> - intquat_t out ; <nl> - out . w = ( intRecipNorm * q . w ) / 1000 ; <nl> - out . x = ( intRecipNorm * q . x ) / 1000 ; <nl> - out . y = ( intRecipNorm * q . y ) / 1000 ; <nl> - out . z = ( intRecipNorm * q . z ) / 1000 ; <nl> - return out ; <nl> - } <nl> - <nl> - intquat_t int_quaternion_multiply ( intquat_t q1 , intquat_t q2 ) <nl> - { <nl> - int32_t s1 = q1 . w ; <nl> - int32_t s2 = q2 . w ; <nl> - <nl> - intvec_t v1 = { q1 . x , q1 . y , q2 . z } ; <nl> - intvec_t v2 = { q2 . x , q2 . y , q2 . z } ; <nl> - <nl> - int32_t w = ( s1 * s2 ) / 1000 - int_dot ( v1 , v2 ) ; <nl> - / / xyz = s1 * v2 + s2 * v1 - v1 x v2 ) <nl> - intvec_t xyz = int_vector_sub ( int_vector_add ( int_scalar_multiply ( s1 , v2 ) , int_scalar_multiply ( s2 , v1 ) ) , int_cross ( v1 , <nl> - v2 ) ) ; <nl> - intquat_t q = { w , xyz . x , xyz . y , xyz . z } ; <nl> - return int_quaternion_normalize ( q ) ; <nl> - } <nl> - <nl> - <nl> - intquat_t int_quaternion_inverse ( intquat_t q ) <nl> - { <nl> - <nl> - intquat_t out = { q . w , - 1 * q . x , - 1 * q . y , - 1 * q . z } ; <nl> - return out ; <nl> - } <nl> - <nl> - intquat_t int_quaternion_from_two_vectors ( intvec_t u , intvec_t v ) <nl> - { <nl> - u = int_vector_normalize ( u ) ; <nl> - v = int_vector_normalize ( v ) ; <nl> - <nl> - intvec_t half = int_vector_normalize ( int_vector_add ( u , v ) ) ; <nl> - <nl> - int32_t w = int_dot ( u , half ) ; <nl> - intvec_t xyz = int_cross ( u , v ) ; <nl> - intquat_t q = { w , xyz . x , xyz . y , xyz . z } ; <nl> - return int_quaternion_normalize ( q ) ; <nl> - } <nl> - <nl> - <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - / * * * FLOATING POINT IMPLEMENTATIONS * * * / <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> - float dot ( vector_t v1 , vector_t v2 ) <nl> - { <nl> - return v1 . x * v2 . x + v1 . y * v2 . y + v1 . z * v2 . z ; <nl> - } <nl> - <nl> - vector_t cross ( vector_t u , vector_t v ) <nl> - { <nl> - vector_t out = { u . y * v . z - u . z * v . y , <nl> - u . z * v . x - u . x * v . z , <nl> - u . x * v . y - u . y * v . x <nl> - } ; <nl> - return out ; <nl> - } <nl> - <nl> - vector_t scalar_multiply ( float s , vector_t v ) <nl> - { <nl> - vector_t out = { s * v . x , <nl> - s * v . y , <nl> - s * v . z <nl> - } ; <nl> - return out ; <nl> - } <nl> - <nl> - vector_t vector_add ( vector_t u , vector_t v ) <nl> - { <nl> - vector_t out = { u . x + v . x , <nl> - u . y + v . y , <nl> - u . z + v . z <nl> - } ; <nl> - return out ; <nl> - <nl> - } <nl> - <nl> - vector_t vector_sub ( vector_t u , vector_t v ) <nl> - { <nl> - vector_t out = { u . x - v . x , <nl> - u . y - v . y , <nl> - u . z - v . z <nl> - } ; <nl> - return out ; <nl> - } <nl> - <nl> - float sqrd_norm ( vector_t v ) <nl> - { <nl> - return v . x * v . x + v . y * v . y + v . z * v . z ; <nl> - } <nl> - <nl> - float norm ( vector_t v ) <nl> - { <nl> - float out = sqrtf ( v . x * v . x + v . y * v . y + v . z * v . z ) ; <nl> - return out ; <nl> - } <nl> - <nl> - vector_t vector_normalize ( vector_t v ) <nl> - { <nl> - float recipNorm = turboInvSqrt ( v . x * v . x + v . y * v . y + v . z * v . z ) ; <nl> - vector_t out = { recipNorm * v . x , <nl> - recipNorm * v . y , <nl> - recipNorm * v . z <nl> - } ; <nl> - return out ; <nl> - } <nl> - <nl> - quaternion_t quaternion_normalize ( quaternion_t q ) <nl> - { <nl> - float recipNorm = turboInvSqrt ( q . w * q . w + q . x * q . x + q . y * q . y + q . z * q . z ) ; <nl> - quaternion_t out = { recipNorm * q . w , <nl> - recipNorm * q . x , <nl> - recipNorm * q . y , <nl> - recipNorm * q . z <nl> - } ; <nl> - return out ; <nl> - } <nl> - <nl> - quaternion_t quaternion_multiply ( quaternion_t q1 , quaternion_t q2 ) <nl> - { <nl> - quaternion_t q = { q1 . w * q2 . w - q1 . x * q2 . x - q1 . y * q2 . y - q1 . z * q2 . z , <nl> - q1 . w * q2 . x + q1 . x * q2 . w - q1 . y * q2 . z + q1 . z * q2 . y , <nl> - q1 . w * q2 . y + q1 . x * q2 . z + q1 . y * q2 . w - q1 . z * q2 . x , <nl> - q1 . w * q2 . z - q1 . x * q2 . y + q1 . y * q2 . x + q1 . z * q2 . w <nl> - } ; <nl> - return q ; <nl> - } <nl> - <nl> - quaternion_t quaternion_inverse ( quaternion_t q ) <nl> - { <nl> - q . x * = - 1 . 0f ; <nl> - q . y * = - 1 . 0f ; <nl> - q . z * = - 1 . 0f ; <nl> - return q ; <nl> - } <nl> - <nl> - quaternion_t quat_from_two_vectors ( vector_t u , vector_t v ) <nl> - { <nl> - float w = 1 . 0f + dot ( u , v ) ; <nl> - vector_t xyz = cross ( u , v ) ; <nl> - quaternion_t q = { w , xyz . x , xyz . y , xyz . z } ; <nl> - return quaternion_normalize ( q ) ; <nl> - } <nl> - <nl> - void euler_from_quat ( quaternion_t q , float * phi , float * theta , float * psi ) <nl> - { <nl> - * phi = atan2_approx ( 2 . 0f * ( q . w * q . x + q . y * q . z ) , <nl> - 1 . 0f - 2 . 0f * ( q . x * q . x + q . y * q . y ) ) ; <nl> - * theta = asin_approx ( 2 . 0f * ( q . w * q . y - q . z * q . x ) ) ; <nl> - * psi = atan2_approx ( 2 . 0f * ( q . w * q . z + q . x * q . y ) , <nl> - 1 . 0f - 2 . 0f * ( q . y * q . y + q . z * q . z ) ) ; <nl> - } <nl> - <nl> - <nl> - float turboInvSqrt ( float x ) <nl> - { <nl> - long i ; <nl> - float x2 , y ; <nl> - const float threehalfs = 1 . 5F ; <nl> - <nl> - x2 = x * 0 . 5F ; <nl> - y = x ; <nl> - i = * ( long * ) & y ; / / evil floating point bit level hacking <nl> - i = 0x5f3759df - ( i > > 1 ) ; <nl> - y = * ( float * ) & i ; <nl> - y = y * ( threehalfs - ( x2 * y * y ) ) ; / / 1st iteration <nl> - y = y * ( threehalfs - ( x2 * y * y ) ) ; / / 2nd iteration , this can be removed <nl> - <nl> - return y ; <nl> - } <nl> - <nl> - float fsign ( float y ) <nl> - { <nl> - return ( float ) ( ( 0 < y ) - ( y < 0 ) ) ; <nl> - } <nl> - <nl> - <nl> - float fsat ( float value , float max ) <nl> - { <nl> - if ( fabs ( value ) > fabs ( max ) ) <nl> - { <nl> - value = max * fsign ( value ) ; <nl> - } <nl> - return value ; <nl> - } <nl> - <nl> - <nl> - int32_t sat ( int32_t value , int32_t max ) <nl> - { <nl> - if ( abs ( value ) > abs ( max ) ) <nl> - { <nl> - value = max * sign ( value ) ; <nl> - } <nl> - return value ; <nl> - } <nl> - <nl> - <nl> - # ifdef __GNUC__ <nl> - _Pragma ( " GCC diagnostic pop " ) <nl> - # endif <nl> - <nl> - # if defined ( _MSC_VER ) <nl> - __pragma ( warning ( pop ) ) <nl> - # endif <nl> + # pragma once <nl> + <nl> + # include < cstdlib > <nl> + # include < cstdint > <nl> + # include < cmath > <nl> + <nl> + # ifdef __GNUC__ <nl> + _Pragma ( " GCC diagnostic push " ) <nl> + _Pragma ( " GCC diagnostic ignored \ " - Wstrict - aliasing \ " " ) <nl> + # endif <nl> + <nl> + # if defined ( _MSC_VER ) <nl> + __pragma ( warning ( push ) ) <nl> + __pragma ( warning ( disable : 4100 4028 4189 4204 4244 4245 4239 4464 4456 4505 4514 4571 4624 4626 4267 4710 4820 5027 5031 ) ) <nl> + # endif <nl> + <nl> + typedef struct <nl> + { <nl> + float x ; <nl> + float y ; <nl> + float z ; <nl> + } vector_t ; <nl> + <nl> + typedef struct <nl> + { <nl> + float w ; <nl> + float x ; <nl> + float y ; <nl> + float z ; <nl> + } quaternion_t ; <nl> + <nl> + typedef struct <nl> + { <nl> + int32_t x ; <nl> + int32_t y ; <nl> + int32_t z ; <nl> + } intvec_t ; <nl> + <nl> + typedef struct <nl> + { <nl> + int32_t w ; <nl> + int32_t x ; <nl> + int32_t y ; <nl> + int32_t z ; <nl> + } intquat_t ; <nl> + <nl> + int32_t int_dot ( intvec_t v1 , intvec_t v2 ) ; <nl> + intvec_t int_cross ( intvec_t u , intvec_t v ) ; <nl> + intvec_t int_scalar_multiply ( int32_t s , intvec_t v ) ; <nl> + intvec_t int_vector_add ( intvec_t u , intvec_t v ) ; <nl> + intvec_t int_vector_sub ( intvec_t u , intvec_t v ) ; <nl> + int32_t int_sqrd_norm ( intvec_t v ) ; <nl> + intvec_t int_vector_normalize ( intvec_t v ) ; <nl> + intquat_t int_quaternion_normalize ( intquat_t q ) ; <nl> + intquat_t int_quaternion_multiply ( const intquat_t q1 , const intquat_t q2 ) ; <nl> + intquat_t int_quaternion_inverse ( intquat_t q ) ; <nl> + intquat_t int_quaternion_from_two_vectors ( intvec_t u , intvec_t v ) ; <nl> + <nl> + float dot ( vector_t v1 , vector_t v2 ) ; <nl> + vector_t cross ( vector_t u , vector_t v ) ; <nl> + vector_t scalar_multiply ( float s , vector_t v ) ; <nl> + vector_t vector_add ( vector_t u , vector_t v ) ; <nl> + vector_t vector_sub ( vector_t u , vector_t v ) ; <nl> + float sqrd_norm ( vector_t v ) ; <nl> + vector_t vector_normalize ( vector_t v ) ; <nl> + quaternion_t quaternion_normalize ( quaternion_t q ) ; <nl> + quaternion_t quaternion_multiply ( quaternion_t q1 , quaternion_t q2 ) ; <nl> + quaternion_t quaternion_inverse ( quaternion_t q ) ; <nl> + quaternion_t quat_from_two_vectors ( vector_t u , vector_t v ) ; <nl> + <nl> + void euler_from_quat ( quaternion_t q , float * phi , float * theta , float * psi ) ; <nl> + void euler_from_int_quat ( intquat_t q , int32_t phi , int32_t theta , int32_t psi ) ; <nl> + <nl> + float turboInvSqrt ( float x ) ; <nl> + <nl> + float fsat ( float value , float max ) ; <nl> + int32_t sat ( int32_t value , int32_t max ) ; <nl> + float fsign ( float y ) ; <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Implementation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + <nl> + <nl> + / / void pfquat ( ) __attribute__ ( ( unused ) ) ; <nl> + void pfquat ( ) { } <nl> + <nl> + int32_t int_dot ( intvec_t v1 , intvec_t v2 ) <nl> + { <nl> + return ( v1 . x * v2 . x + v1 . y * v2 . y + v1 . z * v2 . z ) / 1000 ; <nl> + } <nl> + <nl> + intvec_t int_cross ( intvec_t u , intvec_t v ) <nl> + { <nl> + intvec_t out ; <nl> + out . x = ( u . y * v . z - u . z * v . y ) / 1000 ; <nl> + out . y = ( u . z * v . x - u . x * v . z ) / 1000 ; <nl> + out . z = ( u . x * v . y - u . y * v . x ) / 1000 ; <nl> + return out ; <nl> + } <nl> + <nl> + intvec_t int_scalar_multiply ( int32_t s , intvec_t v ) <nl> + { <nl> + intvec_t out ; <nl> + out . x = ( s * v . x ) / 1000 ; <nl> + out . y = ( s * v . y ) / 1000 ; <nl> + out . z = ( s * v . z ) / 1000 ; <nl> + return out ; <nl> + } <nl> + <nl> + intvec_t int_vector_add ( intvec_t u , intvec_t v ) <nl> + { <nl> + intvec_t out ; <nl> + out . x = u . x + v . x ; <nl> + out . y = u . y + v . y ; <nl> + out . z = u . z + v . z ; <nl> + return out ; <nl> + } <nl> + <nl> + intvec_t int_vector_sub ( intvec_t u , intvec_t v ) <nl> + { <nl> + intvec_t out ; <nl> + out . x = u . x - v . x ; <nl> + out . y = u . y - v . y ; <nl> + out . z = u . z - v . z ; <nl> + return out ; <nl> + } <nl> + <nl> + int32_t int_sqrd_norm ( intvec_t v ) <nl> + { <nl> + return v . x * v . x + v . y * v . y + v . z * v . z ; <nl> + } <nl> + <nl> + intvec_t int_vector_normalize ( intvec_t v ) <nl> + { <nl> + float recipNorm = turboInvSqrt ( ( v . x * v . x + v . y * v . y + v . z * v . z ) / 1000000 . 0f ) ; <nl> + return int_scalar_multiply ( ( int32_t ) ( 1000 * recipNorm ) , v ) ; <nl> + } <nl> + <nl> + intquat_t int_quaternion_normalize ( intquat_t q ) <nl> + { <nl> + float recipNorm = turboInvSqrt ( ( q . w * q . w + q . x * q . x + q . y * q . y + q . z * q . z ) / 1000000 . 0f ) ; <nl> + int32_t intRecipNorm = ( int32_t ) ( recipNorm * 1000 ) ; <nl> + intquat_t out ; <nl> + out . w = ( intRecipNorm * q . w ) / 1000 ; <nl> + out . x = ( intRecipNorm * q . x ) / 1000 ; <nl> + out . y = ( intRecipNorm * q . y ) / 1000 ; <nl> + out . z = ( intRecipNorm * q . z ) / 1000 ; <nl> + return out ; <nl> + } <nl> + <nl> + intquat_t int_quaternion_multiply ( intquat_t q1 , intquat_t q2 ) <nl> + { <nl> + int32_t s1 = q1 . w ; <nl> + int32_t s2 = q2 . w ; <nl> + <nl> + intvec_t v1 = { q1 . x , q1 . y , q2 . z } ; <nl> + intvec_t v2 = { q2 . x , q2 . y , q2 . z } ; <nl> + <nl> + int32_t w = ( s1 * s2 ) / 1000 - int_dot ( v1 , v2 ) ; <nl> + / / xyz = s1 * v2 + s2 * v1 - v1 x v2 ) <nl> + intvec_t xyz = int_vector_sub ( int_vector_add ( int_scalar_multiply ( s1 , v2 ) , int_scalar_multiply ( s2 , v1 ) ) , int_cross ( v1 , <nl> + v2 ) ) ; <nl> + intquat_t q = { w , xyz . x , xyz . y , xyz . z } ; <nl> + return int_quaternion_normalize ( q ) ; <nl> + } <nl> + <nl> + <nl> + intquat_t int_quaternion_inverse ( intquat_t q ) <nl> + { <nl> + <nl> + intquat_t out = { q . w , - 1 * q . x , - 1 * q . y , - 1 * q . z } ; <nl> + return out ; <nl> + } <nl> + <nl> + intquat_t int_quaternion_from_two_vectors ( intvec_t u , intvec_t v ) <nl> + { <nl> + u = int_vector_normalize ( u ) ; <nl> + v = int_vector_normalize ( v ) ; <nl> + <nl> + intvec_t half = int_vector_normalize ( int_vector_add ( u , v ) ) ; <nl> + <nl> + int32_t w = int_dot ( u , half ) ; <nl> + intvec_t xyz = int_cross ( u , v ) ; <nl> + intquat_t q = { w , xyz . x , xyz . y , xyz . z } ; <nl> + return int_quaternion_normalize ( q ) ; <nl> + } <nl> + <nl> + <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + / * * * FLOATING POINT IMPLEMENTATIONS * * * / <nl> + / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> + float dot ( vector_t v1 , vector_t v2 ) <nl> + { <nl> + return v1 . x * v2 . x + v1 . y * v2 . y + v1 . z * v2 . z ; <nl> + } <nl> + <nl> + vector_t cross ( vector_t u , vector_t v ) <nl> + { <nl> + vector_t out = { u . y * v . z - u . z * v . y , <nl> + u . z * v . x - u . x * v . z , <nl> + u . x * v . y - u . y * v . x <nl> + } ; <nl> + return out ; <nl> + } <nl> + <nl> + vector_t scalar_multiply ( float s , vector_t v ) <nl> + { <nl> + vector_t out = { s * v . x , <nl> + s * v . y , <nl> + s * v . z <nl> + } ; <nl> + return out ; <nl> + } <nl> + <nl> + vector_t vector_add ( vector_t u , vector_t v ) <nl> + { <nl> + vector_t out = { u . x + v . x , <nl> + u . y + v . y , <nl> + u . z + v . z <nl> + } ; <nl> + return out ; <nl> + <nl> + } <nl> + <nl> + vector_t vector_sub ( vector_t u , vector_t v ) <nl> + { <nl> + vector_t out = { u . x - v . x , <nl> + u . y - v . y , <nl> + u . z - v . z <nl> + } ; <nl> + return out ; <nl> + } <nl> + <nl> + float sqrd_norm ( vector_t v ) <nl> + { <nl> + return v . x * v . x + v . y * v . y + v . z * v . z ; <nl> + } <nl> + <nl> + float norm ( vector_t v ) <nl> + { <nl> + float out = sqrtf ( v . x * v . x + v . y * v . y + v . z * v . z ) ; <nl> + return out ; <nl> + } <nl> + <nl> + vector_t vector_normalize ( vector_t v ) <nl> + { <nl> + float recipNorm = turboInvSqrt ( v . x * v . x + v . y * v . y + v . z * v . z ) ; <nl> + vector_t out = { recipNorm * v . x , <nl> + recipNorm * v . y , <nl> + recipNorm * v . z <nl> + } ; <nl> + return out ; <nl> + } <nl> + <nl> + quaternion_t quaternion_normalize ( quaternion_t q ) <nl> + { <nl> + float recipNorm = turboInvSqrt ( q . w * q . w + q . x * q . x + q . y * q . y + q . z * q . z ) ; <nl> + quaternion_t out = { recipNorm * q . w , <nl> + recipNorm * q . x , <nl> + recipNorm * q . y , <nl> + recipNorm * q . z <nl> + } ; <nl> + return out ; <nl> + } <nl> + <nl> + quaternion_t quaternion_multiply ( quaternion_t q1 , quaternion_t q2 ) <nl> + { <nl> + quaternion_t q = { q1 . w * q2 . w - q1 . x * q2 . x - q1 . y * q2 . y - q1 . z * q2 . z , <nl> + q1 . w * q2 . x + q1 . x * q2 . w - q1 . y * q2 . z + q1 . z * q2 . y , <nl> + q1 . w * q2 . y + q1 . x * q2 . z + q1 . y * q2 . w - q1 . z * q2 . x , <nl> + q1 . w * q2 . z - q1 . x * q2 . y + q1 . y * q2 . x + q1 . z * q2 . w <nl> + } ; <nl> + return q ; <nl> + } <nl> + <nl> + quaternion_t quaternion_inverse ( quaternion_t q ) <nl> + { <nl> + q . x * = - 1 . 0f ; <nl> + q . y * = - 1 . 0f ; <nl> + q . z * = - 1 . 0f ; <nl> + return q ; <nl> + } <nl> + <nl> + quaternion_t quat_from_two_vectors ( vector_t u , vector_t v ) <nl> + { <nl> + float w = 1 . 0f + dot ( u , v ) ; <nl> + vector_t xyz = cross ( u , v ) ; <nl> + quaternion_t q = { w , xyz . x , xyz . y , xyz . z } ; <nl> + return quaternion_normalize ( q ) ; <nl> + } <nl> + <nl> + void euler_from_quat ( quaternion_t q , float * phi , float * theta , float * psi ) <nl> + { <nl> + * phi = atan2_approx ( 2 . 0f * ( q . w * q . x + q . y * q . z ) , <nl> + 1 . 0f - 2 . 0f * ( q . x * q . x + q . y * q . y ) ) ; <nl> + * theta = asin_approx ( 2 . 0f * ( q . w * q . y - q . z * q . x ) ) ; <nl> + * psi = atan2_approx ( 2 . 0f * ( q . w * q . z + q . x * q . y ) , <nl> + 1 . 0f - 2 . 0f * ( q . y * q . y + q . z * q . z ) ) ; <nl> + } <nl> + <nl> + <nl> + float turboInvSqrt ( float x ) <nl> + { <nl> + long i ; <nl> + float x2 , y ; <nl> + const float threehalfs = 1 . 5F ; <nl> + <nl> + x2 = x * 0 . 5F ; <nl> + y = x ; <nl> + i = * ( long * ) & y ; / / evil floating point bit level hacking <nl> + i = 0x5f3759df - ( i > > 1 ) ; <nl> + y = * ( float * ) & i ; <nl> + y = y * ( threehalfs - ( x2 * y * y ) ) ; / / 1st iteration <nl> + y = y * ( threehalfs - ( x2 * y * y ) ) ; / / 2nd iteration , this can be removed <nl> + <nl> + return y ; <nl> + } <nl> + <nl> + float fsign ( float y ) <nl> + { <nl> + return ( float ) ( ( 0 < y ) - ( y < 0 ) ) ; <nl> + } <nl> + <nl> + <nl> + float fsat ( float value , float max ) <nl> + { <nl> + if ( fabs ( value ) > fabs ( max ) ) <nl> + { <nl> + value = max * fsign ( value ) ; <nl> + } <nl> + return value ; <nl> + } <nl> + <nl> + <nl> + int32_t sat ( int32_t value , int32_t max ) <nl> + { <nl> + if ( abs ( value ) > abs ( max ) ) <nl> + { <nl> + value = max * sign ( value ) ; <nl> + } <nl> + return value ; <nl> + } <nl> + <nl> + <nl> + # ifdef __GNUC__ <nl> + _Pragma ( " GCC diagnostic pop " ) <nl> + # endif <nl> + <nl> + # if defined ( _MSC_VER ) <nl> + __pragma ( warning ( pop ) ) <nl> + # endif <nl> new file mode 100644 <nl> index 000000000 . . 6ab572b60 <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / AirSimSimpleFlightBoard . hpp <nl> <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_AirSimSimpleFlightBoard_hpp <nl> + # define msr_airlib_AirSimSimpleFlightBoard_hpp <nl> + <nl> + # include < exception > <nl> + # include < vector > <nl> + # include " firmware / Board . hpp " <nl> + # include " firmware / Params . hpp " <nl> + # include " common / Common . hpp " <nl> + # include " common / ClockFactory . hpp " <nl> + # include " physics / Kinematics . hpp " <nl> + <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + class AirSimSimpleFlightBoard : public simple_flight : : Board { <nl> + public : <nl> + AirSimSimpleFlightBoard ( const simple_flight : : Params * params ) <nl> + : params_ ( params ) <nl> + { <nl> + } <nl> + <nl> + / / interface for simulator mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + / / for now we don ' t do any state estimation and use ground truth ( i . e . assume perfect sensors ) <nl> + void setKinematics ( const Kinematics : : State * kinematics ) <nl> + { <nl> + kinematics_ = kinematics ; <nl> + } <nl> + <nl> + / / called to get o / p motor signal as float value <nl> + real_T getMotorControlSignal ( uint index ) const <nl> + { <nl> + / / convert PWM to scalled 0 to 1 control signal <nl> + return ( motors_pwm_ [ index ] - params_ - > min_pwm ) / static_cast < float > ( params_ - > max_pwm - params_ - > min_pwm ) ; <nl> + } <nl> + <nl> + / / set current RC stick status <nl> + void setInputChannel ( uint channel , uint16_t val ) <nl> + { <nl> + input_channels_ [ channel ] = val ; <nl> + } <nl> + <nl> + public : <nl> + / / Board interface implementation mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + <nl> + virtual uint64_t micros ( ) const override <nl> + { <nl> + return clock ( ) - > nowNanos ( ) / 1000 ; <nl> + } <nl> + <nl> + virtual uint64_t millis ( ) const override <nl> + { <nl> + return clock ( ) - > nowNanos ( ) / 1000000 ; <nl> + } <nl> + <nl> + virtual uint16_t readChannel ( int16_t channel ) const override <nl> + { <nl> + return static_cast < uint16_t > ( input_channels_ [ channel ] ) ; <nl> + } <nl> + <nl> + virtual void writeOutput ( uint8_t index , uint16_t value ) override <nl> + { <nl> + if ( index < params_ - > motor_count ) <nl> + motors_pwm_ [ index ] = value ; <nl> + else <nl> + throw std : : runtime_error ( " cannot write motor output for index > motor count " ) ; <nl> + } <nl> + <nl> + virtual void setLed ( uint8_t index , int32_t color ) override <nl> + { <nl> + / / TODO : implement this <nl> + unused ( index ) ; <nl> + unused ( color ) ; <nl> + } <nl> + <nl> + virtual void readAccel ( float accel [ 3 ] ) const override <nl> + { <nl> + const auto & linear_accel = kinematics_ - > accelerations . linear ; <nl> + accel [ 0 ] = linear_accel . x ( ) ; <nl> + accel [ 1 ] = linear_accel . y ( ) ; <nl> + accel [ 2 ] = linear_accel . z ( ) ; <nl> + } <nl> + <nl> + virtual void readGyro ( float gyro [ 3 ] ) const override <nl> + { <nl> + const auto & angula_vel = kinematics_ - > twist . angular ; <nl> + gyro [ 0 ] = angula_vel . x ( ) ; <nl> + gyro [ 1 ] = angula_vel . y ( ) ; <nl> + gyro [ 2 ] = angula_vel . z ( ) ; <nl> + } <nl> + <nl> + virtual void delayMicros ( uint32_t us ) override <nl> + { <nl> + sleep ( us * 1E3f ) ; <nl> + } <nl> + <nl> + virtual void delayMillis ( uint32_t ms ) override <nl> + { <nl> + sleep ( static_cast < float > ( ms ) ) ; <nl> + } <nl> + <nl> + virtual void reset ( ) override <nl> + { <nl> + motors_pwm_ . assign ( params_ - > motor_count , 1000 ) ; <nl> + input_channels_ . assign ( params_ - > rc_channel_count , 1000 ) ; <nl> + } <nl> + <nl> + virtual void update ( ) override <nl> + { <nl> + / / no op for now <nl> + } <nl> + <nl> + private : <nl> + void sleep ( double msec ) <nl> + { <nl> + clock ( ) - > sleep_for ( msec * 1000 . 0 ) ; <nl> + } <nl> + <nl> + const ClockBase * clock ( ) const <nl> + { <nl> + return ClockFactory : : get ( ) ; <nl> + } <nl> + <nl> + ClockBase * clock ( ) <nl> + { <nl> + return ClockFactory : : get ( ) ; <nl> + } <nl> + <nl> + private : <nl> + / / motor outputs <nl> + std : : vector < uint16_t > motors_pwm_ ; <nl> + std : : vector < uint16_t > input_channels_ ; <nl> + <nl> + const simple_flight : : Params * params_ ; <nl> + const Kinematics : : State * kinematics_ ; <nl> + } ; <nl> + <nl> + } } / / namespace <nl> + # endif <nl> new file mode 100644 <nl> index 000000000 . . 6a73918b4 <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / AirSimSimpleFlightCommLink . hpp <nl> <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_AirSimSimpleFlightCommLink_hpp <nl> + # define msr_airlib_AirSimSimpleFlightCommLink_hpp <nl> + <nl> + # include < exception > <nl> + # include " firmware / CommLink . hpp " <nl> + # include " common / Common . hpp " <nl> + <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + <nl> + class AirSimSimpleFlightCommLink : public simple_flight : : CommLink { <nl> + public : / / derived class specific methods <nl> + void getStatusMessages ( std : : vector < std : : string > & messages ) <nl> + { <nl> + if ( messages_ . size ( ) > 0 ) { <nl> + messages . insert ( messages . end ( ) , messages_ . begin ( ) , messages_ . end ( ) ) ; <nl> + messages_ . clear ( ) ; <nl> + } <nl> + } <nl> + <nl> + public : / / implement CommLink interface <nl> + virtual void reset ( ) <nl> + { <nl> + messages_ . clear ( ) ; <nl> + } <nl> + <nl> + virtual void update ( ) <nl> + { <nl> + } <nl> + <nl> + virtual void log ( const char * message , int32_t error_level ) <nl> + { <nl> + unused ( error_level ) ; <nl> + messages_ . push_back ( std : : string ( message ) ) ; <nl> + } <nl> + <nl> + private : <nl> + std : : vector < std : : string > messages_ ; <nl> + <nl> + } ; <nl> + <nl> + <nl> + } } / / namespace <nl> + # endif <nl> new file mode 100644 <nl> index 000000000 . . c9a1b09ee <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / SimpleFlightDroneController . hpp <nl> <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_SimpleFlightDroneController_hpp <nl> + # define msr_airlib_SimpleFlightDroneController_hpp <nl> + <nl> + # include " controllers / DroneControllerBase . hpp " <nl> + # include " sensors / SensorCollection . hpp " <nl> + # include " physics / Environment . hpp " <nl> + # include " physics / Kinematics . hpp " <nl> + # include " vehicles / MultiRotorParams . hpp " <nl> + # include " common / Common . hpp " <nl> + # include " AirSimSimpleFlightBoard . hpp " <nl> + # include " AirSimSimpleFlightCommLink . hpp " <nl> + # include " controllers / Settings . hpp " <nl> + # include " firmware / firmware . hpp " <nl> + <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + class SimpleFlightDroneController : public DroneControllerBase { <nl> + <nl> + public : <nl> + SimpleFlightDroneController ( const MultiRotorParams * vehicle_params ) <nl> + : vehicle_params_ ( vehicle_params ) <nl> + { <nl> + / / create sim implementations of board and commlink <nl> + board_ . reset ( new AirSimSimpleFlightBoard ( & params_ ) ) ; <nl> + comm_link_ . reset ( new AirSimSimpleFlightCommLink ( ) ) ; <nl> + <nl> + / / create firmware <nl> + firmware_ . reset ( new simple_flight : : Firmware ( board_ . get ( ) , comm_link_ . get ( ) , & params_ ) ) ; <nl> + firmware_ - > reset ( ) ; <nl> + <nl> + / / find out which RC we should use <nl> + Settings child ; <nl> + Settings : : singleton ( ) . getChild ( " SimpleFlight " , child ) ; <nl> + remote_control_id_ = child . getInt ( " RemoteControlID " , 0 ) ; <nl> + } <nl> + <nl> + void initializePhysics ( const Environment * environment , const Kinematics : : State * kinematics ) <nl> + { <nl> + environment_ = environment ; <nl> + kinematics_ = kinematics ; <nl> + <nl> + board_ - > setKinematics ( kinematics_ ) ; <nl> + } <nl> + <nl> + public : <nl> + / / * * * Start : VehicleControllerBase implementation * * * / / <nl> + virtual void reset ( ) override <nl> + { <nl> + firmware_ - > reset ( ) ; <nl> + } <nl> + <nl> + virtual void update ( ) override <nl> + { <nl> + firmware_ - > update ( ) ; <nl> + } <nl> + <nl> + virtual void start ( ) override <nl> + { <nl> + } <nl> + <nl> + virtual void stop ( ) override <nl> + { <nl> + } <nl> + <nl> + virtual size_t getVertexCount ( ) override <nl> + { <nl> + return vehicle_params_ - > getParams ( ) . rotor_count ; <nl> + } <nl> + <nl> + virtual real_T getVertexControlSignal ( unsigned int rotor_index ) override <nl> + { <nl> + / / convert counter clockwise index to ArduCopter ' s QuadX style index <nl> + unsigned int index_quadx ; <nl> + switch ( rotor_index ) <nl> + { <nl> + case 0 : index_quadx = 1 ; break ; <nl> + case 1 : index_quadx = 2 ; break ; <nl> + case 2 : index_quadx = 3 ; break ; <nl> + case 3 : index_quadx = 0 ; break ; <nl> + default : <nl> + throw std : : runtime_error ( " Rotor index beyond 3 is not supported yet in ROSFlight firmware " ) ; <nl> + } <nl> + <nl> + auto control_signal = board_ - > getMotorControlSignal ( index_quadx ) ; <nl> + <nl> + return control_signal ; <nl> + } <nl> + <nl> + virtual void getStatusMessages ( std : : vector < std : : string > & messages ) override <nl> + { <nl> + comm_link_ - > getStatusMessages ( messages ) ; <nl> + } <nl> + <nl> + virtual bool isOffboardMode ( ) override <nl> + { <nl> + / / TODO : support offboard mode <nl> + return false ; <nl> + } <nl> + <nl> + virtual bool isSimulationMode ( ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + virtual void setOffboardMode ( bool is_set ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + virtual void setSimulationMode ( bool is_set ) override <nl> + { <nl> + if ( ! is_set ) <nl> + throw VehicleCommandNotImplementedException ( " setting non - simulation mode is not supported yet " ) ; <nl> + } <nl> + / / * * * End : VehicleControllerBase implementation * * * / / <nl> + <nl> + / / * * * Start : DroneControllerBase implementation * * * / / <nl> + public : <nl> + Vector3r getPosition ( ) override <nl> + { <nl> + return kinematics_ - > pose . position ; <nl> + } <nl> + <nl> + Vector3r getVelocity ( ) override <nl> + { <nl> + return kinematics_ - > twist . linear ; <nl> + } <nl> + <nl> + Quaternionr getOrientation ( ) override <nl> + { <nl> + return kinematics_ - > pose . orientation ; <nl> + } <nl> + <nl> + LandedState getLandedState ( ) override <nl> + { <nl> + / / TODO : implement this <nl> + return LandedState : : Landed ; <nl> + } <nl> + <nl> + virtual int getRemoteControlID ( ) override <nl> + { <nl> + return remote_control_id_ ; <nl> + } <nl> + <nl> + RCData getRCData ( ) override <nl> + { <nl> + return RCData ( ) ; <nl> + } <nl> + <nl> + void setRCData ( const RCData & rcData ) override <nl> + { <nl> + if ( rcData . is_connected ) { <nl> + board_ - > setInputChannel ( 0 , angleToPwm ( rcData . roll ) ) ; / / X <nl> + board_ - > setInputChannel ( 1 , angleToPwm ( rcData . yaw ) ) ; / / Y <nl> + board_ - > setInputChannel ( 2 , thrustToPwm ( rcData . throttle ) ) ; / / F <nl> + board_ - > setInputChannel ( 3 , angleToPwm ( - rcData . pitch ) ) ; / / Z <nl> + board_ - > setInputChannel ( 4 , switchToPwm ( rcData . switch1 ) ) ; <nl> + board_ - > setInputChannel ( 5 , switchToPwm ( rcData . switch2 ) ) ; <nl> + board_ - > setInputChannel ( 6 , switchToPwm ( rcData . switch3 ) ) ; <nl> + board_ - > setInputChannel ( 7 , switchToPwm ( rcData . switch4 ) ) ; <nl> + board_ - > setInputChannel ( 8 , switchToPwm ( rcData . switch5 ) ) ; <nl> + board_ - > setInputChannel ( 9 , switchToPwm ( rcData . switch6 ) ) ; <nl> + board_ - > setInputChannel ( 10 , switchToPwm ( rcData . switch7 ) ) ; <nl> + board_ - > setInputChannel ( 11 , switchToPwm ( rcData . switch8 ) ) ; <nl> + } <nl> + / / else we don ' t have RC data <nl> + } <nl> + <nl> + bool armDisarm ( bool arm , CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool takeoff ( float max_wait_seconds , CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool land ( float max_wait_seconds , CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool goHome ( CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + bool hover ( CancelableBase & cancelable_action ) override <nl> + { <nl> + return true ; <nl> + } <nl> + <nl> + GeoPoint getHomePoint ( ) override <nl> + { <nl> + return environment_ - > getInitialState ( ) . geo_point ; <nl> + } <nl> + <nl> + GeoPoint getGpsLocation ( ) override <nl> + { <nl> + return environment_ - > getState ( ) . geo_point ; <nl> + } <nl> + <nl> + virtual void reportTelemetry ( float renderTime ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + float getCommandPeriod ( ) override <nl> + { <nl> + return 1 . 0f / 50 ; / / 50hz <nl> + } <nl> + <nl> + float getTakeoffZ ( ) override <nl> + { <nl> + / / pick a number , 3 meters is probably safe <nl> + / / enough to get out of the backwash turbulance . Negative due to NED coordinate system . <nl> + return - 3 . 0f ; <nl> + } <nl> + <nl> + float getDistanceAccuracy ( ) override <nl> + { <nl> + return 0 . 5f ; / / measured in simulator by firing commands " MoveToLocation - x 0 - y 0 " multiple times and looking at distance travelled <nl> + } <nl> + <nl> + protected : <nl> + void commandRollPitchZ ( float pitch , float roll , float z , float yaw ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + void commandVelocity ( float vx , float vy , float vz , const YawMode & yaw_mode ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + void commandVelocityZ ( float vx , float vy , float z , const YawMode & yaw_mode ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + void commandPosition ( float x , float y , float z , const YawMode & yaw_mode ) override <nl> + { <nl> + / / TODO : implement this <nl> + } <nl> + <nl> + const VehicleParams & getVehicleParams ( ) override <nl> + { <nl> + / / used for safety algos . For now just use defaults <nl> + static const VehicleParams safety_params ; <nl> + return safety_params ; <nl> + } <nl> + / / * * * End : DroneControllerBase implementation * * * / / <nl> + <nl> + private : <nl> + / / convert pitch , roll , yaw from - 1 to 1 to PWM <nl> + static uint16_t angleToPwm ( float angle ) <nl> + { <nl> + return static_cast < uint16_t > ( angle * 500 . 0f + 1500 . 0f ) ; <nl> + } <nl> + static uint16_t thrustToPwm ( float thrust ) <nl> + { <nl> + return static_cast < uint16_t > ( ( thrust < 0 ? 0 : thrust ) * 1000 . 0f + 1000 . 0f ) ; <nl> + } <nl> + static uint16_t switchToPwm ( uint switchVal , uint maxSwitchVal = 1 ) <nl> + { <nl> + return static_cast < uint16_t > ( 1000 . 0f * switchVal / maxSwitchVal + 1000 . 0f ) ; <nl> + } <nl> + <nl> + private : <nl> + const MultiRotorParams * vehicle_params_ ; <nl> + const Kinematics : : State * kinematics_ ; <nl> + const Environment * environment_ ; <nl> + <nl> + int remote_control_id_ = 0 ; <nl> + simple_flight : : Params params_ ; <nl> + <nl> + unique_ptr < AirSimSimpleFlightBoard > board_ ; <nl> + unique_ptr < AirSimSimpleFlightCommLink > comm_link_ ; <nl> + unique_ptr < simple_flight : : Firmware > firmware_ ; <nl> + } ; <nl> + <nl> + } } / / namespace <nl> + # endif <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 000000000 . . 25f7ccb49 <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / firmware / Board . hpp <nl> <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + <nl> + namespace simple_flight { <nl> + <nl> + class Board { <nl> + public : <nl> + virtual uint64_t micros ( ) const = 0 ; <nl> + virtual uint64_t millis ( ) const = 0 ; <nl> + virtual uint16_t readChannel ( int16_t channel ) const = 0 ; <nl> + virtual void writeOutput ( uint8_t index , uint16_t pwm ) = 0 ; <nl> + virtual void setLed ( uint8_t index , int32_t color ) = 0 ; <nl> + virtual void readAccel ( float accel [ 3 ] ) const = 0 ; <nl> + virtual void readGyro ( float gyro [ 3 ] ) const = 0 ; <nl> + virtual void delayMicros ( uint32_t us ) = 0 ; <nl> + virtual void delayMillis ( uint32_t ms ) = 0 ; <nl> + virtual void reset ( ) = 0 ; <nl> + virtual void update ( ) = 0 ; <nl> + } ; <nl> + <nl> + <nl> + } / / namespace <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 000000000 . . 98fddce5c <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / firmware / CommLink . hpp <nl> <nl> + # pragma once <nl> + <nl> + # include < cstdint > <nl> + <nl> + <nl> + namespace simple_flight { <nl> + <nl> + class CommLink { <nl> + public : <nl> + virtual void reset ( ) = 0 ; <nl> + virtual void update ( ) = 0 ; <nl> + virtual void log ( const char * message , int32_t error_level ) = 0 ; <nl> + } ; <nl> + <nl> + <nl> + } / / namespace <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 000000000 . . 0975620f8 <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / firmware / Firmware . hpp <nl> <nl> + # pragma once <nl> + <nl> + # include " Board . hpp " <nl> + # include " CommLink . hpp " <nl> + # include " Params . hpp " <nl> + # include " RemoteControl . hpp " <nl> + <nl> + namespace simple_flight { <nl> + <nl> + class Firmware { <nl> + public : <nl> + Firmware ( Board * board , CommLink * comm_link , const Params * params ) <nl> + : board_ ( board ) , comm_link_ ( comm_link ) , params_ ( params ) , rc_ ( board , params ) <nl> + { <nl> + } <nl> + <nl> + void reset ( ) <nl> + { <nl> + board_ - > reset ( ) ; <nl> + comm_link_ - > reset ( ) ; <nl> + rc_ . reset ( ) ; <nl> + } <nl> + <nl> + void update ( ) <nl> + { <nl> + board_ - > update ( ) ; <nl> + comm_link_ - > update ( ) ; <nl> + rc_ . update ( ) ; <nl> + } <nl> + <nl> + private : <nl> + / / objects we use <nl> + Board * board_ ; <nl> + CommLink * comm_link_ ; <nl> + <nl> + const Params * params_ ; <nl> + RemoteControl rc_ ; <nl> + } ; <nl> + <nl> + <nl> + } / / namespace <nl> + <nl> new file mode 100644 <nl> index 000000000 . . 2ee15266c <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / firmware / Params . hpp <nl> <nl> + # pragma once <nl> + <nl> + namespace simple_flight { <nl> + <nl> + struct Params { <nl> + public : <nl> + int16_t rc_channel_count = 12 ; <nl> + int16_t rc_read_interval_ms = 10 ; <nl> + int16_t rc_thrust_channel = 2 ; <nl> + int16_t rc_pitch_channel = 3 ; <nl> + int16_t rc_roll_channel = 0 ; <nl> + int16_t rc_yaw_channel = 1 ; <nl> + <nl> + <nl> + uint16_t motor_count = 16 ; <nl> + uint16_t min_pwm = 1000 ; <nl> + uint16_t max_pwm = 2000 ; <nl> + } ; <nl> + <nl> + <nl> + } / / namespace <nl> \ No newline at end of file <nl> new file mode 100644 <nl> index 000000000 . . 320153aab <nl> mmm / dev / null <nl> ppp b / AirLib / include / controllers / simple_flight / firmware / RemoteControl . hpp <nl> <nl> + # pragma once <nl> + <nl> + # include < vector > <nl> + # include < cstdint > <nl> + # include " Board . hpp " <nl> + <nl> + namespace simple_flight { <nl> + <nl> + class RemoteControl { <nl> + public : <nl> + RemoteControl ( const Board * board , const Params * params ) <nl> + : board_ ( board ) , params_ ( params ) <nl> + { <nl> + pwm_range = params_ - > max_pwm - params_ - > min_pwm ; <nl> + } <nl> + <nl> + void reset ( ) <nl> + { <nl> + rc_channels_ . assign ( params_ - > rc_channel_count , 0 ) ; <nl> + last_rec_read_ = 0 ; <nl> + } <nl> + <nl> + <nl> + void update ( ) <nl> + { <nl> + uint64_t time = board_ - > millis ( ) ; <nl> + <nl> + / / don ' t keep reading if not updated <nl> + if ( time - last_rec_read_ < = params_ - > rc_read_interval_ms ) <nl> + return ; <nl> + <nl> + last_rec_read_ = time ; <nl> + <nl> + / / read rc <nl> + for ( int channel = 0 ; channel < params_ - > rc_channel_count ; + + channel ) <nl> + rc_channels_ [ channel ] = board_ - > readChannel ( channel ) ; <nl> + <nl> + thrust = normalizePwm ( rc_channels_ [ params_ - > rc_thrust_channel ] ) ; <nl> + pitch = normalizePwm ( rc_channels_ [ params_ - > rc_pitch_channel ] ) ; <nl> + roll = normalizePwm ( rc_channels_ [ params_ - > rc_roll_channel ] ) ; <nl> + yaw = normalizePwm ( rc_channels_ [ params_ - > rc_yaw_channel ] ) ; <nl> + } <nl> + <nl> + <nl> + private : <nl> + float normalizePwm ( uint16_t pwm ) <nl> + { <nl> + return ( pwm - params_ - > min_pwm ) / pwm_range ; <nl> + } <nl> + private : <nl> + const Board * board_ ; <nl> + const Params * params_ ; <nl> + <nl> + std : : vector < uint16_t > rc_channels_ ; <nl> + uint64_t last_rec_read_ ; <nl> + float thrust , pitch , roll , yaw ; <nl> + <nl> + float pwm_range ; <nl> + } ; <nl> + <nl> + <nl> + } / / namespace <nl> \ No newline at end of file <nl> mmm a / AirLib / include / vehicles / MultiRotorParams . hpp <nl> ppp b / AirLib / include / vehicles / MultiRotorParams . hpp <nl> class MultiRotorParams { <nl> return controller_ . get ( ) ; <nl> } <nl> <nl> - / / below method is needed to support firmwares without state estimation . In future , we should probably remove this support . <nl> + / / TODO : below method is needed to support firmwares without state estimation . In future , we should probably remove this support . <nl> virtual void initializePhysics ( const Environment * environment , const Kinematics : : State * kinematics ) <nl> { <nl> unused ( environment ) ; <nl> mmm a / AirLib / include / vehicles / MultiRotorParamsFactory . hpp <nl> ppp b / AirLib / include / vehicles / MultiRotorParamsFactory . hpp <nl> <nl> # define msr_airlib_vehicles_MultiRotorParamsFactory_hpp <nl> <nl> # include " vehicles / configs / RosFlightQuadX . hpp " <nl> + # include " vehicles / configs / SimpleFlightQuadX . hpp " <nl> # include " controllers / MavLinkDroneController . hpp " <nl> # include " controllers / Settings . hpp " <nl> # include " vehicles / configs / Px4MultiRotor . hpp " <nl> class MultiRotorParamsFactory { <nl> config . reset ( new Px4MultiRotor ( child ) ) ; <nl> } else if ( vehicle_name = = " RosFlight " ) { <nl> config . reset ( new RosFlightQuadX ( child ) ) ; <nl> + } else if ( vehicle_name = = " SimpleFlight " ) { <nl> + config . reset ( new SimpleFlightQuadX ( child ) ) ; <nl> } else <nl> throw std : : runtime_error ( Utils : : stringf ( " Cannot create vehicle config because vehicle name ' % s ' is not recognized " , vehicle_name . c_str ( ) ) ) ; <nl> <nl> mmm a / AirLib / include / vehicles / configs / Px4MultiRotor . hpp <nl> ppp b / AirLib / include / vehicles / configs / Px4MultiRotor . hpp <nl> class Px4MultiRotor : public MultiRotorParams { <nl> <nl> Vector3r unit_z ( 0 , 0 , - 1 ) ; / / NED frame <nl> <nl> - / / relative to Forward vector in the order ( 0 , 3 , 1 , 2 ) required by quad X pattern <nl> - / / http : / / ardupilot . org / copter / _images / MOTORS_QuadX_QuadPlus . jpg <nl> + / / relative to Forward vector in the order ( 0 , 3 , 1 , 2 ) required by quad X pattern <nl> + / / http : / / ardupilot . org / copter / _images / MOTORS_QuadX_QuadPlus . jpg <nl> arm_lengths . push_back ( 0 . 22f ) ; <nl> arm_lengths . push_back ( 0 . 255f ) ; <nl> arm_lengths . push_back ( 0 . 22f ) ; <nl> mmm a / AirLib / include / vehicles / configs / RosFlightQuadX . hpp <nl> ppp b / AirLib / include / vehicles / configs / RosFlightQuadX . hpp <nl> <nl> # ifndef msr_airlib_vehicles_RosFlightQuadX_hpp <nl> # define msr_airlib_vehicles_RosFlightQuadX_hpp <nl> <nl> - # include " controllers / rosflight / RosFlightDroneController . hpp " <nl> + # include " controllers / ros_flight / RosFlightDroneController . hpp " <nl> # include " vehicles / MultiRotorParams . hpp " <nl> # include " controllers / Settings . hpp " <nl> <nl> new file mode 100644 <nl> index 000000000 . . cba9766e5 <nl> mmm / dev / null <nl> ppp b / AirLib / include / vehicles / configs / SimpleFlightQuadX . hpp <nl> <nl> + / / Copyright ( c ) Microsoft Corporation . All rights reserved . <nl> + / / Licensed under the MIT License . <nl> + <nl> + # ifndef msr_airlib_vehicles_SimpleFlightQuadX_hpp <nl> + # define msr_airlib_vehicles_SimpleFlightQuadX_hpp <nl> + <nl> + # include " controllers / simple_flight / SimpleFlightDroneController . hpp " <nl> + # include " vehicles / MultiRotorParams . hpp " <nl> + # include " controllers / Settings . hpp " <nl> + <nl> + <nl> + namespace msr { namespace airlib { <nl> + <nl> + class SimpleFlightQuadX : public MultiRotorParams { <nl> + public : <nl> + SimpleFlightQuadX ( Settings & settings ) <nl> + { <nl> + unused ( settings ) ; <nl> + } <nl> + <nl> + virtual void initializePhysics ( const Environment * environment , const Kinematics : : State * kinematics ) override <nl> + { <nl> + / / supply this to controller so it can use physics ground truth instead of state estimation ( because ROSFlight doesn ' t have state estimation ) <nl> + static_cast < SimpleFlightDroneController * > ( getController ( ) ) - > initializePhysics ( environment_ , kinematics_ ) ; <nl> + } <nl> + <nl> + protected : <nl> + virtual void setup ( Params & params , SensorCollection & sensors , unique_ptr < DroneControllerBase > & controller ) override <nl> + { <nl> + / * * * * * * * Below is same config as Pixhawk generic model * * * * * * * * / <nl> + <nl> + / / set up arm lengths <nl> + / / dimensions are for F450 frame : http : / / artofcircuits . com / product / quadcopter - frame - hj450 - with - power - distribution <nl> + params . rotor_count = 4 ; <nl> + std : : vector < real_T > arm_lengths ( params . rotor_count , 0 . 2275f ) ; <nl> + <nl> + / / set up mass <nl> + params . mass = 1 . 0f ; / / can be varied from 0 . 800 to 1 . 600 <nl> + real_T motor_assembly_weight = 0 . 055f ; / / weight for MT2212 motor for F450 frame <nl> + real_T box_mass = params . mass - params . rotor_count * motor_assembly_weight ; <nl> + <nl> + / / using rotor_param default , but if you want to change any of the rotor_params , call calculateMaxThrust ( ) to recompute the max_thrust <nl> + / / given new thrust coefficients , motor max_rpm and propeller diameter . <nl> + params . rotor_params . calculateMaxThrust ( ) ; <nl> + <nl> + / / set up dimensions of core body box or abdomen ( not including arms ) . <nl> + params . body_box . x ( ) = 0 . 180f ; params . body_box . y ( ) = 0 . 11f ; params . body_box . z ( ) = 0 . 040f ; <nl> + real_T rotor_z = 2 . 5f / 100 ; <nl> + <nl> + / / computer rotor poses <nl> + initializeRotorQuadX ( params . rotor_poses , params . rotor_count , arm_lengths . data ( ) , rotor_z ) ; <nl> + <nl> + / / compute inertia matrix <nl> + computeInertiaMatrix ( params . inertia , params . body_box , params . rotor_poses , box_mass , motor_assembly_weight ) ; <nl> + <nl> + createStandardSensors ( sensor_storage_ , sensors , params . enabled_sensors ) ; <nl> + createController ( controller , sensors ) ; <nl> + <nl> + / / leave everything else to defaults <nl> + } <nl> + <nl> + private : <nl> + void createController ( unique_ptr < DroneControllerBase > & controller , SensorCollection & sensors ) <nl> + { <nl> + controller . reset ( new SimpleFlightDroneController ( this ) ) ; <nl> + } <nl> + <nl> + private : <nl> + vector < unique_ptr < SensorBase > > sensor_storage_ ; <nl> + const Kinematics : : State * kinematics_ ; <nl> + const Environment * environment_ ; <nl> + } ; <nl> + <nl> + } } / / namespace <nl> + # endif <nl>
initial simple_flight
microsoft/AirSim
1b34838258fcb7501b43cc06f06bacf786fea451
2017-06-22T06:52:52Z
mmm a / docs / en / query_language / functions / array_functions . md <nl> ppp b / docs / en / query_language / functions / array_functions . md <nl> SELECT arrayReverseSort ( [ 1 , 3 , 3 , 0 ] ) <nl> ` ` ` <nl> <nl> Example 2 <nl> + <nl> ` ` ` sql <nl> SELECT arrayReverseSort ( [ ' hello ' , ' world ' , ' ! ' ] ) <nl> ` ` ` <nl>
Added info about arraySort
ClickHouse/ClickHouse
35c41cf05749ac92cd7a626039d2bf8f381708f3
2019-04-19T16:04:45Z
mmm a / . github / workflows / lint . yml <nl> ppp b / . github / workflows / lint . yml <nl> jobs : <nl> id : get_pr_tip <nl> - name : Run flake8 <nl> run : | <nl> - set - eux <nl> + set - eux - o pipefail <nl> pip install flake8 = = 3 . 8 . 2 flake8 - bugbear flake8 - comprehensions flake8 - executable flake8 - pyi = = 20 . 5 . 0 mccabe pycodestyle = = 2 . 6 . 0 pyflakes = = 2 . 2 . 0 <nl> flake8 - - version <nl> - flake8 > $ { GITHUB_WORKSPACE } / flake8 - output . txt <nl> - cat $ { GITHUB_WORKSPACE } / flake8 - output . txt <nl> + flake8 | tee $ { GITHUB_WORKSPACE } / flake8 - output . txt <nl> - name : Add annotations <nl> uses : pytorch / add - annotations - github - action @ master <nl> with : <nl>
Show Flake8 errors in GitHub CI again ( )
pytorch/pytorch
1e275bc1a64919536a7a269fc4de0ea100710da7
2020-10-29T18:59:30Z
mmm a / src / rdb_protocol / protocol . cc <nl> ppp b / src / rdb_protocol / protocol . cc <nl> region_t rdb_protocol_t : : cpu_sharding_subspace ( int subregion_number , <nl> return region_t ( beg , end , key_range_t : : universe ( ) ) ; <nl> } <nl> <nl> + hash_region_t < key_range_t > sindex_range_t : : to_region ( ) const { <nl> + return hash_region_t < key_range_t > ( <nl> + rdb_protocol_t : : sindex_key_range ( <nl> + start ! = NULL ? start - > truncated_secondary ( ) : store_key_t : : min ( ) , <nl> + end ! = NULL ? end - > truncated_secondary ( ) : store_key_t : : max ( ) ) ) ; <nl> + } <nl> + <nl> + <nl> bool sindex_range_t : : contains ( counted_t < const ql : : datum_t > value ) const { <nl> return ( ! start | | ( * start < * value | | ( * start = = * value & & ! start_open ) ) ) & & <nl> ( ! end | | ( * value < * end | | ( * value = = * end & & ! end_open ) ) ) ; <nl> mmm a / src / rdb_protocol / protocol . hpp <nl> ppp b / src / rdb_protocol / protocol . hpp <nl> class sindex_range_t { <nl> counted_t < const ql : : datum_t > _end , bool _end_open ) <nl> : start ( _start ) , end ( _end ) , start_open ( _start_open ) , end_open ( _end_open ) { } <nl> / / Constructs some kind of region out of truncated_secondary values . <nl> + hash_region_t < key_range_t > to_region ( ) const ; <nl> bool contains ( counted_t < const ql : : datum_t > value ) const ; <nl> <nl> counted_t < const ql : : datum_t > start , end ; <nl> struct rdb_protocol_t { <nl> sorting_t _sorting = UNORDERED ) <nl> : region ( region_t : : universe ( ) ) , sindex ( _sindex ) , <nl> sindex_range ( _sindex_range ) , <nl> - sindex_region ( <nl> - hash_region_t < key_range_t > ( <nl> - rdb_protocol_t : : sindex_key_range ( <nl> - _sindex_range . start ! = NULL <nl> - ? _sindex_range . start - > truncated_secondary ( ) <nl> - : store_key_t : : min ( ) , <nl> - _sindex_range . end ! = NULL <nl> - ? _sindex_range . end - > truncated_secondary ( ) <nl> - : store_key_t : : max ( ) ) ) ) , <nl> + sindex_region ( sindex_range - > to_region ( ) ) , <nl> sorting ( _sorting ) { } <nl> <nl> rget_read_t ( const region_t & _sindex_region , <nl>
added function back
rethinkdb/rethinkdb
3f8e828359134d9329ce0ed9f7d48b830fba7708
2013-10-21T21:33:52Z
mmm a / dbms / benchmark / clickhouse / benchmark . sh <nl> ppp b / dbms / benchmark / clickhouse / benchmark . sh <nl> <nl> # ! / bin / bash <nl> <nl> - ck = " clickhouse - client " <nl> test_table = " hits_100m " <nl> - claster = " self " <nl> <nl> start_date = " ' 2013 - 07 - 01 ' " <nl> early_stop_date = " ' 2013 - 07 - 02 ' " <nl> stop_date = " ' 2013 - 07 - 31 ' " <nl> counter_id = 34 <nl> <nl> - function run_ck_server <nl> + function run_ck_server <nl> { <nl> - sudo sh - c " ulimit - v 54000000 ; / etc / init . d / clickhouse - server - metrika - yandex - ulimit restart " <nl> + sudo sh - c " ulimit - v 54000000 ; / etc / init . d / clickhouse - server restart " <nl> } <nl> <nl> # execute queries <nl> function execute ( ) <nl> if [ [ $ query = ~ $ comment_re ] ] ; then <nl> echo " $ query " <nl> echo <nl> - else <nl> + else <nl> sync <nl> sudo sh - c " echo 3 > / proc / sys / vm / drop_caches " <nl> <nl> function execute ( ) <nl> fi <nl> <nl> # restart clickhouse if failed <nl> - ps aux | grep - P ' \ d + / usr / bin / clickhouse - server ' <nl> + ps aux | grep - P ' \ d + clickhouse - server ' <nl> if [ " $ ? " ! = " 0 " ] ; then <nl> run_ck_server <nl> fi <nl> function execute ( ) <nl> fi <nl> <nl> let " index = $ index + 1 " <nl> + echo " Ran $ index queries . " > & 2 <nl> done <nl> } <nl> <nl> mmm a / dbms / benchmark / clickhouse / expect . tcl <nl> ppp b / dbms / benchmark / clickhouse / expect . tcl <nl> <nl> - # ! / bin / bash <nl> # ! / bin / expect <nl> <nl> # Set timeout <nl> mmm a / dbms / include / DB / AggregateFunctions / AggregateFunctionUniq . h <nl> ppp b / dbms / include / DB / AggregateFunctions / AggregateFunctionUniq . h <nl> <nl> # include < type_traits > <nl> <nl> # include < stats / UniquesHashSet . h > <nl> - # include < statdaemons / HyperLogLogCounter . h > <nl> <nl> # include < DB / IO / WriteHelpers . h > <nl> # include < DB / IO / ReadHelpers . h > <nl> <nl> <nl> # include < DB / Interpreters / AggregationCommon . h > <nl> # include < DB / Common / HashTable / HashSet . h > <nl> + # include < DB / Common / HyperLogLogWithSmallSetOptimization . h > <nl> <nl> # include < DB / Columns / ColumnString . h > <nl> <nl> struct AggregateFunctionUniqUniquesHashSetData <nl> { <nl> typedef UniquesHashSet < DefaultHash < UInt64 > > Set ; <nl> Set set ; <nl> - <nl> + <nl> static String getName ( ) { return " uniq " ; } <nl> } ; <nl> <nl> <nl> + template < typename T > <nl> struct AggregateFunctionUniqHLL12Data <nl> { <nl> - typedef HLL12 Set ; <nl> + typedef HyperLogLogWithSmallSetOptimization < T , 16 , 12 > Set ; <nl> + Set set ; <nl> + <nl> + static String getName ( ) { return " uniqHLL12 " ; } <nl> + } ; <nl> + <nl> + template < > <nl> + struct AggregateFunctionUniqHLL12Data < String > <nl> + { <nl> + typedef HyperLogLogWithSmallSetOptimization < UInt64 , 16 , 12 > Set ; <nl> Set set ; <nl> - <nl> + <nl> static String getName ( ) { return " uniqHLL12 " ; } <nl> } ; <nl> <nl> mmm a / dbms / include / DB / Client / ParallelReplicas . h <nl> ppp b / dbms / include / DB / Client / ParallelReplicas . h <nl> <nl> # include < DB / Common / Throttler . h > <nl> # include < DB / Client / Connection . h > <nl> # include < DB / Client / ConnectionPool . h > <nl> + # include < Poco / ScopedLock . h > <nl> + # include < Poco / Mutex . h > <nl> <nl> <nl> namespace DB <nl> namespace DB <nl> <nl> / * * Для получения данных сразу из нескольких реплик ( соединений ) в рамках одного потока . <nl> * В качестве вырожденного случая , может также работать с одним соединением . <nl> + * Предполагается , что все функции кроме sendCancel всегда выполняются в одном потоке . <nl> * <nl> * Интерфейс почти совпадает с Connection . <nl> * / <nl> class ParallelReplicas final : private boost : : noncopyable <nl> std : : string dumpAddresses ( ) const ; <nl> <nl> / / / Возвращает количесто реплик . <nl> + / / / Без блокировки , потому что sendCancel ( ) не меняет это количество . <nl> size_t size ( ) const { return replica_map . size ( ) ; } <nl> <nl> / / / Проверить , есть ли действительные реплики . <nl> + / / / Без блокировки , потому что sendCancel ( ) не меняет состояние реплик . <nl> bool hasActiveReplicas ( ) const { return active_replica_count > 0 ; } <nl> <nl> private : <nl> / / / Реплики хэшированные по id сокета <nl> using ReplicaMap = std : : unordered_map < int , Connection * > ; <nl> <nl> - <nl> + private : <nl> / / / Зарегистрировать реплику . <nl> void registerReplica ( Connection * connection ) ; <nl> <nl> + / / / Внутренняя версия функции receivePacket без блокировки . <nl> + Connection : : Packet receivePacketUnlocked ( ) ; <nl> + <nl> / / / Получить реплику , на которой можно прочитать данные . <nl> ReplicaMap : : iterator getReplicaForReading ( ) ; <nl> <nl> / * * Проверить , есть ли данные , которые можно прочитать на каких - нибудь репликах . <nl> - * Возвращает одну такую реплику , если она найдётся . <nl> - * / <nl> + * Возвращает одну такую реплику , если она найдётся . <nl> + * / <nl> ReplicaMap : : iterator waitForReadEvent ( ) ; <nl> <nl> / / / Пометить реплику как недействительную . <nl> void invalidateReplica ( ReplicaMap : : iterator it ) ; <nl> <nl> - <nl> + private : <nl> Settings * settings ; <nl> ReplicaMap replica_map ; <nl> <nl> class ParallelReplicas final : private boost : : noncopyable <nl> bool sent_query = false ; <nl> / / / Отменили запрос <nl> bool cancelled = false ; <nl> + <nl> + / / / Мьютекс для того , чтобы функция sendCancel могла выполняться безопасно <nl> + / / / в отдельном потоке . <nl> + mutable Poco : : FastMutex cancel_mutex ; <nl> } ; <nl> <nl> } <nl> mmm a / dbms / include / DB / Common / Arena . h <nl> ppp b / dbms / include / DB / Common / Arena . h <nl> class Arena <nl> <nl> size_t growth_factor ; <nl> size_t linear_growth_threshold ; <nl> - <nl> + <nl> / / / Последний непрерывный кусок памяти . <nl> Chunk * head ; <nl> size_t size_in_bytes ; <nl> class Arena <nl> size_t nextSize ( size_t min_next_size ) const <nl> { <nl> size_t size_after_grow = 0 ; <nl> - <nl> + <nl> if ( head - > size ( ) < linear_growth_threshold ) <nl> size_after_grow = head - > size ( ) * growth_factor ; <nl> else <nl> class Arena <nl> return res ; <nl> } <nl> <nl> + / * * Отменить только что сделанное выделение памяти . <nl> + * Нужно передать размер не меньше того , который был только что выделен . <nl> + * / <nl> + void rollback ( size_t size ) <nl> + { <nl> + head - > pos - = size ; <nl> + } <nl> + <nl> + / * * Начать или расширить непрерывный кусок памяти . <nl> + * begin - текущее начало куска памяти , если его надо расширить , или nullptr , если его надо начать . <nl> + * Если в чанке не хватило места - скопировать существующие данные в новый кусок памяти и изменить значение begin . <nl> + * / <nl> + char * allocContinue ( size_t size , char const * & begin ) <nl> + { <nl> + if ( unlikely ( head - > pos + size > head - > end ) ) <nl> + { <nl> + char * prev_end = head - > pos ; <nl> + addChunk ( size ) ; <nl> + <nl> + if ( begin ) <nl> + { <nl> + begin = insert ( begin , prev_end - begin ) ; <nl> + return allocContinue ( size , begin ) ; <nl> + } <nl> + } <nl> + <nl> + char * res = head - > pos ; <nl> + head - > pos + = size ; <nl> + <nl> + if ( ! begin ) <nl> + begin = res ; <nl> + <nl> + return res ; <nl> + } <nl> + <nl> / / / Вставить строку без выравнивания . <nl> const char * insert ( const char * data , size_t size ) <nl> { <nl> class Arena <nl> memcpy ( res , data , size ) ; <nl> return res ; <nl> } <nl> - <nl> + <nl> / / / Размер выделенного пула в байтах <nl> size_t size ( ) const <nl> { <nl> new file mode 100644 <nl> index 00000000000 . . 7932ddfb0e8 <nl> mmm / dev / null <nl> ppp b / dbms / include / DB / Common / HyperLogLogWithSmallSetOptimization . h <nl> <nl> + # pragma once <nl> + <nl> + # include < statdaemons / HyperLogLogCounter . h > <nl> + # include < DB / Common / HashTable / SmallTable . h > <nl> + <nl> + namespace DB <nl> + { <nl> + <nl> + <nl> + / * * Для маленького количества ключей - массив фиксированного размера " на стеке " . <nl> + * Для большого - выделяется HyperLogLog . <nl> + * NOTE Возможно , имеет смысл сделать реализацию для среднего размера в виде хэш - таблицы . <nl> + * / <nl> + template < <nl> + typename Key , <nl> + UInt8 small_set_size , <nl> + UInt8 K , <nl> + typename Hash = IntHash32 < Key > , <nl> + typename DenominatorType = float > <nl> + class HyperLogLogWithSmallSetOptimization <nl> + { <nl> + private : <nl> + using Small = SmallSet < Key , small_set_size > ; <nl> + using Large = HyperLogLogCounter < K , Hash , DenominatorType > ; <nl> + <nl> + Small small ; <nl> + Large * large = nullptr ; <nl> + <nl> + bool isLarge ( ) const <nl> + { <nl> + return large ! = nullptr ; <nl> + } <nl> + <nl> + void toLarge ( ) <nl> + { <nl> + if ( current_memory_tracker ) <nl> + current_memory_tracker - > alloc ( sizeof ( large ) ) ; <nl> + <nl> + / / / На время копирования данных из tiny , устанавливать значение large ещё нельзя ( иначе оно перезатрёт часть данных ) . <nl> + Large * tmp_large = new Large ; <nl> + <nl> + for ( const auto & x : small ) <nl> + tmp_large - > insert ( x ) ; <nl> + <nl> + large = tmp_large ; <nl> + } <nl> + <nl> + public : <nl> + ~ HyperLogLogWithSmallSetOptimization ( ) <nl> + { <nl> + if ( isLarge ( ) ) <nl> + { <nl> + delete large ; <nl> + <nl> + if ( current_memory_tracker ) <nl> + current_memory_tracker - > free ( sizeof ( large ) ) ; <nl> + } <nl> + } <nl> + <nl> + void insert ( Key value ) <nl> + { <nl> + if ( ! isLarge ( ) ) <nl> + { <nl> + if ( small . find ( value ) = = small . end ( ) ) <nl> + { <nl> + if ( ! small . full ( ) ) <nl> + small . insert ( value ) ; <nl> + else <nl> + { <nl> + toLarge ( ) ; <nl> + large - > insert ( value ) ; <nl> + } <nl> + } <nl> + } <nl> + else <nl> + large - > insert ( value ) ; <nl> + } <nl> + <nl> + UInt32 size ( ) const <nl> + { <nl> + return ! isLarge ( ) ? small . size ( ) : large - > size ( ) ; <nl> + } <nl> + <nl> + void merge ( const HyperLogLogWithSmallSetOptimization & rhs ) <nl> + { <nl> + if ( rhs . isLarge ( ) ) <nl> + { <nl> + if ( ! isLarge ( ) ) <nl> + toLarge ( ) ; <nl> + <nl> + large - > merge ( * rhs . large ) ; <nl> + } <nl> + else <nl> + { <nl> + for ( const auto & x : rhs . small ) <nl> + insert ( x ) ; <nl> + } <nl> + } <nl> + <nl> + / / / Можно вызывать только для пустого объекта . <nl> + void read ( DB : : ReadBuffer & in ) <nl> + { <nl> + bool is_large ; <nl> + readBinary ( is_large , in ) ; <nl> + <nl> + if ( is_large ) <nl> + { <nl> + toLarge ( ) ; <nl> + large - > read ( in ) ; <nl> + } <nl> + else <nl> + small . read ( in ) ; <nl> + } <nl> + <nl> + void readAndMerge ( DB : : ReadBuffer & in ) <nl> + { <nl> + / / / Немного не оптимально . <nl> + HyperLogLogWithSmallSetOptimization other ; <nl> + other . read ( in ) ; <nl> + merge ( other ) ; <nl> + } <nl> + <nl> + void write ( DB : : WriteBuffer & out ) const <nl> + { <nl> + writeBinary ( isLarge ( ) , out ) ; <nl> + <nl> + if ( isLarge ( ) ) <nl> + large - > write ( out ) ; <nl> + else <nl> + small . write ( out ) ; <nl> + } <nl> + } ; <nl> + <nl> + <nl> + } <nl> mmm a / dbms / include / DB / Common / UInt128 . h <nl> ppp b / dbms / include / DB / Common / UInt128 . h <nl> struct UInt128TrivialHash <nl> inline void readBinary ( UInt128 & x , ReadBuffer & buf ) { readPODBinary ( x , buf ) ; } <nl> inline void writeBinary ( const UInt128 & x , WriteBuffer & buf ) { writePODBinary ( x , buf ) ; } <nl> <nl> + <nl> + / * * Используется при агрегации , для укладки большого количества ключей постоянной длины в хэш - таблицу . <nl> + * / <nl> + struct UInt256 <nl> + { <nl> + UInt64 a ; <nl> + UInt64 b ; <nl> + UInt64 c ; <nl> + UInt64 d ; <nl> + <nl> + bool operator = = ( const UInt256 rhs ) const <nl> + { <nl> + return a = = rhs . a & & b = = rhs . b & & c = = rhs . c & & d = = rhs . d ; <nl> + <nl> + / * Так получается не лучше . <nl> + return 0xFFFF = = _mm_movemask_epi8 ( _mm_and_si128 ( <nl> + _mm_cmpeq_epi8 ( <nl> + _mm_loadu_si128 ( reinterpret_cast < const __m128i * > ( & a ) ) , <nl> + _mm_loadu_si128 ( reinterpret_cast < const __m128i * > ( & rhs . a ) ) ) , <nl> + _mm_cmpeq_epi8 ( <nl> + _mm_loadu_si128 ( reinterpret_cast < const __m128i * > ( & c ) ) , <nl> + _mm_loadu_si128 ( reinterpret_cast < const __m128i * > ( & rhs . c ) ) ) ) ) ; * / <nl> + } <nl> + <nl> + bool operator ! = ( const UInt256 rhs ) const { return ! operator = = ( rhs ) ; } <nl> + <nl> + bool operator = = ( const UInt64 rhs ) const { return a = = rhs & & b = = 0 & & c = = 0 & & d = = 0 ; } <nl> + bool operator ! = ( const UInt64 rhs ) const { return ! operator = = ( rhs ) ; } <nl> + <nl> + UInt256 & operator = ( const UInt64 rhs ) { a = rhs ; b = 0 ; c = 0 ; d = 0 ; return * this ; } <nl> + } ; <nl> + <nl> + struct UInt256HashCRC32 <nl> + { <nl> + size_t operator ( ) ( UInt256 x ) const <nl> + { <nl> + UInt64 crc = - 1ULL ; <nl> + asm ( " crc32q % [ x ] , % [ crc ] \ n " : [ crc ] " + r " ( crc ) : [ x ] " rm " ( x . a ) ) ; <nl> + asm ( " crc32q % [ x ] , % [ crc ] \ n " : [ crc ] " + r " ( crc ) : [ x ] " rm " ( x . b ) ) ; <nl> + asm ( " crc32q % [ x ] , % [ crc ] \ n " : [ crc ] " + r " ( crc ) : [ x ] " rm " ( x . c ) ) ; <nl> + asm ( " crc32q % [ x ] , % [ crc ] \ n " : [ crc ] " + r " ( crc ) : [ x ] " rm " ( x . d ) ) ; <nl> + return crc ; <nl> + } <nl> + } ; <nl> + <nl> + inline void readBinary ( UInt256 & x , ReadBuffer & buf ) { readPODBinary ( x , buf ) ; } <nl> + inline void writeBinary ( const UInt256 & x , WriteBuffer & buf ) { writePODBinary ( x , buf ) ; } <nl> + <nl> } <nl> mmm a / dbms / include / DB / Core / Defines . h <nl> ppp b / dbms / include / DB / Core / Defines . h <nl> <nl> <nl> # define DEFAULT_MAX_QUERY_SIZE 65536 <nl> # define SHOW_CHARS_ON_SYNTAX_ERROR 160L <nl> - # define DEFAULT_MAX_THREADS 8 <nl> # define DEFAULT_MAX_DISTRIBUTED_CONNECTIONS 1024 <nl> # define DEFAULT_INTERACTIVE_DELAY 100000 <nl> # define DBMS_DEFAULT_DISTRIBUTED_CONNECTIONS_POOL_SIZE 1024 <nl> mmm a / dbms / include / DB / Core / ErrorCodes . h <nl> ppp b / dbms / include / DB / Core / ErrorCodes . h <nl> namespace ErrorCodes <nl> NO_AVAILABLE_REPLICA , <nl> MISMATCH_REPLICAS_DATA_SOURCES , <nl> STORAGE_DOESNT_SUPPORT_PARALLEL_REPLICAS , <nl> + CPUID_ERROR , <nl> <nl> POCO_EXCEPTION = 1000 , <nl> STD_EXCEPTION , <nl> mmm a / dbms / include / DB / DataStreams / AggregatingBlockInputStream . h <nl> ppp b / dbms / include / DB / DataStreams / AggregatingBlockInputStream . h <nl> class AggregatingBlockInputStream : public IProfilingBlockInputStream <nl> public : <nl> AggregatingBlockInputStream ( BlockInputStreamPtr input_ , const ColumnNumbers & keys_ , AggregateDescriptions & aggregates_ , <nl> bool overflow_row_ , bool final_ , size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , <nl> - Compiler * compiler_ , UInt32 min_count_to_compile_ ) <nl> - : aggregator ( keys_ , aggregates_ , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , compiler_ , min_count_to_compile_ ) , <nl> + Compiler * compiler_ , UInt32 min_count_to_compile_ , size_t group_by_two_level_threshold_ ) <nl> + : aggregator ( keys_ , aggregates_ , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , <nl> + compiler_ , min_count_to_compile_ , group_by_two_level_threshold_ ) , <nl> final ( final_ ) <nl> { <nl> children . push_back ( input_ ) ; <nl> class AggregatingBlockInputStream : public IProfilingBlockInputStream <nl> * / <nl> AggregatingBlockInputStream ( BlockInputStreamPtr input_ , const Names & key_names , const AggregateDescriptions & aggregates , <nl> bool overflow_row_ , bool final_ , size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , <nl> - Compiler * compiler_ , UInt32 min_count_to_compile_ ) <nl> - : aggregator ( key_names , aggregates , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , compiler_ , min_count_to_compile_ ) , <nl> + Compiler * compiler_ , UInt32 min_count_to_compile_ , size_t group_by_two_level_threshold_ ) <nl> + : aggregator ( key_names , aggregates , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , <nl> + compiler_ , min_count_to_compile_ , group_by_two_level_threshold_ ) , <nl> final ( final_ ) <nl> { <nl> children . push_back ( input_ ) ; <nl> mmm a / dbms / include / DB / DataStreams / MergingAggregatedBlockInputStream . h <nl> ppp b / dbms / include / DB / DataStreams / MergingAggregatedBlockInputStream . h <nl> class MergingAggregatedBlockInputStream : public IProfilingBlockInputStream <nl> public : <nl> MergingAggregatedBlockInputStream ( BlockInputStreamPtr input_ , const ColumnNumbers & keys_ , <nl> const AggregateDescriptions & aggregates_ , bool overflow_row_ , bool final_ , size_t max_threads_ ) <nl> - : aggregator ( keys_ , aggregates_ , overflow_row_ , 0 , OverflowMode : : THROW , nullptr , 0 ) , <nl> + : aggregator ( keys_ , aggregates_ , overflow_row_ , 0 , OverflowMode : : THROW , nullptr , 0 , 0 ) , <nl> final ( final_ ) , max_threads ( max_threads_ ) <nl> { <nl> children . push_back ( input_ ) ; <nl> class MergingAggregatedBlockInputStream : public IProfilingBlockInputStream <nl> <nl> MergingAggregatedBlockInputStream ( BlockInputStreamPtr input_ , const Names & keys_names_ , <nl> const AggregateDescriptions & aggregates_ , bool overflow_row_ , bool final_ , size_t max_threads_ ) <nl> - : aggregator ( keys_names_ , aggregates_ , overflow_row_ , 0 , OverflowMode : : THROW , nullptr , 0 ) , <nl> + : aggregator ( keys_names_ , aggregates_ , overflow_row_ , 0 , OverflowMode : : THROW , nullptr , 0 , 0 ) , <nl> final ( final_ ) , max_threads ( max_threads_ ) <nl> { <nl> children . push_back ( input_ ) ; <nl> mmm a / dbms / include / DB / DataStreams / ParallelAggregatingBlockInputStream . h <nl> ppp b / dbms / include / DB / DataStreams / ParallelAggregatingBlockInputStream . h <nl> class ParallelAggregatingBlockInputStream : public IProfilingBlockInputStream <nl> ParallelAggregatingBlockInputStream ( BlockInputStreams inputs , const ColumnNumbers & keys_ , <nl> AggregateDescriptions & aggregates_ , bool overflow_row_ , bool final_ , size_t max_threads_ , <nl> size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , <nl> - Compiler * compiler_ , UInt32 min_count_to_compile_ ) <nl> - : aggregator ( keys_ , aggregates_ , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , compiler_ , min_count_to_compile_ ) , <nl> + Compiler * compiler_ , UInt32 min_count_to_compile_ , size_t group_by_two_level_threshold_ ) <nl> + : aggregator ( keys_ , aggregates_ , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , <nl> + compiler_ , min_count_to_compile_ , group_by_two_level_threshold_ ) , <nl> final ( final_ ) , max_threads ( std : : min ( inputs . size ( ) , max_threads_ ) ) , <nl> keys_size ( keys_ . size ( ) ) , aggregates_size ( aggregates_ . size ( ) ) , <nl> handler ( * this ) , processor ( inputs , max_threads , handler ) <nl> class ParallelAggregatingBlockInputStream : public IProfilingBlockInputStream <nl> ParallelAggregatingBlockInputStream ( BlockInputStreams inputs , const Names & key_names , <nl> const AggregateDescriptions & aggregates , bool overflow_row_ , bool final_ , size_t max_threads_ , <nl> size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , <nl> - Compiler * compiler_ , UInt32 min_count_to_compile_ ) <nl> - : aggregator ( key_names , aggregates , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , compiler_ , min_count_to_compile_ ) , <nl> + Compiler * compiler_ , UInt32 min_count_to_compile_ , size_t group_by_two_level_threshold_ ) <nl> + : aggregator ( key_names , aggregates , overflow_row_ , max_rows_to_group_by_ , group_by_overflow_mode_ , <nl> + compiler_ , min_count_to_compile_ , group_by_two_level_threshold_ ) , <nl> final ( final_ ) , max_threads ( std : : min ( inputs . size ( ) , max_threads_ ) ) , <nl> keys_size ( key_names . size ( ) ) , aggregates_size ( aggregates . size ( ) ) , <nl> handler ( * this ) , processor ( inputs , max_threads , handler ) <nl> class ParallelAggregatingBlockInputStream : public IProfilingBlockInputStream <nl> { <nl> parent . aggregator . executeOnBlock ( block , * parent . many_data [ thread_num ] , <nl> parent . threads_data [ thread_num ] . key_columns , parent . threads_data [ thread_num ] . aggregate_columns , <nl> - parent . threads_data [ thread_num ] . key_sizes , parent . threads_data [ thread_num ] . key , parent . no_more_keys ) ; <nl> + parent . threads_data [ thread_num ] . key_sizes , parent . threads_data [ thread_num ] . key , <nl> + parent . no_more_keys ) ; <nl> <nl> parent . threads_data [ thread_num ] . src_rows + = block . rowsInFirstColumn ( ) ; <nl> parent . threads_data [ thread_num ] . src_bytes + = block . bytes ( ) ; <nl> mmm a / dbms / include / DB / DataStreams / RemoteBlockInputStream . h <nl> ppp b / dbms / include / DB / DataStreams / RemoteBlockInputStream . h <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> private : <nl> void init ( const Settings * settings_ ) <nl> { <nl> + sent_query . store ( false , std : : memory_order_seq_cst ) ; <nl> + finished . store ( false , std : : memory_order_seq_cst ) ; <nl> + got_exception_from_replica . store ( false , std : : memory_order_seq_cst ) ; <nl> + got_unknown_packet_from_replica . store ( false , std : : memory_order_seq_cst ) ; <nl> + was_cancelled . store ( false , std : : memory_order_seq_cst ) ; <nl> + <nl> if ( settings_ ) <nl> { <nl> send_settings = true ; <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> if ( ! __sync_bool_compare_and_swap ( & is_cancelled , false , true ) ) <nl> return ; <nl> <nl> - if ( isQueryInProgress ( ) & & ! hasThrownException ( ) ) <nl> + if ( hasNoQueryInProgress ( ) | | hasThrownException ( ) ) <nl> + return ; <nl> + <nl> + if ( tryCancel ( ) ) <nl> { <nl> std : : string addresses = parallel_replicas - > dumpAddresses ( ) ; <nl> LOG_TRACE ( log , " ( " + addresses + " ) Cancelling query " ) ; <nl> - <nl> - / / / Если запрошено прервать запрос - попросим удалённые реплики тоже прервать запрос . <nl> - was_cancelled = true ; <nl> - parallel_replicas - > sendCancel ( ) ; <nl> } <nl> } <nl> <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> * все соединения , затем читаем и пропускаем оставшиеся пакеты чтобы <nl> * эти соединения не остались висеть в рассихронизированном состоянии . <nl> * / <nl> - if ( isQueryInProgress ( ) ) <nl> + if ( established | | isQueryInProgress ( ) ) <nl> parallel_replicas - > disconnect ( ) ; <nl> } <nl> <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> <nl> Block readImpl ( ) override <nl> { <nl> - if ( ! sent_query ) <nl> + if ( ! sent_query . load ( std : : memory_order_seq_cst ) ) <nl> { <nl> createParallelReplicas ( ) ; <nl> + established = true ; <nl> parallel_replicas - > sendQuery ( query , " " , stage , true ) ; <nl> + established = false ; <nl> + sent_query . store ( true , std : : memory_order_seq_cst ) ; <nl> sendExternalTables ( ) ; <nl> - __sync_synchronize ( ) ; <nl> - sent_query = true ; <nl> } <nl> <nl> while ( true ) <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> break ; / / / Если блок пустой - получим другие пакеты до EndOfStream . <nl> <nl> case Protocol : : Server : : Exception : <nl> - got_exception_from_replica = true ; <nl> + got_exception_from_replica . store ( true , std : : memory_order_seq_cst ) ; <nl> packet . exception - > rethrow ( ) ; <nl> break ; <nl> <nl> case Protocol : : Server : : EndOfStream : <nl> if ( ! parallel_replicas - > hasActiveReplicas ( ) ) <nl> { <nl> - finished = true ; <nl> + finished . store ( true , std : : memory_order_seq_cst ) ; <nl> return Block ( ) ; <nl> } <nl> break ; <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> break ; <nl> <nl> default : <nl> - got_unknown_packet_from_replica = true ; <nl> + got_unknown_packet_from_replica . store ( true , std : : memory_order_seq_cst ) ; <nl> throw Exception ( " Unknown packet from server " , ErrorCodes : : UNKNOWN_PACKET_FROM_SERVER ) ; <nl> } <nl> } <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> * / <nl> <nl> / / / Отправим просьбу прервать выполнение запроса , если ещё не отправляли . <nl> - if ( ! was_cancelled ) <nl> + if ( tryCancel ( ) ) <nl> { <nl> std : : string addresses = parallel_replicas - > dumpAddresses ( ) ; <nl> LOG_TRACE ( log , " ( " + addresses + " ) Cancelling query because enough data has been read " ) ; <nl> - <nl> - was_cancelled = true ; <nl> - parallel_replicas - > sendCancel ( ) ; <nl> } <nl> <nl> / / / Получим оставшиеся пакеты , чтобы не было рассинхронизации в соединениях с репликами . <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> switch ( packet . type ) <nl> { <nl> case Protocol : : Server : : EndOfStream : <nl> - finished = true ; <nl> + finished . store ( true , std : : memory_order_seq_cst ) ; <nl> break ; <nl> <nl> case Protocol : : Server : : Exception : <nl> - got_exception_from_replica = true ; <nl> + got_exception_from_replica . store ( true , std : : memory_order_seq_cst ) ; <nl> packet . exception - > rethrow ( ) ; <nl> break ; <nl> <nl> default : <nl> - got_unknown_packet_from_replica = true ; <nl> + got_unknown_packet_from_replica . store ( true , std : : memory_order_seq_cst ) ; <nl> throw Exception ( " Unknown packet from server " , ErrorCodes : : UNKNOWN_PACKET_FROM_SERVER ) ; <nl> } <nl> } <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> / / / Возвращает true , если запрос отправлен , а ещё не выполнен . <nl> bool isQueryInProgress ( ) const <nl> { <nl> - return sent_query & & ! finished & & ! was_cancelled ; <nl> + return sent_query . load ( std : : memory_order_seq_cst ) & & ! finished . load ( std : : memory_order_seq_cst ) & & ! was_cancelled . load ( std : : memory_order_seq_cst ) ; <nl> } <nl> <nl> / / / Возвращает true , если никакой запрос не отправлен или один запрос уже выполнен . <nl> bool hasNoQueryInProgress ( ) const <nl> { <nl> - return ! sent_query | | finished ; <nl> + return ! sent_query . load ( std : : memory_order_seq_cst ) | | finished . load ( std : : memory_order_seq_cst ) ; <nl> } <nl> <nl> / / / Возвращает true , если исключение было выкинуто . <nl> bool hasThrownException ( ) const <nl> { <nl> - return got_exception_from_replica | | got_unknown_packet_from_replica ; <nl> + return got_exception_from_replica . load ( std : : memory_order_seq_cst ) | | got_unknown_packet_from_replica . load ( std : : memory_order_seq_cst ) ; <nl> + } <nl> + <nl> + private : <nl> + / / / ITable : : read requires a Context , therefore we should create one if the user can ' t supply it <nl> + static Context & getDefaultContext ( ) <nl> + { <nl> + static Context instance ; <nl> + return instance ; <nl> + } <nl> + <nl> + / / / Отправить запрос на отмену всех соединений к репликам , если такой запрос ещё не был отправлен . <nl> + bool tryCancel ( ) <nl> + { <nl> + bool old_val = false ; <nl> + bool new_val = true ; <nl> + if ( was_cancelled . compare_exchange_strong ( old_val , new_val , std : : memory_order_seq_cst , std : : memory_order_relaxed ) ) <nl> + { <nl> + parallel_replicas - > sendCancel ( ) ; <nl> + return true ; <nl> + } <nl> + else <nl> + return false ; <nl> } <nl> <nl> private : <nl> class RemoteBlockInputStream : public IProfilingBlockInputStream <nl> QueryProcessingStage : : Enum stage ; <nl> Context context ; <nl> <nl> + / / / Установили соединения с репликами , но ещё не отправили запрос . <nl> + volatile bool established = false ; <nl> + <nl> / / / Отправили запрос ( это делается перед получением первого блока ) . <nl> - bool sent_query = false ; <nl> + std : : atomic < bool > sent_query ; <nl> <nl> / * * Получили все данные от всех реплик , до пакета EndOfStream . <nl> * Если при уничтожении объекта , ещё не все данные считаны , <nl> * то для того , чтобы не было рассинхронизации , на реплики отправляются просьбы прервать выполнение запроса , <nl> * и после этого считываются все пакеты до EndOfStream . <nl> * / <nl> - bool finished = false ; <nl> + std : : atomic < bool > finished ; <nl> <nl> / * * На каждую реплику была отправлена просьба прервать выполнение запроса , так как данные больше не нужны . <nl> * Это может быть из - за того , что данных достаточно ( например , при использовании LIMIT ) , <nl> * или если на стороне клиента произошло исключение . <nl> * / <nl> - bool was_cancelled = false ; <nl> + std : : atomic < bool > was_cancelled ; <nl> <nl> / * * С одной репилки было получено исключение . В этом случае получать больше пакетов или <nl> * просить прервать запрос на этой реплике не нужно . <nl> * / <nl> - bool got_exception_from_replica = false ; <nl> + std : : atomic < bool > got_exception_from_replica ; <nl> <nl> / * * С одной реплики был получен неизвестный пакет . В этом случае получать больше пакетов или <nl> * просить прервать запрос на этой реплике не нужно . <nl> * / <nl> - bool got_unknown_packet_from_replica = false ; <nl> + std : : atomic < bool > got_unknown_packet_from_replica ; <nl> <nl> Logger * log = & Logger : : get ( " RemoteBlockInputStream " ) ; <nl> - <nl> - / / / ITable : : read requires a Context , therefore we should create one if the user can ' t supply it <nl> - static Context & getDefaultContext ( ) <nl> - { <nl> - static Context instance ; <nl> - return instance ; <nl> - } <nl> } ; <nl> <nl> } <nl> mmm a / dbms / include / DB / Functions / FunctionsArray . h <nl> ppp b / dbms / include / DB / Functions / FunctionsArray . h <nl> class FunctionArrayEnumerateUniq : public IFunction <nl> size_t off = offsets [ i ] ; <nl> for ( size_t j = prev_off ; j < off ; + + j ) <nl> { <nl> - res_values [ j ] = + + indices [ pack128 ( j , count , columns , key_sizes ) ] ; <nl> + res_values [ j ] = + + indices [ packFixed < UInt128 > ( j , count , columns , key_sizes ) ] ; <nl> } <nl> prev_off = off ; <nl> } <nl> mmm a / dbms / include / DB / Interpreters / AggregationCommon . h <nl> ppp b / dbms / include / DB / Interpreters / AggregationCommon . h <nl> <nl> # include < DB / Core / Defines . h > <nl> # include < DB / Core / StringRef . h > <nl> # include < DB / Columns / IColumn . h > <nl> + # include < DB / Columns / ColumnsNumber . h > <nl> + # include < DB / Columns / ColumnFixedString . h > <nl> <nl> <nl> template < > <nl> namespace DB <nl> typedef std : : vector < size_t > Sizes ; <nl> <nl> <nl> - / / / Записать набор ключей фиксированной длины в UInt128 , уложив их подряд ( при допущении , что они помещаются ) . <nl> - static inline UInt128 ALWAYS_INLINE pack128 ( <nl> + / / / Записать набор ключей фиксированной длины в T , уложив их подряд ( при допущении , что они помещаются ) . <nl> + template < typename T > <nl> + static inline T ALWAYS_INLINE packFixed ( <nl> size_t i , size_t keys_size , const ConstColumnPlainPtrs & key_columns , const Sizes & key_sizes ) <nl> { <nl> union <nl> { <nl> - UInt128 key ; <nl> - char bytes [ 16 ] ; <nl> + T key ; <nl> + char bytes [ sizeof ( key ) ] ; <nl> } ; <nl> <nl> - memset ( bytes , 0 , 16 ) ; <nl> + memset ( bytes , 0 , sizeof ( key ) ) ; <nl> size_t offset = 0 ; <nl> for ( size_t j = 0 ; j < keys_size ; + + j ) <nl> { <nl> - StringRef key_data = key_columns [ j ] - > getDataAt ( i ) ; <nl> - memcpy ( bytes + offset , key_data . data , key_sizes [ j ] ) ; <nl> - offset + = key_sizes [ j ] ; <nl> + switch ( key_sizes [ j ] ) <nl> + { <nl> + case 1 : <nl> + memcpy ( bytes + offset , & static_cast < const ColumnUInt8 * > ( key_columns [ j ] ) - > getData ( ) [ i ] , 1 ) ; <nl> + offset + = 1 ; <nl> + break ; <nl> + case 2 : <nl> + memcpy ( bytes + offset , & static_cast < const ColumnUInt16 * > ( key_columns [ j ] ) - > getData ( ) [ i ] , 2 ) ; <nl> + offset + = 2 ; <nl> + break ; <nl> + case 4 : <nl> + memcpy ( bytes + offset , & static_cast < const ColumnUInt32 * > ( key_columns [ j ] ) - > getData ( ) [ i ] , 4 ) ; <nl> + offset + = 4 ; <nl> + break ; <nl> + case 8 : <nl> + memcpy ( bytes + offset , & static_cast < const ColumnUInt64 * > ( key_columns [ j ] ) - > getData ( ) [ i ] , 8 ) ; <nl> + offset + = 8 ; <nl> + break ; <nl> + default : <nl> + memcpy ( bytes + offset , & static_cast < const ColumnFixedString * > ( key_columns [ j ] ) - > getChars ( ) [ i * key_sizes [ j ] ] , key_sizes [ j ] ) ; <nl> + offset + = key_sizes [ j ] ; <nl> + } <nl> } <nl> <nl> return key ; <nl> static inline StringRef * ALWAYS_INLINE extractKeysAndPlaceInPool ( <nl> } <nl> <nl> <nl> + / * * Скопировать ключи в пул в непрерывный кусок памяти . <nl> + * Потом разместить в пуле StringRef - ы на них . <nl> + * <nl> + * [ key1 ] [ key2 ] . . . [ keyN ] [ ref1 ] [ ref2 ] . . . [ refN ] <nl> + * ^ mmmmmmmmmmmmmmmmmmmmm | | <nl> + * ^ mmmmmmmmmmmmmmmmmmmmm | <nl> + * ^ mmmreturn - valuemmm - ^ <nl> + * <nl> + * Вернуть StringRef на кусок памяти с ключами ( без учёта StringRef - ов после них ) . <nl> + * / <nl> + static inline StringRef ALWAYS_INLINE extractKeysAndPlaceInPoolContiguous ( <nl> + size_t i , size_t keys_size , const ConstColumnPlainPtrs & key_columns , StringRefs & keys , Arena & pool ) <nl> + { <nl> + size_t sum_keys_size = 0 ; <nl> + for ( size_t j = 0 ; j < keys_size ; + + j ) <nl> + { <nl> + keys [ j ] = key_columns [ j ] - > getDataAtWithTerminatingZero ( i ) ; <nl> + sum_keys_size + = keys [ j ] . size ; <nl> + } <nl> + <nl> + char * res = pool . alloc ( sum_keys_size + keys_size * sizeof ( StringRef ) ) ; <nl> + char * place = res ; <nl> + <nl> + for ( size_t j = 0 ; j < keys_size ; + + j ) <nl> + { <nl> + memcpy ( place , keys [ j ] . data , keys [ j ] . size ) ; <nl> + keys [ j ] . data = place ; <nl> + place + = keys [ j ] . size ; <nl> + } <nl> + <nl> + / / / Размещаем в пуле StringRef - ы на только что скопированные ключи . <nl> + memcpy ( place , & keys [ 0 ] , keys_size * sizeof ( StringRef ) ) ; <nl> + <nl> + return { res , sum_keys_size } ; <nl> + } <nl> + <nl> + <nl> } <nl> mmm a / dbms / include / DB / Interpreters / Aggregator . h <nl> ppp b / dbms / include / DB / Interpreters / Aggregator . h <nl> typedef AggregateDataPtr AggregatedDataWithoutKey ; <nl> typedef HashMap < UInt64 , AggregateDataPtr , HashCRC32 < UInt64 > > AggregatedDataWithUInt64Key ; <nl> typedef HashMapWithSavedHash < StringRef , AggregateDataPtr > AggregatedDataWithStringKey ; <nl> typedef HashMap < UInt128 , AggregateDataPtr , UInt128HashCRC32 > AggregatedDataWithKeys128 ; <nl> + typedef HashMap < UInt256 , AggregateDataPtr , UInt256HashCRC32 > AggregatedDataWithKeys256 ; <nl> typedef HashMap < UInt128 , std : : pair < StringRef * , AggregateDataPtr > , UInt128TrivialHash > AggregatedDataHashed ; <nl> <nl> typedef TwoLevelHashMap < UInt64 , AggregateDataPtr , HashCRC32 < UInt64 > > AggregatedDataWithUInt64KeyTwoLevel ; <nl> typedef TwoLevelHashMapWithSavedHash < StringRef , AggregateDataPtr > AggregatedDataWithStringKeyTwoLevel ; <nl> typedef TwoLevelHashMap < UInt128 , AggregateDataPtr , UInt128HashCRC32 > AggregatedDataWithKeys128TwoLevel ; <nl> + typedef TwoLevelHashMap < UInt256 , AggregateDataPtr , UInt256HashCRC32 > AggregatedDataWithKeys256TwoLevel ; <nl> typedef TwoLevelHashMap < UInt128 , std : : pair < StringRef * , AggregateDataPtr > , UInt128TrivialHash > AggregatedDataHashedTwoLevel ; <nl> <nl> typedef HashMap < UInt64 , AggregateDataPtr , TrivialHash , HashTableFixedGrower < 8 > > AggregatedDataWithUInt8Key ; <nl> struct AggregationMethodOneNumber <nl> size_t keys_size , / / / Количество ключевых столбцов . <nl> size_t i , / / / Из какой строки блока достать ключ . <nl> const Sizes & key_sizes , / / / Если ключи фиксированной длины - их длины . Не используется в методах агрегации по ключам переменной длины . <nl> - StringRefs & keys ) const / / / Сюда могут быть записаны ссылки на данные ключей в столбцах . Они могут быть использованы в дальнейшем . <nl> + StringRefs & keys , / / / Сюда могут быть записаны ссылки на данные ключей в столбцах . Они могут быть использованы в дальнейшем . <nl> + Arena & pool ) const <nl> { <nl> return unionCastToUInt64 ( vec [ i ] ) ; <nl> } <nl> struct AggregationMethodOneNumber <nl> { <nl> } <nl> <nl> + / * * Действие , которое нужно сделать , если ключ не новый . Например , откатить выделение памяти в пуле . <nl> + * / <nl> + static void onExistingKey ( const Key & key , StringRefs & keys , Arena & pool ) { } <nl> + <nl> + / * * Не использовать оптимизацию для идущих подряд ключей . <nl> + * / <nl> + static const bool no_consecutive_keys_optimization = false ; <nl> + <nl> / * * Вставить ключ из хэш - таблицы в столбцы . <nl> * / <nl> static void insertKeyIntoColumns ( const typename Data : : value_type & value , ColumnPlainPtrs & key_columns , size_t keys_size , const Sizes & key_sizes ) <nl> struct AggregationMethodString <nl> size_t keys_size , <nl> size_t i , <nl> const Sizes & key_sizes , <nl> - StringRefs & keys ) const <nl> + StringRefs & keys , <nl> + Arena & pool ) const <nl> { <nl> return StringRef ( <nl> & ( * chars ) [ i = = 0 ? 0 : ( * offsets ) [ i - 1 ] ] , <nl> struct AggregationMethodString <nl> value . first . data = pool . insert ( value . first . data , value . first . size ) ; <nl> } <nl> <nl> + static void onExistingKey ( const Key & key , StringRefs & keys , Arena & pool ) { } <nl> + <nl> + static const bool no_consecutive_keys_optimization = false ; <nl> + <nl> static void insertKeyIntoColumns ( const typename Data : : value_type & value , ColumnPlainPtrs & key_columns , size_t keys_size , const Sizes & key_sizes ) <nl> { <nl> key_columns [ 0 ] - > insertData ( value . first . data , value . first . size ) ; <nl> struct AggregationMethodFixedString <nl> size_t keys_size , <nl> size_t i , <nl> const Sizes & key_sizes , <nl> - StringRefs & keys ) const <nl> + StringRefs & keys , <nl> + Arena & pool ) const <nl> { <nl> return StringRef ( & ( * chars ) [ i * n ] , n ) ; <nl> } <nl> struct AggregationMethodFixedString <nl> value . first . data = pool . insert ( value . first . data , value . first . size ) ; <nl> } <nl> <nl> + static void onExistingKey ( const Key & key , StringRefs & keys , Arena & pool ) { } <nl> + <nl> + static const bool no_consecutive_keys_optimization = false ; <nl> + <nl> static void insertKeyIntoColumns ( const typename Data : : value_type & value , ColumnPlainPtrs & key_columns , size_t keys_size , const Sizes & key_sizes ) <nl> { <nl> key_columns [ 0 ] - > insertData ( value . first . data , value . first . size ) ; <nl> struct AggregationMethodFixedString <nl> } ; <nl> <nl> <nl> - / / / Для случая , когда все ключи фиксированной длины , и они помещаются в 128 бит . <nl> + / / / Для случая , когда все ключи фиксированной длины , и они помещаются в N ( например , 128 ) бит . <nl> template < typename TData > <nl> - struct AggregationMethodKeys128 <nl> + struct AggregationMethodKeysFixed <nl> { <nl> typedef TData Data ; <nl> typedef typename Data : : key_type Key ; <nl> struct AggregationMethodKeys128 <nl> <nl> Data data ; <nl> <nl> - AggregationMethodKeys128 ( ) { } <nl> + AggregationMethodKeysFixed ( ) { } <nl> <nl> template < typename Other > <nl> - AggregationMethodKeys128 ( const Other & other ) : data ( other . data ) { } <nl> + AggregationMethodKeysFixed ( const Other & other ) : data ( other . data ) { } <nl> <nl> struct State <nl> { <nl> struct AggregationMethodKeys128 <nl> size_t keys_size , <nl> size_t i , <nl> const Sizes & key_sizes , <nl> - StringRefs & keys ) const <nl> + StringRefs & keys , <nl> + Arena & pool ) const <nl> { <nl> - return pack128 ( i , keys_size , key_columns , key_sizes ) ; <nl> + return packFixed < Key > ( i , keys_size , key_columns , key_sizes ) ; <nl> } <nl> } ; <nl> <nl> struct AggregationMethodKeys128 <nl> { <nl> } <nl> <nl> + static void onExistingKey ( const Key & key , StringRefs & keys , Arena & pool ) { } <nl> + <nl> + static const bool no_consecutive_keys_optimization = false ; <nl> + <nl> static void insertKeyIntoColumns ( const typename Data : : value_type & value , ColumnPlainPtrs & key_columns , size_t keys_size , const Sizes & key_sizes ) <nl> { <nl> size_t offset = 0 ; <nl> struct AggregationMethodKeys128 <nl> } ; <nl> <nl> <nl> + / / / Для остальных случаев . Агрегирует по конкатенации ключей . ( При этом , строки , содержащие нули посередине , могут склеиться . ) <nl> + template < typename TData > <nl> + struct AggregationMethodConcat <nl> + { <nl> + typedef TData Data ; <nl> + typedef typename Data : : key_type Key ; <nl> + typedef typename Data : : mapped_type Mapped ; <nl> + typedef typename Data : : iterator iterator ; <nl> + typedef typename Data : : const_iterator const_iterator ; <nl> + <nl> + Data data ; <nl> + <nl> + AggregationMethodConcat ( ) { } <nl> + <nl> + template < typename Other > <nl> + AggregationMethodConcat ( const Other & other ) : data ( other . data ) { } <nl> + <nl> + struct State <nl> + { <nl> + void init ( ConstColumnPlainPtrs & key_columns ) <nl> + { <nl> + } <nl> + <nl> + Key getKey ( <nl> + const ConstColumnPlainPtrs & key_columns , <nl> + size_t keys_size , <nl> + size_t i , <nl> + const Sizes & key_sizes , <nl> + StringRefs & keys , <nl> + Arena & pool ) const <nl> + { <nl> + return extractKeysAndPlaceInPoolContiguous ( i , keys_size , key_columns , keys , pool ) ; <nl> + } <nl> + } ; <nl> + <nl> + static AggregateDataPtr & getAggregateData ( Mapped & value ) { return value ; } <nl> + static const AggregateDataPtr & getAggregateData ( const Mapped & value ) { return value ; } <nl> + <nl> + static void onNewKey ( typename Data : : value_type & value , size_t keys_size , size_t i , StringRefs & keys , Arena & pool ) <nl> + { <nl> + } <nl> + <nl> + static void onExistingKey ( const Key & key , StringRefs & keys , Arena & pool ) <nl> + { <nl> + pool . rollback ( key . size + keys . size ( ) * sizeof ( keys [ 0 ] ) ) ; <nl> + } <nl> + <nl> + / / / Если ключ уже был , то он удаляется из пула ( затирается ) , и сравнить с ним следующий ключ уже нельзя . <nl> + static const bool no_consecutive_keys_optimization = true ; <nl> + <nl> + static void insertKeyIntoColumns ( const typename Data : : value_type & value , ColumnPlainPtrs & key_columns , size_t keys_size , const Sizes & key_sizes ) <nl> + { <nl> + / / / См . функцию extractKeysAndPlaceInPoolContiguous . <nl> + const StringRef * key_refs = reinterpret_cast < const StringRef * > ( value . first . data + value . first . size ) ; <nl> + <nl> + for ( size_t i = 0 ; i < keys_size ; + + i ) <nl> + key_columns [ i ] - > insertDataWithTerminatingZero ( key_refs [ i ] . data , key_refs [ i ] . size ) ; <nl> + } <nl> + } ; <nl> + <nl> + <nl> / / / Для остальных случаев . Агрегирует по 128 битному хэшу от ключа . ( При этом , строки , содержащие нули посередине , могут склеиться . ) <nl> template < typename TData > <nl> struct AggregationMethodHashed <nl> struct AggregationMethodHashed <nl> size_t keys_size , <nl> size_t i , <nl> const Sizes & key_sizes , <nl> - StringRefs & keys ) const <nl> + StringRefs & keys , <nl> + Arena & pool ) const <nl> { <nl> return hash128 ( i , keys_size , key_columns , keys ) ; <nl> } <nl> struct AggregationMethodHashed <nl> value . second . first = placeKeysInPool ( i , keys_size , keys , pool ) ; <nl> } <nl> <nl> + static void onExistingKey ( const Key & key , StringRefs & keys , Arena & pool ) { } <nl> + <nl> + static const bool no_consecutive_keys_optimization = false ; <nl> + <nl> static void insertKeyIntoColumns ( const typename Data : : value_type & value , ColumnPlainPtrs & key_columns , size_t keys_size , const Sizes & key_sizes ) <nl> { <nl> for ( size_t i = 0 ; i < keys_size ; + + i ) <nl> struct AggregatedDataVariants : private boost : : noncopyable <nl> std : : unique_ptr < AggregationMethodOneNumber < UInt64 , AggregatedDataWithUInt64Key > > key64 ; <nl> std : : unique_ptr < AggregationMethodString < AggregatedDataWithStringKey > > key_string ; <nl> std : : unique_ptr < AggregationMethodFixedString < AggregatedDataWithStringKey > > key_fixed_string ; <nl> - std : : unique_ptr < AggregationMethodKeys128 < AggregatedDataWithKeys128 > > keys128 ; <nl> + std : : unique_ptr < AggregationMethodKeysFixed < AggregatedDataWithKeys128 > > keys128 ; <nl> + std : : unique_ptr < AggregationMethodKeysFixed < AggregatedDataWithKeys256 > > keys256 ; <nl> std : : unique_ptr < AggregationMethodHashed < AggregatedDataHashed > > hashed ; <nl> + std : : unique_ptr < AggregationMethodConcat < AggregatedDataWithStringKey > > concat ; <nl> <nl> std : : unique_ptr < AggregationMethodOneNumber < UInt32 , AggregatedDataWithUInt64KeyTwoLevel > > key32_two_level ; <nl> std : : unique_ptr < AggregationMethodOneNumber < UInt64 , AggregatedDataWithUInt64KeyTwoLevel > > key64_two_level ; <nl> std : : unique_ptr < AggregationMethodString < AggregatedDataWithStringKeyTwoLevel > > key_string_two_level ; <nl> std : : unique_ptr < AggregationMethodFixedString < AggregatedDataWithStringKeyTwoLevel > > key_fixed_string_two_level ; <nl> - std : : unique_ptr < AggregationMethodKeys128 < AggregatedDataWithKeys128TwoLevel > > keys128_two_level ; <nl> + std : : unique_ptr < AggregationMethodKeysFixed < AggregatedDataWithKeys128TwoLevel > > keys128_two_level ; <nl> + std : : unique_ptr < AggregationMethodKeysFixed < AggregatedDataWithKeys256TwoLevel > > keys256_two_level ; <nl> std : : unique_ptr < AggregationMethodHashed < AggregatedDataHashedTwoLevel > > hashed_two_level ; <nl> + std : : unique_ptr < AggregationMethodConcat < AggregatedDataWithStringKeyTwoLevel > > concat_two_level ; <nl> <nl> / / / В этом и подобных макросах , вариант without_key не учитывается . <nl> # define APPLY_FOR_AGGREGATED_VARIANTS ( M ) \ <nl> struct AggregatedDataVariants : private boost : : noncopyable <nl> M ( key_string , false ) \ <nl> M ( key_fixed_string , false ) \ <nl> M ( keys128 , false ) \ <nl> + M ( keys256 , false ) \ <nl> M ( hashed , false ) \ <nl> + M ( concat , false ) \ <nl> M ( key32_two_level , true ) \ <nl> M ( key64_two_level , true ) \ <nl> M ( key_string_two_level , true ) \ <nl> M ( key_fixed_string_two_level , true ) \ <nl> M ( keys128_two_level , true ) \ <nl> - M ( hashed_two_level , true ) <nl> + M ( keys256_two_level , true ) \ <nl> + M ( hashed_two_level , true ) \ <nl> + M ( concat_two_level , true ) <nl> <nl> enum class Type <nl> { <nl> struct AggregatedDataVariants : private boost : : noncopyable <nl> M ( key_string ) \ <nl> M ( key_fixed_string ) \ <nl> M ( keys128 ) \ <nl> - M ( hashed ) <nl> + M ( keys256 ) \ <nl> + M ( hashed ) \ <nl> + M ( concat ) <nl> <nl> # define APPLY_FOR_VARIANTS_NOT_CONVERTIBLE_TO_TWO_LEVEL ( M ) \ <nl> M ( key8 ) \ <nl> struct AggregatedDataVariants : private boost : : noncopyable <nl> M ( key_string_two_level ) \ <nl> M ( key_fixed_string_two_level ) \ <nl> M ( keys128_two_level ) \ <nl> - M ( hashed_two_level ) <nl> + M ( keys256_two_level ) \ <nl> + M ( hashed_two_level ) \ <nl> + M ( concat_two_level ) <nl> } ; <nl> <nl> typedef SharedPtr < AggregatedDataVariants > AggregatedDataVariantsPtr ; <nl> class Aggregator <nl> { <nl> public : <nl> Aggregator ( const ColumnNumbers & keys_ , const AggregateDescriptions & aggregates_ , bool overflow_row_ , <nl> - size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , Compiler * compiler_ , UInt32 min_count_to_compile_ ) <nl> + size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , Compiler * compiler_ , UInt32 min_count_to_compile_ , <nl> + size_t group_by_two_level_threshold_ ) <nl> : keys ( keys_ ) , aggregates ( aggregates_ ) , aggregates_size ( aggregates . size ( ) ) , <nl> overflow_row ( overflow_row_ ) , <nl> max_rows_to_group_by ( max_rows_to_group_by_ ) , group_by_overflow_mode ( group_by_overflow_mode_ ) , <nl> - compiler ( compiler_ ) , min_count_to_compile ( min_count_to_compile_ ) <nl> + compiler ( compiler_ ) , min_count_to_compile ( min_count_to_compile_ ) , group_by_two_level_threshold ( group_by_two_level_threshold_ ) <nl> { <nl> std : : sort ( keys . begin ( ) , keys . end ( ) ) ; <nl> keys . erase ( std : : unique ( keys . begin ( ) , keys . end ( ) ) , keys . end ( ) ) ; <nl> class Aggregator <nl> } <nl> <nl> Aggregator ( const Names & key_names_ , const AggregateDescriptions & aggregates_ , bool overflow_row_ , <nl> - size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , Compiler * compiler_ , UInt32 min_count_to_compile_ ) <nl> + size_t max_rows_to_group_by_ , OverflowMode group_by_overflow_mode_ , Compiler * compiler_ , UInt32 min_count_to_compile_ , <nl> + size_t group_by_two_level_threshold_ ) <nl> : key_names ( key_names_ ) , aggregates ( aggregates_ ) , aggregates_size ( aggregates . size ( ) ) , <nl> overflow_row ( overflow_row_ ) , <nl> max_rows_to_group_by ( max_rows_to_group_by_ ) , group_by_overflow_mode ( group_by_overflow_mode_ ) , <nl> - compiler ( compiler_ ) , min_count_to_compile ( min_count_to_compile_ ) <nl> + compiler ( compiler_ ) , min_count_to_compile ( min_count_to_compile_ ) , group_by_two_level_threshold ( group_by_two_level_threshold_ ) <nl> { <nl> std : : sort ( key_names . begin ( ) , key_names . end ( ) ) ; <nl> key_names . erase ( std : : unique ( key_names . begin ( ) , key_names . end ( ) ) , key_names . end ( ) ) ; <nl> class Aggregator <nl> bool compiled_if_possible = false ; <nl> void compileIfPossible ( AggregatedDataVariants : : Type type ) ; <nl> <nl> + / * * При каком количестве ключей , начинает использоваться двухуровневая агрегация . <nl> + * 0 - никогда не использовать . <nl> + * / <nl> + size_t group_by_two_level_threshold ; <nl> <nl> / * * Если заданы только имена столбцов ( key_names , а также aggregates [ i ] . column_name ) , то вычислить номера столбцов . <nl> * Сформировать блок - пример результата . <nl> mmm a / dbms / include / DB / Interpreters / Settings . h <nl> ppp b / dbms / include / DB / Interpreters / Settings . h <nl> struct Settings <nl> M ( SettingUInt64 , max_block_size , DEFAULT_BLOCK_SIZE ) \ <nl> / * * Максимальный размер блока для вставки , если мы управляем формированием блоков для вставки . * / \ <nl> M ( SettingUInt64 , max_insert_block_size , DEFAULT_INSERT_BLOCK_SIZE ) \ <nl> - / * * Максимальное количество потоков выполнения запроса * / \ <nl> - M ( SettingUInt64 , max_threads , DEFAULT_MAX_THREADS ) \ <nl> + / * * Максимальное количество потоков выполнения запроса . По - умолчанию - определять автоматически . * / \ <nl> + M ( SettingMaxThreads , max_threads , 0 ) \ <nl> / * * Максимальное количество соединений при распределённой обработке одного запроса ( должно быть больше , чем max_threads ) . * / \ <nl> M ( SettingUInt64 , max_distributed_connections , DEFAULT_MAX_DISTRIBUTED_CONNECTIONS ) \ <nl> / * * Какую часть запроса можно прочитать в оперативку для парсинга ( оставшиеся данные для INSERT , если есть , считываются позже ) * / \ <nl> struct Settings <nl> M ( SettingBool , compile , false ) \ <nl> / * * Количество одинаковых по структуре запросов перед тем , как инициируется их компиляция . * / \ <nl> M ( SettingUInt64 , min_count_to_compile , 0 ) \ <nl> + / * * При каком количестве ключей , начинает использоваться двухуровневая агрегация . 0 - никогда не использовать . * / \ <nl> + M ( SettingUInt64 , group_by_two_level_threshold , 30000 ) \ <nl> \ <nl> / * * Максимальное количество используемых реплик каждого шарда при выполнении запроса * / \ <nl> M ( SettingUInt64 , max_parallel_replicas , 1 ) \ <nl> struct Settings <nl> M ( SettingUInt64 , merge_tree_max_rows_to_use_cache , ( 1024 * 1024 ) ) \ <nl> \ <nl> / * * Минимальная длина выражения expr = x1 OR . . . expr = xN для оптимизации * / \ <nl> - M ( SettingUInt64 , min_or_chain_length_for_optimization , 6 ) \ <nl> + M ( SettingUInt64 , optimize_min_equality_disjunction_chain_length , 4 ) \ <nl> <nl> / / / Всевозможные ограничения на выполнение запроса . <nl> Limits limits ; <nl> mmm a / dbms / include / DB / Interpreters / SettingsCommon . h <nl> ppp b / dbms / include / DB / Interpreters / SettingsCommon . h <nl> <nl> # include < DB / Core / Field . h > <nl> # include < DB / IO / WriteHelpers . h > <nl> # include < Poco / Timespan . h > <nl> + # include < cpuid / libcpuid . h > <nl> <nl> <nl> namespace DB <nl> struct SettingUInt64 <nl> typedef SettingUInt64 SettingBool ; <nl> <nl> <nl> + / * * В отличие от SettingUInt64 , поддерживает значение ' auto ' - количество процессорных ядер без учёта SMT . <nl> + * Значение 0 так же воспринимается как auto . <nl> + * При сериализации , auto записывается так же , как 0 . <nl> + * / <nl> + struct SettingMaxThreads <nl> + { <nl> + UInt64 value ; <nl> + bool is_auto ; <nl> + bool changed = false ; <nl> + <nl> + SettingMaxThreads ( UInt64 x = 0 ) : value ( x ? x : getAutoValue ( ) ) , is_auto ( x = = 0 ) { } <nl> + <nl> + operator UInt64 ( ) const { return value ; } <nl> + SettingMaxThreads & operator = ( UInt64 x ) { set ( x ) ; return * this ; } <nl> + <nl> + String toString ( ) const <nl> + { <nl> + / / / Вместо значения auto выводим актуальное значение , чтобы его было легче посмотреть . <nl> + return DB : : toString ( value ) ; <nl> + } <nl> + <nl> + void set ( UInt64 x ) <nl> + { <nl> + value = x ? x : getAutoValue ( ) ; <nl> + is_auto = x = = 0 ; <nl> + changed = true ; <nl> + } <nl> + <nl> + void set ( const Field & x ) <nl> + { <nl> + if ( x . getType ( ) = = Field : : Types : : String ) <nl> + set ( safeGet < const String & > ( x ) ) ; <nl> + else <nl> + set ( safeGet < UInt64 > ( x ) ) ; <nl> + } <nl> + <nl> + void set ( const String & x ) <nl> + { <nl> + if ( x = = " auto " ) <nl> + setAuto ( ) ; <nl> + else <nl> + set ( parse < UInt64 > ( x ) ) ; <nl> + } <nl> + <nl> + void set ( ReadBuffer & buf ) <nl> + { <nl> + UInt64 x = 0 ; <nl> + readVarUInt ( x , buf ) ; <nl> + set ( x ) ; <nl> + } <nl> + <nl> + void write ( WriteBuffer & buf ) const <nl> + { <nl> + writeVarUInt ( is_auto ? 0 : value , buf ) ; <nl> + } <nl> + <nl> + void setAuto ( ) <nl> + { <nl> + value = getAutoValue ( ) ; <nl> + is_auto = true ; <nl> + } <nl> + <nl> + UInt64 getAutoValue ( ) const <nl> + { <nl> + static auto res = getAutoValueImpl ( ) ; <nl> + return res ; <nl> + } <nl> + <nl> + / / / Выполняется один раз за всё время . Выполняется из одного потока . <nl> + UInt64 getAutoValueImpl ( ) const <nl> + { <nl> + cpu_raw_data_t raw_data ; <nl> + if ( 0 ! = cpuid_get_raw_data ( & raw_data ) ) <nl> + throw Exception ( " Cannot cpuid_get_raw_data : " + String ( cpuid_error ( ) ) , ErrorCodes : : CPUID_ERROR ) ; <nl> + <nl> + cpu_id_t data ; <nl> + if ( 0 ! = cpu_identify ( & raw_data , & data ) ) <nl> + throw Exception ( " Cannot cpu_identify : " + String ( cpuid_error ( ) ) , ErrorCodes : : CPUID_ERROR ) ; <nl> + <nl> + return data . num_cores * data . total_logical_cpus / data . num_logical_cpus ; <nl> + } <nl> + } ; <nl> + <nl> + <nl> struct SettingSeconds <nl> { <nl> Poco : : Timespan value ; <nl> mmm a / dbms / include / DB / Interpreters / SpecializedAggregator . h <nl> ppp b / dbms / include / DB / Interpreters / SpecializedAggregator . h <nl> void NO_INLINE Aggregator : : executeSpecializedCase ( <nl> bool overflow = false ; / / / Новый ключ не поместился в хэш - таблицу из - за no_more_keys . <nl> <nl> / / / Получаем ключ для вставки в хэш - таблицу . <nl> - typename Method : : Key key = state . getKey ( key_columns , keys_size , i , key_sizes , keys ) ; <nl> + typename Method : : Key key = state . getKey ( key_columns , keys_size , i , key_sizes , keys , * aggregates_pool ) ; <nl> <nl> if ( ! no_more_keys ) / / / Вставляем . <nl> { <nl> / / / Оптимизация для часто повторяющихся ключей . <nl> - if ( i ! = 0 & & key = = prev_key ) <nl> + if ( ! Method : : no_consecutive_keys_optimization ) <nl> { <nl> - AggregateDataPtr value = Method : : getAggregateData ( it - > second ) ; <nl> - <nl> - / / / Добавляем значения в агрегатные функции . <nl> - AggregateFunctionsList : : forEach ( AggregateFunctionsUpdater ( <nl> - aggregate_functions , offsets_of_aggregate_states , aggregate_columns , value , i ) ) ; <nl> - <nl> - continue ; <nl> + if ( i ! = 0 & & key = = prev_key ) <nl> + { <nl> + AggregateDataPtr value = Method : : getAggregateData ( it - > second ) ; <nl> + <nl> + / / / Добавляем значения в агрегатные функции . <nl> + AggregateFunctionsList : : forEach ( AggregateFunctionsUpdater ( <nl> + aggregate_functions , offsets_of_aggregate_states , aggregate_columns , value , i ) ) ; <nl> + <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> + continue ; <nl> + } <nl> + else <nl> + prev_key = key ; <nl> } <nl> - else <nl> - prev_key = key ; <nl> <nl> method . data . emplace ( key , it , inserted ) ; <nl> } <nl> void NO_INLINE Aggregator : : executeSpecializedCase ( <nl> <nl> / / / Если ключ не поместился , и данные не надо агрегировать в отдельную строку , то делать нечего . <nl> if ( no_more_keys & & overflow & & ! overflow_row ) <nl> + { <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> continue ; <nl> + } <nl> <nl> / / / Если вставили новый ключ - инициализируем состояния агрегатных функций , и возможно , что - нибудь связанное с ключом . <nl> if ( inserted ) <nl> void NO_INLINE Aggregator : : executeSpecializedCase ( <nl> AggregateFunctionsList : : forEach ( AggregateFunctionsCreator ( <nl> aggregate_functions , offsets_of_aggregate_states , aggregate_columns , aggregate_data ) ) ; <nl> } <nl> + else <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> <nl> AggregateDataPtr value = ( ! no_more_keys | | ! overflow ) ? Method : : getAggregateData ( it - > second ) : overflow_row ; <nl> <nl> mmm a / dbms / include / DB / Storages / ITableDeclaration . h <nl> ppp b / dbms / include / DB / Storages / ITableDeclaration . h <nl> <nl> # include < DB / Core / Block . h > <nl> # include < DB / Storages / ColumnDefault . h > <nl> <nl> + # include < boost / range / iterator_range . hpp > <nl> + # include < boost / range / join . hpp > <nl> + <nl> + <nl> namespace DB <nl> { <nl> <nl> class ITableDeclaration <nl> <nl> private : <nl> virtual const NamesAndTypesList & getColumnsListImpl ( ) const = 0 ; <nl> + <nl> + using ColumnsListRange = boost : : range : : joined_range < <nl> + const boost : : iterator_range < NamesAndTypesList : : const_iterator > , <nl> + const boost : : iterator_range < NamesAndTypesList : : const_iterator > > ; <nl> + ColumnsListRange getColumnsListIterator ( ) const ; <nl> } ; <nl> <nl> } <nl> mmm a / dbms / src / AggregateFunctions / AggregateFunctionFactory . cpp <nl> ppp b / dbms / src / AggregateFunctions / AggregateFunctionFactory . cpp <nl> AggregateFunctionPtr AggregateFunctionFactory : : get ( const String & name , const Da <nl> if ( res ) <nl> return res ; <nl> else if ( typeid_cast < const DataTypeDate * > ( & argument_type ) ) <nl> - return new AggregateFunctionUniq < DataTypeDate : : FieldType , AggregateFunctionUniqHLL12Data > ; <nl> + return new AggregateFunctionUniq < DataTypeDate : : FieldType , AggregateFunctionUniqHLL12Data < DataTypeDate : : FieldType > > ; <nl> else if ( typeid_cast < const DataTypeDateTime * > ( & argument_type ) ) <nl> - return new AggregateFunctionUniq < DataTypeDateTime : : FieldType , AggregateFunctionUniqHLL12Data > ; <nl> + return new AggregateFunctionUniq < DataTypeDateTime : : FieldType , AggregateFunctionUniqHLL12Data < DataTypeDateTime : : FieldType > > ; <nl> else if ( typeid_cast < const DataTypeString * > ( & argument_type ) | | typeid_cast < const DataTypeFixedString * > ( & argument_type ) ) <nl> - return new AggregateFunctionUniq < String , AggregateFunctionUniqHLL12Data > ; <nl> + return new AggregateFunctionUniq < String , AggregateFunctionUniqHLL12Data < String > > ; <nl> else <nl> throw Exception ( " Illegal type " + argument_types [ 0 ] - > getName ( ) + " of argument for aggregate function " + name , ErrorCodes : : ILLEGAL_TYPE_OF_ARGUMENT ) ; <nl> } <nl> mmm a / dbms / src / Client / ParallelReplicas . cpp <nl> ppp b / dbms / src / Client / ParallelReplicas . cpp <nl> ParallelReplicas : : ParallelReplicas ( IConnectionPool * pool_ , Settings * settings_ <nl> <nl> void ParallelReplicas : : sendExternalTablesData ( std : : vector < ExternalTablesData > & data ) <nl> { <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + <nl> if ( ! sent_query ) <nl> throw Exception ( " Cannot send external tables data : query not yet sent . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> <nl> void ParallelReplicas : : sendExternalTablesData ( std : : vector < ExternalTablesData > & <nl> <nl> void ParallelReplicas : : sendQuery ( const String & query , const String & query_id , UInt64 stage , bool with_pending_data ) <nl> { <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + <nl> if ( sent_query ) <nl> throw Exception ( " Query already sent . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> <nl> void ParallelReplicas : : sendQuery ( const String & query , const String & query_id , <nl> <nl> Connection : : Packet ParallelReplicas : : receivePacket ( ) <nl> { <nl> - if ( ! sent_query ) <nl> - throw Exception ( " Cannot receive packets : no query sent . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - if ( ! hasActiveReplicas ( ) ) <nl> - throw Exception ( " No more packets are available . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> - <nl> - auto it = getReplicaForReading ( ) ; <nl> - if ( it = = replica_map . end ( ) ) <nl> - throw Exception ( " No available replica " , ErrorCodes : : NO_AVAILABLE_REPLICA ) ; <nl> - <nl> - Connection * connection = it - > second ; <nl> - Connection : : Packet packet = connection - > receivePacket ( ) ; <nl> - <nl> - switch ( packet . type ) <nl> - { <nl> - case Protocol : : Server : : Data : <nl> - case Protocol : : Server : : Progress : <nl> - case Protocol : : Server : : ProfileInfo : <nl> - case Protocol : : Server : : Totals : <nl> - case Protocol : : Server : : Extremes : <nl> - break ; <nl> - <nl> - case Protocol : : Server : : EndOfStream : <nl> - invalidateReplica ( it ) ; <nl> - break ; <nl> - <nl> - case Protocol : : Server : : Exception : <nl> - default : <nl> - connection - > disconnect ( ) ; <nl> - invalidateReplica ( it ) ; <nl> - break ; <nl> - } <nl> - <nl> - return packet ; <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + return receivePacketUnlocked ( ) ; <nl> } <nl> <nl> void ParallelReplicas : : disconnect ( ) <nl> { <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + <nl> for ( auto it = replica_map . begin ( ) ; it ! = replica_map . end ( ) ; + + it ) <nl> { <nl> Connection * connection = it - > second ; <nl> void ParallelReplicas : : disconnect ( ) <nl> <nl> void ParallelReplicas : : sendCancel ( ) <nl> { <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + <nl> if ( ! sent_query | | cancelled ) <nl> throw Exception ( " Cannot cancel . Either no query sent or already cancelled . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> <nl> void ParallelReplicas : : sendCancel ( ) <nl> <nl> Connection : : Packet ParallelReplicas : : drain ( ) <nl> { <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + <nl> if ( ! cancelled ) <nl> throw Exception ( " Cannot drain connections : cancel first . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> <nl> Connection : : Packet ParallelReplicas : : drain ( ) <nl> <nl> while ( hasActiveReplicas ( ) ) <nl> { <nl> - Connection : : Packet packet = receivePacket ( ) ; <nl> + Connection : : Packet packet = receivePacketUnlocked ( ) ; <nl> <nl> switch ( packet . type ) <nl> { <nl> Connection : : Packet ParallelReplicas : : drain ( ) <nl> <nl> std : : string ParallelReplicas : : dumpAddresses ( ) const <nl> { <nl> + Poco : : ScopedLock < Poco : : FastMutex > lock ( cancel_mutex ) ; <nl> + <nl> bool is_first = true ; <nl> std : : ostringstream os ; <nl> for ( auto & e : replica_map ) <nl> std : : string ParallelReplicas : : dumpAddresses ( ) const <nl> return os . str ( ) ; <nl> } <nl> <nl> - <nl> void ParallelReplicas : : registerReplica ( Connection * connection ) <nl> { <nl> if ( connection = = nullptr ) <nl> void ParallelReplicas : : registerReplica ( Connection * connection ) <nl> connection - > setThrottler ( throttler ) ; <nl> } <nl> <nl> + Connection : : Packet ParallelReplicas : : receivePacketUnlocked ( ) <nl> + { <nl> + if ( ! sent_query ) <nl> + throw Exception ( " Cannot receive packets : no query sent . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + if ( ! hasActiveReplicas ( ) ) <nl> + throw Exception ( " No more packets are available . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> + <nl> + auto it = getReplicaForReading ( ) ; <nl> + if ( it = = replica_map . end ( ) ) <nl> + throw Exception ( " No available replica " , ErrorCodes : : NO_AVAILABLE_REPLICA ) ; <nl> + <nl> + Connection * connection = it - > second ; <nl> + Connection : : Packet packet = connection - > receivePacket ( ) ; <nl> + <nl> + switch ( packet . type ) <nl> + { <nl> + case Protocol : : Server : : Data : <nl> + case Protocol : : Server : : Progress : <nl> + case Protocol : : Server : : ProfileInfo : <nl> + case Protocol : : Server : : Totals : <nl> + case Protocol : : Server : : Extremes : <nl> + break ; <nl> + <nl> + case Protocol : : Server : : EndOfStream : <nl> + invalidateReplica ( it ) ; <nl> + break ; <nl> + <nl> + case Protocol : : Server : : Exception : <nl> + default : <nl> + connection - > disconnect ( ) ; <nl> + invalidateReplica ( it ) ; <nl> + break ; <nl> + } <nl> + <nl> + return packet ; <nl> + } <nl> <nl> ParallelReplicas : : ReplicaMap : : iterator ParallelReplicas : : getReplicaForReading ( ) <nl> { <nl> mmm a / dbms / src / DataStreams / tests / aggregating_stream . cpp <nl> ppp b / dbms / src / DataStreams / tests / aggregating_stream . cpp <nl> int main ( int argc , char * * argv ) <nl> column_x . type = new DB : : DataTypeInt16 ; <nl> DB : : ColumnInt16 * x = new DB : : ColumnInt16 ; <nl> column_x . column = x ; <nl> - DB : : PODArray < Int16 > & vec_x = x - > getData ( ) ; <nl> + auto & vec_x = x - > getData ( ) ; <nl> <nl> vec_x . resize ( n ) ; <nl> for ( size_t i = 0 ; i < n ; + + i ) <nl> int main ( int argc , char * * argv ) <nl> <nl> DB : : BlockInputStreamPtr stream = new DB : : OneBlockInputStream ( block ) ; <nl> stream = new DB : : AggregatingBlockInputStream ( stream , key_column_numbers , aggregate_descriptions , false , true , <nl> - 0 , DB : : OverflowMode : : THROW , nullptr , 0 ) ; <nl> + 0 , DB : : OverflowMode : : THROW , nullptr , 0 , 0 ) ; <nl> <nl> DB : : WriteBufferFromOStream ob ( std : : cout ) ; <nl> DB : : RowOutputStreamPtr row_out = new DB : : TabSeparatedRowOutputStream ( ob , sample ) ; <nl> mmm a / dbms / src / Interpreters / Aggregator . cpp <nl> ppp b / dbms / src / Interpreters / Aggregator . cpp <nl> AggregatedDataVariants : : Type Aggregator : : chooseAggregationMethod ( const ConstColu <nl> * Затем , в процессе работы , данные могут быть переконвертированы в two - level структуру , если их становится много . <nl> * / <nl> <nl> - bool keys_fit_128_bits = true ; <nl> + bool all_fixed = true ; <nl> size_t keys_bytes = 0 ; <nl> key_sizes . resize ( keys_size ) ; <nl> for ( size_t j = 0 ; j < keys_size ; + + j ) <nl> { <nl> if ( ! key_columns [ j ] - > isFixed ( ) ) <nl> { <nl> - keys_fit_128_bits = false ; <nl> + all_fixed = false ; <nl> break ; <nl> } <nl> key_sizes [ j ] = key_columns [ j ] - > sizeOfField ( ) ; <nl> keys_bytes + = key_sizes [ j ] ; <nl> } <nl> - if ( keys_bytes > 16 ) <nl> - keys_fit_128_bits = false ; <nl> <nl> / / / Если ключей нет <nl> if ( keys_size = = 0 ) <nl> AggregatedDataVariants : : Type Aggregator : : chooseAggregationMethod ( const ConstColu <nl> throw Exception ( " Logical error : numeric column has sizeOfField not in 1 , 2 , 4 , 8 . " , ErrorCodes : : LOGICAL_ERROR ) ; <nl> } <nl> <nl> - / / / Если ключи помещаются в 128 бит , будем использовать хэш - таблицу по упакованным в 128 - бит ключам <nl> - if ( keys_fit_128_bits ) <nl> + / / / Если ключи помещаются в N бит , будем использовать хэш - таблицу по упакованным в N - бит ключам <nl> + if ( all_fixed & & keys_bytes < = 16 ) <nl> return AggregatedDataVariants : : Type : : keys128 ; <nl> + if ( all_fixed & & keys_bytes < = 32 ) <nl> + return AggregatedDataVariants : : Type : : keys256 ; <nl> <nl> / / / Если есть один строковый ключ , то используем хэш - таблицу с ним <nl> if ( keys_size = = 1 & & typeid_cast < const ColumnString * > ( key_columns [ 0 ] ) ) <nl> AggregatedDataVariants : : Type Aggregator : : chooseAggregationMethod ( const ConstColu <nl> if ( keys_size = = 1 & & typeid_cast < const ColumnFixedString * > ( key_columns [ 0 ] ) ) <nl> return AggregatedDataVariants : : Type : : key_fixed_string ; <nl> <nl> - / / / Иначе будем агрегировать по хэшу от ключей . <nl> - return AggregatedDataVariants : : Type : : hashed ; <nl> + / / / Иначе будем агрегировать по конкатенации ключей . <nl> + return AggregatedDataVariants : : Type : : concat ; <nl> + <nl> + / / / NOTE AggregatedDataVariants : : Type : : hashed не используется . <nl> } <nl> <nl> <nl> void NO_INLINE Aggregator : : executeImplCase ( <nl> bool overflow = false ; / / / Новый ключ не поместился в хэш - таблицу из - за no_more_keys . <nl> <nl> / / / Получаем ключ для вставки в хэш - таблицу . <nl> - typename Method : : Key key = state . getKey ( key_columns , keys_size , i , key_sizes , keys ) ; <nl> + typename Method : : Key key = state . getKey ( key_columns , keys_size , i , key_sizes , keys , * aggregates_pool ) ; <nl> <nl> if ( ! no_more_keys ) / / / Вставляем . <nl> { <nl> / / / Оптимизация для часто повторяющихся ключей . <nl> - if ( i ! = 0 & & key = = prev_key ) <nl> + if ( ! Method : : no_consecutive_keys_optimization ) <nl> { <nl> - / / / Добавляем значения в агрегатные функции . <nl> - AggregateDataPtr value = Method : : getAggregateData ( it - > second ) ; <nl> - for ( size_t j = 0 ; j < aggregates_size ; + + j ) / / / NOTE : Заменить индекс на два указателя ? <nl> - aggregate_functions [ j ] - > add ( value + offsets_of_aggregate_states [ j ] , & aggregate_columns [ j ] [ 0 ] , i ) ; <nl> + if ( i ! = 0 & & key = = prev_key ) <nl> + { <nl> + / / / Добавляем значения в агрегатные функции . <nl> + AggregateDataPtr value = Method : : getAggregateData ( it - > second ) ; <nl> + for ( size_t j = 0 ; j < aggregates_size ; + + j ) / / / NOTE : Заменить индекс на два указателя ? <nl> + aggregate_functions [ j ] - > add ( value + offsets_of_aggregate_states [ j ] , & aggregate_columns [ j ] [ 0 ] , i ) ; <nl> <nl> - continue ; <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> + continue ; <nl> + } <nl> + else <nl> + prev_key = key ; <nl> } <nl> - else <nl> - prev_key = key ; <nl> <nl> method . data . emplace ( key , it , inserted ) ; <nl> } <nl> void NO_INLINE Aggregator : : executeImplCase ( <nl> <nl> / / / Если ключ не поместился , и данные не надо агрегировать в отдельную строку , то делать нечего . <nl> if ( no_more_keys & & overflow & & ! overflow_row ) <nl> + { <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> continue ; <nl> + } <nl> <nl> / / / Если вставили новый ключ - инициализируем состояния агрегатных функций , и возможно , что - нибудь связанное с ключом . <nl> if ( inserted ) <nl> void NO_INLINE Aggregator : : executeImplCase ( <nl> aggregate_data = aggregates_pool - > alloc ( total_size_of_aggregate_states ) ; <nl> createAggregateStates ( aggregate_data ) ; <nl> } <nl> + else <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> <nl> AggregateDataPtr value = ( ! no_more_keys | | ! overflow ) ? Method : : getAggregateData ( it - > second ) : overflow_row ; <nl> <nl> bool Aggregator : : executeOnBlock ( Block & block , AggregatedDataVariants & result , <nl> <nl> size_t result_size = result . sizeWithoutOverflowRow ( ) ; <nl> <nl> - / / / Если результат уже достаточно большой , и его можно сконвертировать в двухуровневую хэш - таблицу . <nl> - constexpr auto TWO_LEVEL_HASH_TABLE_THRESHOLD = 30000 ; <nl> - <nl> - / * * Почему выбрано 30 000 ? Потому что при таком количестве элементов , в TwoLevelHashTable , <nl> - * скорее всего , хватит места на все ключи , с размером таблицы по - умолчанию <nl> - * ( 256 корзин по 256 ячеек , fill factor = 0 . 5 ) <nl> - * TODO Не конвертировать , если запрос выполняется в один поток . <nl> - * / <nl> - <nl> - if ( result . isConvertibleToTwoLevel ( ) & & result_size > = TWO_LEVEL_HASH_TABLE_THRESHOLD ) <nl> + if ( group_by_two_level_threshold & & result . isConvertibleToTwoLevel ( ) & & result_size > = group_by_two_level_threshold ) <nl> result . convertToTwoLevel ( ) ; <nl> <nl> / / / Проверка ограничений . <nl> AggregatedDataVariantsPtr Aggregator : : merge ( ManyAggregatedDataVariants & data_va <nl> mergeSingleLevelDataImpl < decltype ( res - > key_fixed_string ) : : element_type > ( non_empty_data ) ; <nl> else if ( res - > type = = AggregatedDataVariants : : Type : : keys128 ) <nl> mergeSingleLevelDataImpl < decltype ( res - > keys128 ) : : element_type > ( non_empty_data ) ; <nl> + else if ( res - > type = = AggregatedDataVariants : : Type : : keys256 ) <nl> + mergeSingleLevelDataImpl < decltype ( res - > keys256 ) : : element_type > ( non_empty_data ) ; <nl> else if ( res - > type = = AggregatedDataVariants : : Type : : hashed ) <nl> mergeSingleLevelDataImpl < decltype ( res - > hashed ) : : element_type > ( non_empty_data ) ; <nl> + else if ( res - > type = = AggregatedDataVariants : : Type : : concat ) <nl> + mergeSingleLevelDataImpl < decltype ( res - > concat ) : : element_type > ( non_empty_data ) ; <nl> else if ( res - > type = = AggregatedDataVariants : : Type : : key32_two_level ) <nl> mergeTwoLevelDataImpl < decltype ( res - > key32_two_level ) : : element_type > ( non_empty_data , thread_pool . get ( ) ) ; <nl> else if ( res - > type = = AggregatedDataVariants : : Type : : key64_two_level ) <nl> AggregatedDataVariantsPtr Aggregator : : merge ( ManyAggregatedDataVariants & data_va <nl> mergeTwoLevelDataImpl < decltype ( res - > key_fixed_string_two_level ) : : element_type > ( non_empty_data , thread_pool . get ( ) ) ; <nl> else if ( res - > type = = AggregatedDataVariants : : Type : : keys128_two_level ) <nl> mergeTwoLevelDataImpl < decltype ( res - > keys128_two_level ) : : element_type > ( non_empty_data , thread_pool . get ( ) ) ; <nl> + else if ( res - > type = = AggregatedDataVariants : : Type : : keys256_two_level ) <nl> + mergeTwoLevelDataImpl < decltype ( res - > keys256_two_level ) : : element_type > ( non_empty_data , thread_pool . get ( ) ) ; <nl> else if ( res - > type = = AggregatedDataVariants : : Type : : hashed_two_level ) <nl> mergeTwoLevelDataImpl < decltype ( res - > hashed_two_level ) : : element_type > ( non_empty_data , thread_pool . get ( ) ) ; <nl> + else if ( res - > type = = AggregatedDataVariants : : Type : : concat_two_level ) <nl> + mergeTwoLevelDataImpl < decltype ( res - > concat_two_level ) : : element_type > ( non_empty_data , thread_pool . get ( ) ) ; <nl> else if ( res - > type ! = AggregatedDataVariants : : Type : : without_key ) <nl> throw Exception ( " Unknown aggregated data variant . " , ErrorCodes : : UNKNOWN_AGGREGATED_DATA_VARIANT ) ; <nl> <nl> void NO_INLINE Aggregator : : mergeStreamsImpl ( <nl> bool inserted ; / / / Вставили новый ключ , или такой ключ уже был ? <nl> <nl> / / / Получаем ключ для вставки в хэш - таблицу . <nl> - auto key = state . getKey ( key_columns , keys_size , i , result . key_sizes , keys ) ; <nl> + auto key = state . getKey ( key_columns , keys_size , i , result . key_sizes , keys , * aggregates_pool ) ; <nl> <nl> data . emplace ( key , it , inserted ) ; <nl> <nl> void NO_INLINE Aggregator : : mergeStreamsImpl ( <nl> aggregate_data = aggregates_pool - > alloc ( total_size_of_aggregate_states ) ; <nl> createAggregateStates ( aggregate_data ) ; <nl> } <nl> + else <nl> + method . onExistingKey ( key , keys , * aggregates_pool ) ; <nl> <nl> / / / Мерджим состояния агрегатных функций . <nl> for ( size_t j = 0 ; j < aggregates_size ; + + j ) <nl> mmm a / dbms / src / Interpreters / InterpreterSelectQuery . cpp <nl> ppp b / dbms / src / Interpreters / InterpreterSelectQuery . cpp <nl> void InterpreterSelectQuery : : executeAggregation ( BlockInputStreams & streams , Exp <nl> { <nl> stream = new ParallelAggregatingBlockInputStream ( streams , key_names , aggregates , overflow_row , final , <nl> settings . max_threads , settings . limits . max_rows_to_group_by , settings . limits . group_by_overflow_mode , <nl> - settings . compile ? & context . getCompiler ( ) : nullptr , settings . min_count_to_compile ) ; <nl> + settings . compile ? & context . getCompiler ( ) : nullptr , settings . min_count_to_compile , settings . group_by_two_level_threshold ) ; <nl> <nl> streams . resize ( 1 ) ; <nl> } <nl> else <nl> stream = new AggregatingBlockInputStream ( stream , key_names , aggregates , overflow_row , final , <nl> settings . limits . max_rows_to_group_by , settings . limits . group_by_overflow_mode , <nl> - settings . compile ? & context . getCompiler ( ) : nullptr , settings . min_count_to_compile ) ; <nl> + settings . compile ? & context . getCompiler ( ) : nullptr , settings . min_count_to_compile , 0 ) ; <nl> } <nl> <nl> <nl> mmm a / dbms / src / Interpreters / Join . cpp <nl> ppp b / dbms / src / Interpreters / Join . cpp <nl> void Join : : insertFromBlockImpl ( Maps & maps , size_t rows , const ConstColumnPlainP <nl> for ( size_t i = 0 ; i < rows ; + + i ) <nl> { <nl> UInt128 key = keys_fit_128_bits <nl> - ? pack128 ( i , keys_size , key_columns , key_sizes ) <nl> + ? packFixed < UInt128 > ( i , keys_size , key_columns , key_sizes ) <nl> : hash128 ( i , keys_size , key_columns ) ; <nl> <nl> Inserter < STRICTNESS , Map > : : insert ( res , key , stored_block , i , pool ) ; <nl> void Join : : joinBlockImpl ( Block & block , const Maps & maps ) const <nl> for ( size_t i = 0 ; i < rows ; + + i ) <nl> { <nl> UInt128 key = keys_fit_128_bits <nl> - ? pack128 ( i , keys_size , key_columns , key_sizes ) <nl> + ? packFixed < UInt128 > ( i , keys_size , key_columns , key_sizes ) <nl> : hash128 ( i , keys_size , key_columns ) ; <nl> <nl> Adder < KIND , STRICTNESS , Map > : : add ( map , key , num_columns_to_add , added_columns , i , filter . get ( ) , current_offset , offsets_to_replicate . get ( ) ) ; <nl> mmm a / dbms / src / Interpreters / LogicalExpressionsOptimizer . cpp <nl> ppp b / dbms / src / Interpreters / LogicalExpressionsOptimizer . cpp <nl> LogicalExpressionsOptimizer : : OrWithExpression : : OrWithExpression ( ASTFunction * or <nl> <nl> bool LogicalExpressionsOptimizer : : OrWithExpression : : operator < ( const OrWithExpression & rhs ) const <nl> { <nl> - std : : ptrdiff_t res1 = this - > or_function - rhs . or_function ; <nl> - if ( res1 < 0 ) <nl> - return true ; <nl> - if ( res1 > 0 ) <nl> - return false ; <nl> - <nl> - int res2 = this - > expression . compare ( rhs . expression ) ; <nl> - if ( res2 < 0 ) <nl> - return true ; <nl> - if ( res2 > 0 ) <nl> - return false ; <nl> - <nl> - return false ; <nl> + return std : : tie ( this - > or_function , this - > expression ) < std : : tie ( rhs . or_function , rhs . expression ) ; <nl> } <nl> <nl> LogicalExpressionsOptimizer : : LogicalExpressionsOptimizer ( ASTSelectQuery * select_query_ , const Settings & settings_ ) <nl> bool LogicalExpressionsOptimizer : : mayOptimizeDisjunctiveEqualityChain ( const Disj <nl> const auto & equality_functions = equalities . functions ; <nl> <nl> / / / Исключаем слишком короткие цепочки . <nl> - if ( equality_functions . size ( ) < settings . min_or_chain_length_for_optimization ) <nl> + if ( equality_functions . size ( ) < settings . optimize_min_equality_disjunction_chain_length ) <nl> return false ; <nl> <nl> / / / Проверяем , что правые части всех равенств имеют один и тот же тип . <nl> mmm a / dbms / src / Interpreters / Set . cpp <nl> ppp b / dbms / src / Interpreters / Set . cpp <nl> bool Set : : insertFromBlock ( const Block & block , bool create_ordered_set ) <nl> <nl> / / / Для всех строчек <nl> for ( size_t i = 0 ; i < rows ; + + i ) <nl> - res . insert ( keys_fit_128_bits ? pack128 ( i , keys_size , key_columns , key_sizes ) : hash128 ( i , keys_size , key_columns ) ) ; <nl> + res . insert ( keys_fit_128_bits ? packFixed < UInt128 > ( i , keys_size , key_columns , key_sizes ) : hash128 ( i , keys_size , key_columns ) ) ; <nl> } <nl> else <nl> throw Exception ( " Unknown set variant . " , ErrorCodes : : UNKNOWN_SET_DATA_VARIANT ) ; <nl> void Set : : executeOrdinary ( const ConstColumnPlainPtrs & key_columns , ColumnUInt8 : <nl> <nl> / / / Для всех строчек <nl> for ( size_t i = 0 ; i < rows ; + + i ) <nl> - vec_res [ i ] = negative ^ ( set . end ( ) ! = set . find ( keys_fit_128_bits ? pack128 ( i , keys_size , key_columns , key_sizes ) : hash128 ( i , keys_size , key_columns ) ) ) ; <nl> + vec_res [ i ] = negative ^ <nl> + ( set . end ( ) ! = set . find ( keys_fit_128_bits <nl> + ? packFixed < UInt128 > ( i , keys_size , key_columns , key_sizes ) <nl> + : hash128 ( i , keys_size , key_columns ) ) ) ; <nl> } <nl> else <nl> throw Exception ( " Unknown set variant . " , ErrorCodes : : UNKNOWN_SET_DATA_VARIANT ) ; <nl> void Set : : executeArray ( const ColumnArray * key_column , ColumnUInt8 : : Container_t <nl> for ( size_t j = prev_offset ; j < offsets [ i ] ; + + j ) <nl> { <nl> / / / Строим ключ <nl> - res | = negative ^ ( set . end ( ) ! = set . find ( keys_fit_128_bits ? pack128 ( i , 1 , nested_columns , key_sizes ) : hash128 ( i , 1 , nested_columns ) ) ) ; <nl> + res | = negative ^ <nl> + ( set . end ( ) ! = set . find ( keys_fit_128_bits <nl> + ? packFixed < UInt128 > ( i , 1 , nested_columns , key_sizes ) <nl> + : hash128 ( i , 1 , nested_columns ) ) ) ; <nl> if ( res ) <nl> break ; <nl> } <nl> mmm a / dbms / src / Interpreters / tests / aggregate . cpp <nl> ppp b / dbms / src / Interpreters / tests / aggregate . cpp <nl> int main ( int argc , char * * argv ) <nl> column_x . type = new DB : : DataTypeInt16 ; <nl> DB : : ColumnInt16 * x = new DB : : ColumnInt16 ; <nl> column_x . column = x ; <nl> - DB : : PODArray < Int16 > & vec_x = x - > getData ( ) ; <nl> + auto & vec_x = x - > getData ( ) ; <nl> <nl> vec_x . resize ( n ) ; <nl> for ( size_t i = 0 ; i < n ; + + i ) <nl> int main ( int argc , char * * argv ) <nl> DB : : DataTypes empty_list_of_types ; <nl> aggregate_descriptions [ 0 ] . function = factory . get ( " count " , empty_list_of_types ) ; <nl> <nl> - DB : : Aggregator aggregator ( key_column_numbers , aggregate_descriptions , false , 0 , DB : : OverflowMode : : THROW , nullptr , 0 ) ; <nl> + DB : : Aggregator aggregator ( key_column_numbers , aggregate_descriptions , false , 0 , DB : : OverflowMode : : THROW , nullptr , 0 , 0 ) ; <nl> <nl> { <nl> Poco : : Stopwatch stopwatch ; <nl> mmm a / dbms / src / Interpreters / tests / expression . cpp <nl> ppp b / dbms / src / Interpreters / tests / expression . cpp <nl> int main ( int argc , char * * argv ) <nl> column_x . type = new DataTypeInt16 ; <nl> ColumnInt16 * x = new ColumnInt16 ; <nl> column_x . column = x ; <nl> - PODArray < Int16 > & vec_x = x - > getData ( ) ; <nl> + auto & vec_x = x - > getData ( ) ; <nl> <nl> vec_x . resize ( n ) ; <nl> for ( size_t i = 0 ; i < n ; + + i ) <nl> mmm a / dbms / src / Storages / ITableDeclaration . cpp <nl> ppp b / dbms / src / Storages / ITableDeclaration . cpp <nl> <nl> # include < DB / Parsers / ASTNameTypePair . h > <nl> # include < DB / Interpreters / Context . h > <nl> <nl> + <nl> namespace DB <nl> { <nl> <nl> NamesAndTypesList ITableDeclaration : : getColumnsList ( ) const <nl> } <nl> <nl> <nl> + ITableDeclaration : : ColumnsListRange ITableDeclaration : : getColumnsListIterator ( ) const <nl> + { <nl> + const auto & columns = getColumnsListImpl ( ) ; <nl> + return boost : : join ( <nl> + boost : : iterator_range < NamesAndTypesList : : const_iterator > ( columns . begin ( ) , columns . end ( ) ) , <nl> + boost : : iterator_range < NamesAndTypesList : : const_iterator > ( std : : begin ( materialized_columns ) , std : : end ( materialized_columns ) ) ) ; <nl> + } <nl> + <nl> + <nl> bool ITableDeclaration : : hasRealColumn ( const String & column_name ) const <nl> { <nl> - const NamesAndTypesList & real_columns = getColumnsList ( ) ; <nl> - for ( auto & it : real_columns ) <nl> + for ( auto & it : getColumnsListIterator ( ) ) <nl> if ( it . name = = column_name ) <nl> return true ; <nl> return false ; <nl> bool ITableDeclaration : : hasRealColumn ( const String & column_name ) const <nl> <nl> Names ITableDeclaration : : getColumnNamesList ( ) const <nl> { <nl> - const NamesAndTypesList & real_columns = getColumnsList ( ) ; <nl> Names res ; <nl> - for ( auto & it : real_columns ) <nl> + for ( auto & it : getColumnsListIterator ( ) ) <nl> res . push_back ( it . name ) ; <nl> return res ; <nl> } <nl> Names ITableDeclaration : : getColumnNamesList ( ) const <nl> <nl> NameAndTypePair ITableDeclaration : : getRealColumn ( const String & column_name ) const <nl> { <nl> - const NamesAndTypesList & real_columns = getColumnsList ( ) ; <nl> - for ( auto & it : real_columns ) <nl> + for ( auto & it : getColumnsListIterator ( ) ) <nl> if ( it . name = = column_name ) <nl> return it ; <nl> throw Exception ( " There is no column " + column_name + " in table . " , ErrorCodes : : NO_SUCH_COLUMN_IN_TABLE ) ; <nl> NameAndTypePair ITableDeclaration : : getColumn ( const String & column_name ) const <nl> <nl> const DataTypePtr ITableDeclaration : : getDataTypeByName ( const String & column_name ) const <nl> { <nl> - for ( const auto & column : getColumnsList ( ) ) <nl> + for ( const auto & column : getColumnsListIterator ( ) ) <nl> if ( column . name = = column_name ) <nl> return column . type ; <nl> <nl> Block ITableDeclaration : : getSampleBlock ( ) const <nl> { <nl> Block res ; <nl> <nl> - for ( const auto & col : getColumnsList ( ) ) <nl> + for ( const auto & col : getColumnsListIterator ( ) ) <nl> res . insert ( { col . type - > createColumn ( ) , col . type , col . name } ) ; <nl> <nl> return res ; <nl> new file mode 100644 <nl> index 00000000000 . . 05a86aa8596 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00127_group_by_concat . reference <nl> <nl> + 0 9 <nl> + 1 9 <nl> + 2 9 <nl> + 3 9 <nl> + 4 9 <nl> + 5 9 <nl> + 6 9 <nl> + 7 9 <nl> + 8 9 <nl> + 9 9 <nl> + 10 9 <nl> + 11 9 <nl> + 12 9 <nl> + 13 9 <nl> + 14 9 <nl> + 15 9 <nl> + 16 8 <nl> + 17 8 <nl> + 18 8 <nl> + 19 8 <nl> + 20 8 <nl> + 21 8 <nl> + 22 8 <nl> + 23 8 <nl> + 24 8 <nl> + 25 8 <nl> + 26 8 <nl> + 27 8 <nl> + 28 8 <nl> + 29 8 <nl> + 30 8 <nl> + 31 8 <nl> + 32 8 <nl> + 33 8 <nl> + 34 8 <nl> + 35 8 <nl> + 36 8 <nl> + 37 8 <nl> + 38 8 <nl> + 39 8 <nl> + 40 8 <nl> + 41 8 <nl> + 42 8 <nl> + 43 8 <nl> + 44 8 <nl> + 45 8 <nl> + 46 8 <nl> + 47 8 <nl> + 48 8 <nl> + 49 8 <nl> + 50 8 <nl> + 51 8 <nl> + 52 8 <nl> + 53 8 <nl> + 54 8 <nl> + 55 8 <nl> + 56 8 <nl> + 57 8 <nl> + 58 8 <nl> + 59 8 <nl> + 60 8 <nl> + 61 8 <nl> + 62 8 <nl> + 63 8 <nl> + 64 8 <nl> + 65 8 <nl> + 66 8 <nl> + 67 8 <nl> + 68 8 <nl> + 69 8 <nl> + 70 8 <nl> + 71 8 <nl> + 72 8 <nl> + 73 8 <nl> + 74 8 <nl> + 75 8 <nl> + 76 8 <nl> + 77 8 <nl> + 78 8 <nl> + 79 8 <nl> + 80 8 <nl> + 81 8 <nl> + 82 8 <nl> + 83 8 <nl> + 84 8 <nl> + 85 8 <nl> + 86 8 <nl> + 87 8 <nl> + 88 8 <nl> + 89 8 <nl> + 90 8 <nl> + 91 8 <nl> + 92 8 <nl> + 93 8 <nl> + 94 8 <nl> + 95 8 <nl> + 96 8 <nl> + 97 8 <nl> + 98 8 <nl> + 99 8 <nl> + 100 8 <nl> + 101 8 <nl> + 102 8 <nl> + 103 8 <nl> + 104 8 <nl> + 105 8 <nl> + 106 8 <nl> + 107 8 <nl> + 108 8 <nl> + 109 8 <nl> + 110 8 <nl> + 111 8 <nl> + 112 8 <nl> + 113 8 <nl> + 114 8 <nl> + 115 8 <nl> + 116 8 <nl> + 117 8 <nl> + 118 8 <nl> + 119 8 <nl> + 120 8 <nl> + 121 8 <nl> + 122 8 <nl> new file mode 100644 <nl> index 00000000000 . . 4f343f69518 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00127_group_by_concat . sql <nl> @ @ - 0 , 0 + 1 @ @ <nl> + SELECT materialize ( ' ' ) AS k1 , number % 123 AS k2 , count ( ) AS c FROM ( SELECT * FROM system . numbers LIMIT 1000 ) GROUP BY k1 , k2 ORDER BY k1 , k2 ; <nl> new file mode 100644 <nl> index 00000000000 . . f5ba86c1d71 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00128_group_by_number_and_fixed_string . reference <nl> <nl> + 99999 <nl> + 99998 <nl> + 99997 <nl> + 99996 <nl> + 99995 <nl> + 99994 <nl> + 99993 <nl> + 99992 <nl> + 99991 <nl> + 99990 <nl> new file mode 100644 <nl> index 00000000000 . . 25d25c2b751 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00128_group_by_number_and_fixed_string . sql <nl> @ @ - 0 , 0 + 1 @ @ <nl> + SELECT n , k FROM ( SELECT number AS n , toFixedString ( materialize ( ' ' ) , 3 ) AS k FROM system . numbers LIMIT 100000 ) GROUP BY n , k ORDER BY n DESC , k LIMIT 10 ; <nl> new file mode 100644 <nl> index 00000000000 . . ca936f2abf5 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / asm - bits . c <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + <nl> + # include " libcpuid . h " <nl> + # include " asm - bits . h " <nl> + <nl> + int cpuid_exists_by_eflags ( void ) <nl> + { <nl> + # if defined ( PLATFORM_X64 ) <nl> + return 1 ; / * CPUID is always present on the x86_64 * / <nl> + # elif defined ( PLATFORM_X86 ) <nl> + # if defined ( COMPILER_GCC ) <nl> + int result ; <nl> + __asm __volatile ( <nl> + " pushfl \ n " <nl> + " pop % % eax \ n " <nl> + " mov % % eax , % % ecx \ n " <nl> + " xor $ 0x200000 , % % eax \ n " <nl> + " push % % eax \ n " <nl> + " popfl \ n " <nl> + " pushfl \ n " <nl> + " pop % % eax \ n " <nl> + " xor % % ecx , % % eax \ n " <nl> + " mov % % eax , % 0 \ n " <nl> + " push % % ecx \ n " <nl> + " popfl \ n " <nl> + : " = m " ( result ) <nl> + : : " eax " , " ecx " , " memory " ) ; <nl> + return ( result ! = 0 ) ; <nl> + # elif defined ( COMPILER_MICROSOFT ) <nl> + int result ; <nl> + __asm { <nl> + pushfd <nl> + pop eax <nl> + mov ecx , eax <nl> + xor eax , 0x200000 <nl> + push eax <nl> + popfd <nl> + pushfd <nl> + pop eax <nl> + xor eax , ecx <nl> + mov result , eax <nl> + push ecx <nl> + popfd <nl> + } ; <nl> + return ( result ! = 0 ) ; <nl> + # else <nl> + return 0 ; <nl> + # endif / * COMPILER_MICROSOFT * / <nl> + # else <nl> + return 0 ; <nl> + # endif / * PLATFORM_X86 * / <nl> + } <nl> + <nl> + / * <nl> + * with MSVC / AMD64 , the exec_cpuid ( ) and cpu_rdtsc ( ) functions <nl> + * are implemented in separate . asm files . Otherwise , use inline assembly <nl> + * / <nl> + void exec_cpuid ( uint32_t * regs ) <nl> + { <nl> + # ifdef INLINE_ASM_SUPPORTED <nl> + # ifdef COMPILER_GCC <nl> + # ifdef PLATFORM_X64 <nl> + __asm __volatile ( <nl> + " mov % 0 , % % rdi \ n " <nl> + <nl> + " push % % rbx \ n " <nl> + " push % % rcx \ n " <nl> + " push % % rdx \ n " <nl> + <nl> + " mov ( % % rdi ) , % % eax \ n " <nl> + " mov 4 ( % % rdi ) , % % ebx \ n " <nl> + " mov 8 ( % % rdi ) , % % ecx \ n " <nl> + " mov 12 ( % % rdi ) , % % edx \ n " <nl> + <nl> + " cpuid \ n " <nl> + <nl> + " movl % % eax , ( % % rdi ) \ n " <nl> + " movl % % ebx , 4 ( % % rdi ) \ n " <nl> + " movl % % ecx , 8 ( % % rdi ) \ n " <nl> + " movl % % edx , 12 ( % % rdi ) \ n " <nl> + " pop % % rdx \ n " <nl> + " pop % % rcx \ n " <nl> + " pop % % rbx \ n " <nl> + : <nl> + : " m " ( regs ) <nl> + : " memory " , " eax " , " rdi " <nl> + ) ; <nl> + # else <nl> + __asm __volatile ( <nl> + " mov % 0 , % % edi \ n " <nl> + <nl> + " push % % ebx \ n " <nl> + " push % % ecx \ n " <nl> + " push % % edx \ n " <nl> + <nl> + " mov ( % % edi ) , % % eax \ n " <nl> + " mov 4 ( % % edi ) , % % ebx \ n " <nl> + " mov 8 ( % % edi ) , % % ecx \ n " <nl> + " mov 12 ( % % edi ) , % % edx \ n " <nl> + <nl> + " cpuid \ n " <nl> + <nl> + " mov % % eax , ( % % edi ) \ n " <nl> + " mov % % ebx , 4 ( % % edi ) \ n " <nl> + " mov % % ecx , 8 ( % % edi ) \ n " <nl> + " mov % % edx , 12 ( % % edi ) \ n " <nl> + " pop % % edx \ n " <nl> + " pop % % ecx \ n " <nl> + " pop % % ebx \ n " <nl> + : <nl> + : " m " ( regs ) <nl> + : " memory " , " eax " , " edi " <nl> + ) ; <nl> + # endif / * COMPILER_GCC * / <nl> + # else <nl> + # ifdef COMPILER_MICROSOFT <nl> + __asm { <nl> + push ebx <nl> + push ecx <nl> + push edx <nl> + push edi <nl> + mov edi , regs <nl> + <nl> + mov eax , [ edi ] <nl> + mov ebx , [ edi + 4 ] <nl> + mov ecx , [ edi + 8 ] <nl> + mov edx , [ edi + 12 ] <nl> + <nl> + cpuid <nl> + <nl> + mov [ edi ] , eax <nl> + mov [ edi + 4 ] , ebx <nl> + mov [ edi + 8 ] , ecx <nl> + mov [ edi + 12 ] , edx <nl> + <nl> + pop edi <nl> + pop edx <nl> + pop ecx <nl> + pop ebx <nl> + } <nl> + # else <nl> + # error " Unsupported compiler " <nl> + # endif / * COMPILER_MICROSOFT * / <nl> + # endif <nl> + # endif / * INLINE_ASSEMBLY_SUPPORTED * / <nl> + } <nl> + <nl> + # ifdef INLINE_ASM_SUPPORTED <nl> + void cpu_rdtsc ( uint64_t * result ) <nl> + { <nl> + uint32_t low_part , hi_part ; <nl> + # ifdef COMPILER_GCC <nl> + __asm __volatile ( <nl> + " rdtsc \ n " <nl> + " mov % % eax , % 0 \ n " <nl> + " mov % % edx , % 1 \ n " <nl> + : " = m " ( low_part ) , " = m " ( hi_part ) : : " memory " , " eax " , " edx " <nl> + ) ; <nl> + # else <nl> + # ifdef COMPILER_MICROSOFT <nl> + __asm { <nl> + rdtsc <nl> + mov low_part , eax <nl> + mov hi_part , edx <nl> + } ; <nl> + # else <nl> + # error " Unsupported compiler " <nl> + # endif / * COMPILER_MICROSOFT * / <nl> + # endif / * COMPILER_GCC * / <nl> + * result = ( uint64_t ) low_part + ( ( ( uint64_t ) hi_part ) < < 32 ) ; <nl> + } <nl> + # endif / * INLINE_ASM_SUPPORTED * / <nl> + <nl> + # ifdef INLINE_ASM_SUPPORTED <nl> + void busy_sse_loop ( int cycles ) <nl> + { <nl> + # ifdef COMPILER_GCC <nl> + # ifndef __APPLE__ <nl> + # define XALIGN " . balign 16 \ n " <nl> + # else <nl> + # define XALIGN " . align 4 \ n " <nl> + # endif <nl> + __asm __volatile ( <nl> + " xorps % % xmm0 , % % xmm0 \ n " <nl> + " xorps % % xmm1 , % % xmm1 \ n " <nl> + " xorps % % xmm2 , % % xmm2 \ n " <nl> + " xorps % % xmm3 , % % xmm3 \ n " <nl> + " xorps % % xmm4 , % % xmm4 \ n " <nl> + " xorps % % xmm5 , % % xmm5 \ n " <nl> + " xorps % % xmm6 , % % xmm6 \ n " <nl> + " xorps % % xmm7 , % % xmm7 \ n " <nl> + XALIGN <nl> + " . bsLoop : \ n " <nl> + / / 0 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 1 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 2 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 3 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 4 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 5 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 6 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 7 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 8 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 9 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 10 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 11 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 12 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 13 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 14 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 15 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 16 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 17 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 18 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 19 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 20 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 21 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 22 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 23 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 24 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 25 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 26 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 27 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 28 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 29 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 30 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + / / 31 : <nl> + " addps % % xmm1 , % % xmm0 \ n " <nl> + " addps % % xmm2 , % % xmm1 \ n " <nl> + " addps % % xmm3 , % % xmm2 \ n " <nl> + " addps % % xmm4 , % % xmm3 \ n " <nl> + " addps % % xmm5 , % % xmm4 \ n " <nl> + " addps % % xmm6 , % % xmm5 \ n " <nl> + " addps % % xmm7 , % % xmm6 \ n " <nl> + " addps % % xmm0 , % % xmm7 \ n " <nl> + <nl> + " dec % % eax \ n " <nl> + " jnz . bsLoop \ n " <nl> + : : " a " ( cycles ) <nl> + ) ; <nl> + # else <nl> + # ifdef COMPILER_MICROSOFT <nl> + __asm { <nl> + mov eax , cycles <nl> + xorps xmm0 , xmm0 <nl> + xorps xmm1 , xmm1 <nl> + xorps xmm2 , xmm2 <nl> + xorps xmm3 , xmm3 <nl> + xorps xmm4 , xmm4 <nl> + xorps xmm5 , xmm5 <nl> + xorps xmm6 , xmm6 <nl> + xorps xmm7 , xmm7 <nl> + / / - - <nl> + align 16 <nl> + bsLoop : <nl> + / / 0 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 1 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 2 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 3 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 4 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 5 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 6 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 7 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 8 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 9 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 10 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 11 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 12 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 13 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 14 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 15 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 16 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 17 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 18 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 19 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 20 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 21 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 22 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 23 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 24 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 25 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 26 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 27 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 28 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 29 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 30 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / 31 : <nl> + addps xmm0 , xmm1 <nl> + addps xmm1 , xmm2 <nl> + addps xmm2 , xmm3 <nl> + addps xmm3 , xmm4 <nl> + addps xmm4 , xmm5 <nl> + addps xmm5 , xmm6 <nl> + addps xmm6 , xmm7 <nl> + addps xmm7 , xmm0 <nl> + / / mmmmmmmmmmmmmmmmmmmmm - <nl> + dec eax <nl> + jnz bsLoop <nl> + } <nl> + # else <nl> + # error " Unsupported compiler " <nl> + # endif / * COMPILER_MICROSOFT * / <nl> + # endif / * COMPILER_GCC * / <nl> + } <nl> + # endif / * INLINE_ASSEMBLY_SUPPORTED * / <nl> new file mode 100644 <nl> index 00000000000 . . 3a03e11ce8c <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / asm - bits . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # ifndef __ASM_BITS_H__ <nl> + # define __ASM_BITS_H__ <nl> + # include " libcpuid . h " <nl> + <nl> + / * Determine Compiler : * / <nl> + # if defined ( _MSC_VER ) <nl> + # define COMPILER_MICROSOFT <nl> + # elif defined ( __GNUC__ ) <nl> + # define COMPILER_GCC <nl> + # endif <nl> + <nl> + / * Determine Platform * / <nl> + # if defined ( __x86_64__ ) | | defined ( _M_AMD64 ) <nl> + # define PLATFORM_X64 <nl> + # elif defined ( __i386__ ) | | defined ( _M_IX86 ) <nl> + # define PLATFORM_X86 <nl> + # endif <nl> + <nl> + / * Under Windows / AMD64 with MSVC , inline assembly isn ' t supported * / <nl> + # if ( defined ( COMPILER_GCC ) & & defined ( PLATFORM_X64 ) ) | | defined ( PLATFORM_X86 ) <nl> + # define INLINE_ASM_SUPPORTED <nl> + # endif <nl> + <nl> + int cpuid_exists_by_eflags ( void ) ; <nl> + void exec_cpuid ( uint32_t * regs ) ; <nl> + void busy_sse_loop ( int cycles ) ; <nl> + <nl> + # endif / * __ASM_BITS_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . 29b513c4ac1 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / config . h <nl> <nl> + / * Version number of package * / <nl> + # define VERSION " 0 . 2 . 1 " <nl> new file mode 100644 <nl> index 00000000000 . . 96e07f6938e <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / cpuid_main . c <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # include " libcpuid . h " <nl> + # include " recog_intel . h " <nl> + # include " recog_amd . h " <nl> + # include " asm - bits . h " <nl> + # include " libcpuid_util . h " <nl> + # include " config . h " <nl> + # include < stdio . h > <nl> + # include < string . h > <nl> + # include < stdlib . h > <nl> + <nl> + / * Implementation : * / <nl> + <nl> + static int _libcpiud_errno = ERR_OK ; <nl> + <nl> + int set_error ( cpu_error_t err ) <nl> + { <nl> + _libcpiud_errno = ( int ) err ; <nl> + return ( int ) err ; <nl> + } <nl> + <nl> + static void raw_data_t_constructor ( struct cpu_raw_data_t * raw ) <nl> + { <nl> + memset ( raw , 0 , sizeof ( struct cpu_raw_data_t ) ) ; <nl> + } <nl> + <nl> + static void cpu_id_t_constructor ( struct cpu_id_t * id ) <nl> + { <nl> + memset ( id , 0 , sizeof ( struct cpu_id_t ) ) ; <nl> + id - > l1_data_cache = id - > l1_instruction_cache = id - > l2_cache = id - > l3_cache = - 1 ; <nl> + id - > l1_assoc = id - > l2_assoc = id - > l3_assoc = - 1 ; <nl> + id - > l1_cacheline = id - > l2_cacheline = id - > l3_cacheline = - 1 ; <nl> + id - > sse_size = - 1 ; <nl> + } <nl> + <nl> + static int parse_token ( const char * expected_token , const char * token , <nl> + const char * value , uint32_t array [ ] [ 4 ] , int limit , int * recognized ) <nl> + { <nl> + char format [ 32 ] ; <nl> + int veax , vebx , vecx , vedx ; <nl> + int index ; <nl> + <nl> + if ( * recognized ) return 1 ; / * already recognized * / <nl> + if ( strncmp ( token , expected_token , strlen ( expected_token ) ) ) return 1 ; / * not what we search for * / <nl> + sprintf ( format , " % s [ % % d ] " , expected_token ) ; <nl> + * recognized = 1 ; <nl> + if ( 1 = = sscanf ( token , format , & index ) & & index > = 0 & & index < limit ) { <nl> + if ( 4 = = sscanf ( value , " % x % x % x % x " , & veax , & vebx , & vecx , & vedx ) ) { <nl> + array [ index ] [ 0 ] = veax ; <nl> + array [ index ] [ 1 ] = vebx ; <nl> + array [ index ] [ 2 ] = vecx ; <nl> + array [ index ] [ 3 ] = vedx ; <nl> + return 1 ; <nl> + } <nl> + } <nl> + return 0 ; <nl> + } <nl> + <nl> + / * get_total_cpus ( ) system specific code : uses OS routines to determine total number of CPUs * / <nl> + # ifdef __APPLE__ <nl> + # include < unistd . h > <nl> + # include < mach / clock_types . h > <nl> + # include < mach / clock . h > <nl> + # include < mach / mach . h > <nl> + static int get_total_cpus ( void ) <nl> + { <nl> + kern_return_t kr ; <nl> + host_basic_info_data_t basic_info ; <nl> + host_info_t info = ( host_info_t ) & basic_info ; <nl> + host_flavor_t flavor = HOST_BASIC_INFO ; <nl> + mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT ; <nl> + kr = host_info ( mach_host_self ( ) , flavor , info , & count ) ; <nl> + if ( kr ! = KERN_SUCCESS ) return 1 ; <nl> + return basic_info . avail_cpus ; <nl> + } <nl> + # define GET_TOTAL_CPUS_DEFINED <nl> + # endif <nl> + <nl> + # ifdef _WIN32 <nl> + # include < windows . h > <nl> + static int get_total_cpus ( void ) <nl> + { <nl> + SYSTEM_INFO system_info ; <nl> + GetSystemInfo ( & system_info ) ; <nl> + return system_info . dwNumberOfProcessors ; <nl> + } <nl> + # define GET_TOTAL_CPUS_DEFINED <nl> + # endif <nl> + <nl> + # if defined linux | | defined __linux__ | | defined __sun <nl> + # include < sys / sysinfo . h > <nl> + # include < unistd . h > <nl> + <nl> + static int get_total_cpus ( void ) <nl> + { <nl> + return sysconf ( _SC_NPROCESSORS_ONLN ) ; <nl> + } <nl> + # define GET_TOTAL_CPUS_DEFINED <nl> + # endif <nl> + <nl> + # if defined __FreeBSD__ | | defined __OpenBSD__ | | defined __NetBSD__ | | defined __bsdi__ | | defined __QNX__ <nl> + # include < sys / sysctl . h > <nl> + <nl> + static int get_total_cpus ( void ) <nl> + { <nl> + int mib [ 2 ] = { CTL_HW , HW_NCPU } ; <nl> + int ncpus ; <nl> + size_t len = sizeof ( ncpus ) ; <nl> + if ( sysctl ( mib , 2 , & ncpus , & len , ( void * ) 0 , 0 ) ! = 0 ) return 1 ; <nl> + return ncpus ; <nl> + } <nl> + # define GET_TOTAL_CPUS_DEFINED <nl> + # endif <nl> + <nl> + # ifndef GET_TOTAL_CPUS_DEFINED <nl> + static int get_total_cpus ( void ) <nl> + { <nl> + static int warning_printed = 0 ; <nl> + if ( ! warning_printed ) { <nl> + warning_printed = 1 ; <nl> + warnf ( " Your system is not supported by libcpuid - - don ' t know how to detect the \ n " ) ; <nl> + warnf ( " total number of CPUs on your system . It will be reported as 1 . \ n " ) ; <nl> + printf ( " Please use cpu_id_t . logical_cpus field instead . \ n " ) ; <nl> + } <nl> + return 1 ; <nl> + } <nl> + # endif / * GET_TOTAL_CPUS_DEFINED * / <nl> + <nl> + <nl> + static void load_features_common ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + const struct feature_map_t matchtable_edx1 [ ] = { <nl> + { 0 , CPU_FEATURE_FPU } , <nl> + { 1 , CPU_FEATURE_VME } , <nl> + { 2 , CPU_FEATURE_DE } , <nl> + { 3 , CPU_FEATURE_PSE } , <nl> + { 4 , CPU_FEATURE_TSC } , <nl> + { 5 , CPU_FEATURE_MSR } , <nl> + { 6 , CPU_FEATURE_PAE } , <nl> + { 7 , CPU_FEATURE_MCE } , <nl> + { 8 , CPU_FEATURE_CX8 } , <nl> + { 9 , CPU_FEATURE_APIC } , <nl> + { 11 , CPU_FEATURE_SEP } , <nl> + { 12 , CPU_FEATURE_MTRR } , <nl> + { 13 , CPU_FEATURE_PGE } , <nl> + { 14 , CPU_FEATURE_MCA } , <nl> + { 15 , CPU_FEATURE_CMOV } , <nl> + { 16 , CPU_FEATURE_PAT } , <nl> + { 17 , CPU_FEATURE_PSE36 } , <nl> + { 19 , CPU_FEATURE_CLFLUSH } , <nl> + { 23 , CPU_FEATURE_MMX } , <nl> + { 24 , CPU_FEATURE_FXSR } , <nl> + { 25 , CPU_FEATURE_SSE } , <nl> + { 26 , CPU_FEATURE_SSE2 } , <nl> + { 28 , CPU_FEATURE_HT } , <nl> + } ; <nl> + const struct feature_map_t matchtable_ecx1 [ ] = { <nl> + { 0 , CPU_FEATURE_PNI } , <nl> + { 3 , CPU_FEATURE_MONITOR } , <nl> + { 9 , CPU_FEATURE_SSSE3 } , <nl> + { 12 , CPU_FEATURE_FMA3 } , <nl> + { 13 , CPU_FEATURE_CX16 } , <nl> + { 19 , CPU_FEATURE_SSE4_1 } , <nl> + { 21 , CPU_FEATURE_X2APIC } , <nl> + { 23 , CPU_FEATURE_POPCNT } , <nl> + { 29 , CPU_FEATURE_F16C } , <nl> + } ; <nl> + const struct feature_map_t matchtable_edx81 [ ] = { <nl> + { 11 , CPU_FEATURE_SYSCALL } , <nl> + { 27 , CPU_FEATURE_RDTSCP } , <nl> + { 29 , CPU_FEATURE_LM } , <nl> + } ; <nl> + const struct feature_map_t matchtable_ecx81 [ ] = { <nl> + { 0 , CPU_FEATURE_LAHF_LM } , <nl> + } ; <nl> + const struct feature_map_t matchtable_edx87 [ ] = { <nl> + { 8 , CPU_FEATURE_CONSTANT_TSC } , <nl> + } ; <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 1 ) { <nl> + match_features ( matchtable_edx1 , COUNT_OF ( matchtable_edx1 ) , raw - > basic_cpuid [ 1 ] [ 3 ] , data ) ; <nl> + match_features ( matchtable_ecx1 , COUNT_OF ( matchtable_ecx1 ) , raw - > basic_cpuid [ 1 ] [ 2 ] , data ) ; <nl> + } <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 0x80000001 ) { <nl> + match_features ( matchtable_edx81 , COUNT_OF ( matchtable_edx81 ) , raw - > ext_cpuid [ 1 ] [ 3 ] , data ) ; <nl> + match_features ( matchtable_ecx81 , COUNT_OF ( matchtable_ecx81 ) , raw - > ext_cpuid [ 1 ] [ 2 ] , data ) ; <nl> + } <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 0x80000007 ) { <nl> + match_features ( matchtable_edx87 , COUNT_OF ( matchtable_edx87 ) , raw - > ext_cpuid [ 7 ] [ 3 ] , data ) ; <nl> + } <nl> + if ( data - > flags [ CPU_FEATURE_SSE ] ) { <nl> + / * apply guesswork to check if the SSE unit width is 128 bit * / <nl> + switch ( data - > vendor ) { <nl> + case VENDOR_AMD : <nl> + data - > sse_size = ( data - > ext_family > = 16 & & data - > ext_family ! = 17 ) ? 128 : 64 ; <nl> + break ; <nl> + case VENDOR_INTEL : <nl> + data - > sse_size = ( data - > family = = 6 & & data - > ext_model > = 15 ) ? 128 : 64 ; <nl> + break ; <nl> + default : <nl> + break ; <nl> + } <nl> + / * leave the CPU_FEATURE_128BIT_SSE_AUTH 0 ; the advanced per - vendor detection routines <nl> + * will set it accordingly if they detect the needed bit * / <nl> + } <nl> + } <nl> + <nl> + static int cpuid_basic_identify ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + int i , j , basic , xmodel , xfamily , ext ; <nl> + char brandstr [ 64 ] = { 0 } ; <nl> + const struct { cpu_vendor_t vendor ; char match [ 16 ] ; } <nl> + matchtable [ NUM_CPU_VENDORS ] = { <nl> + / * source : http : / / www . sandpile . org / ia32 / cpuid . htm * / <nl> + { VENDOR_INTEL , " GenuineIntel " } , <nl> + { VENDOR_AMD , " AuthenticAMD " } , <nl> + { VENDOR_CYRIX , " CyrixInstead " } , <nl> + { VENDOR_NEXGEN , " NexGenDriven " } , <nl> + { VENDOR_TRANSMETA , " GenuineTMx86 " } , <nl> + { VENDOR_UMC , " UMC UMC UMC " } , <nl> + { VENDOR_CENTAUR , " CentaurHauls " } , <nl> + { VENDOR_RISE , " RiseRiseRise " } , <nl> + { VENDOR_SIS , " SiS SiS SiS " } , <nl> + { VENDOR_NSC , " Geode by NSC " } , <nl> + } ; <nl> + <nl> + memcpy ( data - > vendor_str + 0 , & raw - > basic_cpuid [ 0 ] [ 1 ] , 4 ) ; <nl> + memcpy ( data - > vendor_str + 4 , & raw - > basic_cpuid [ 0 ] [ 3 ] , 4 ) ; <nl> + memcpy ( data - > vendor_str + 8 , & raw - > basic_cpuid [ 0 ] [ 2 ] , 4 ) ; <nl> + data - > vendor_str [ 12 ] = 0 ; <nl> + / * Determine vendor : * / <nl> + data - > vendor = VENDOR_UNKNOWN ; <nl> + for ( i = 0 ; i < NUM_CPU_VENDORS ; i + + ) <nl> + if ( ! strcmp ( data - > vendor_str , matchtable [ i ] . match ) ) { <nl> + data - > vendor = matchtable [ i ] . vendor ; <nl> + break ; <nl> + } <nl> + if ( data - > vendor = = VENDOR_UNKNOWN ) <nl> + return set_error ( ERR_CPU_UNKN ) ; <nl> + basic = raw - > basic_cpuid [ 0 ] [ 0 ] ; <nl> + if ( basic > = 1 ) { <nl> + data - > family = ( raw - > basic_cpuid [ 1 ] [ 0 ] > > 8 ) & 0xf ; <nl> + data - > model = ( raw - > basic_cpuid [ 1 ] [ 0 ] > > 4 ) & 0xf ; <nl> + data - > stepping = raw - > basic_cpuid [ 1 ] [ 0 ] & 0xf ; <nl> + xmodel = ( raw - > basic_cpuid [ 1 ] [ 0 ] > > 16 ) & 0xf ; <nl> + xfamily = ( raw - > basic_cpuid [ 1 ] [ 0 ] > > 20 ) & 0xff ; <nl> + if ( data - > vendor = = VENDOR_AMD & & data - > family < 0xf ) <nl> + data - > ext_family = data - > family ; <nl> + else <nl> + data - > ext_family = data - > family + xfamily ; <nl> + data - > ext_model = data - > model + ( xmodel < < 4 ) ; <nl> + } <nl> + ext = raw - > ext_cpuid [ 0 ] [ 0 ] - 0x8000000 ; <nl> + <nl> + / * obtain the brand string , if present : * / <nl> + if ( ext > = 4 ) { <nl> + for ( i = 0 ; i < 3 ; i + + ) <nl> + for ( j = 0 ; j < 4 ; j + + ) <nl> + memcpy ( brandstr + i * 16 + j * 4 , <nl> + & raw - > ext_cpuid [ 2 + i ] [ j ] , 4 ) ; <nl> + brandstr [ 48 ] = 0 ; <nl> + i = 0 ; <nl> + while ( brandstr [ i ] = = ' ' ) i + + ; <nl> + strncpy ( data - > brand_str , brandstr + i , sizeof ( data - > brand_str ) ) ; <nl> + data - > brand_str [ 48 ] = 0 ; <nl> + } <nl> + load_features_common ( raw , data ) ; <nl> + data - > total_logical_cpus = get_total_cpus ( ) ; <nl> + return set_error ( ERR_OK ) ; <nl> + } <nl> + <nl> + static void make_list_from_string ( const char * csv , struct cpu_list_t * list ) <nl> + { <nl> + int i , n , l , last ; <nl> + l = ( int ) strlen ( csv ) ; <nl> + n = 0 ; <nl> + for ( i = 0 ; i < l ; i + + ) if ( csv [ i ] = = ' , ' ) n + + ; <nl> + n + + ; <nl> + list - > num_entries = n ; <nl> + list - > names = ( char * * ) malloc ( sizeof ( char * ) * n ) ; <nl> + last = - 1 ; <nl> + n = 0 ; <nl> + for ( i = 0 ; i < = l ; i + + ) if ( i = = l | | csv [ i ] = = ' , ' ) { <nl> + list - > names [ n ] = ( char * ) malloc ( i - last ) ; <nl> + memcpy ( list - > names [ n ] , & csv [ last + 1 ] , i - last - 1 ) ; <nl> + list - > names [ n ] [ i - last - 1 ] = ' \ 0 ' ; <nl> + n + + ; <nl> + last = i ; <nl> + } <nl> + } <nl> + <nl> + <nl> + / * Interface : * / <nl> + <nl> + int cpuid_get_total_cpus ( void ) <nl> + { <nl> + return get_total_cpus ( ) ; <nl> + } <nl> + <nl> + int cpuid_present ( void ) <nl> + { <nl> + return cpuid_exists_by_eflags ( ) ; <nl> + } <nl> + <nl> + void cpu_exec_cpuid ( uint32_t eax , uint32_t * regs ) <nl> + { <nl> + regs [ 0 ] = eax ; <nl> + regs [ 1 ] = regs [ 2 ] = regs [ 3 ] = 0 ; <nl> + exec_cpuid ( regs ) ; <nl> + } <nl> + <nl> + void cpu_exec_cpuid_ext ( uint32_t * regs ) <nl> + { <nl> + exec_cpuid ( regs ) ; <nl> + } <nl> + <nl> + int cpuid_get_raw_data ( struct cpu_raw_data_t * data ) <nl> + { <nl> + unsigned i ; <nl> + if ( ! cpuid_present ( ) ) <nl> + return set_error ( ERR_NO_CPUID ) ; <nl> + for ( i = 0 ; i < 32 ; i + + ) <nl> + cpu_exec_cpuid ( i , data - > basic_cpuid [ i ] ) ; <nl> + for ( i = 0 ; i < 32 ; i + + ) <nl> + cpu_exec_cpuid ( 0x80000000 + i , data - > ext_cpuid [ i ] ) ; <nl> + for ( i = 0 ; i < 4 ; i + + ) { <nl> + memset ( data - > intel_fn4 [ i ] , 0 , sizeof ( data - > intel_fn4 [ i ] ) ) ; <nl> + data - > intel_fn4 [ i ] [ 0 ] = 4 ; <nl> + data - > intel_fn4 [ i ] [ 2 ] = i ; <nl> + cpu_exec_cpuid_ext ( data - > intel_fn4 [ i ] ) ; <nl> + } <nl> + for ( i = 0 ; i < MAX_INTELFN11_LEVEL ; i + + ) { <nl> + memset ( data - > intel_fn11 [ i ] , 0 , sizeof ( data - > intel_fn11 [ i ] ) ) ; <nl> + data - > intel_fn11 [ i ] [ 0 ] = 11 ; <nl> + data - > intel_fn11 [ i ] [ 2 ] = i ; <nl> + cpu_exec_cpuid_ext ( data - > intel_fn11 [ i ] ) ; <nl> + } <nl> + return set_error ( ERR_OK ) ; <nl> + } <nl> + <nl> + int cpuid_serialize_raw_data ( struct cpu_raw_data_t * data , const char * filename ) <nl> + { <nl> + int i ; <nl> + FILE * f ; <nl> + <nl> + if ( ! strcmp ( filename , " " ) ) <nl> + f = stdout ; <nl> + else <nl> + f = fopen ( filename , " wt " ) ; <nl> + if ( ! f ) return set_error ( ERR_OPEN ) ; <nl> + <nl> + fprintf ( f , " version = % s \ n " , VERSION ) ; <nl> + for ( i = 0 ; i < MAX_CPUID_LEVEL ; i + + ) <nl> + fprintf ( f , " basic_cpuid [ % d ] = % 08x % 08x % 08x % 08x \ n " , i , <nl> + data - > basic_cpuid [ i ] [ 0 ] , data - > basic_cpuid [ i ] [ 1 ] , <nl> + data - > basic_cpuid [ i ] [ 2 ] , data - > basic_cpuid [ i ] [ 3 ] ) ; <nl> + for ( i = 0 ; i < MAX_EXT_CPUID_LEVEL ; i + + ) <nl> + fprintf ( f , " ext_cpuid [ % d ] = % 08x % 08x % 08x % 08x \ n " , i , <nl> + data - > ext_cpuid [ i ] [ 0 ] , data - > ext_cpuid [ i ] [ 1 ] , <nl> + data - > ext_cpuid [ i ] [ 2 ] , data - > ext_cpuid [ i ] [ 3 ] ) ; <nl> + for ( i = 0 ; i < MAX_INTELFN4_LEVEL ; i + + ) <nl> + fprintf ( f , " intel_fn4 [ % d ] = % 08x % 08x % 08x % 08x \ n " , i , <nl> + data - > intel_fn4 [ i ] [ 0 ] , data - > intel_fn4 [ i ] [ 1 ] , <nl> + data - > intel_fn4 [ i ] [ 2 ] , data - > intel_fn4 [ i ] [ 3 ] ) ; <nl> + for ( i = 0 ; i < MAX_INTELFN11_LEVEL ; i + + ) <nl> + fprintf ( f , " intel_fn11 [ % d ] = % 08x % 08x % 08x % 08x \ n " , i , <nl> + data - > intel_fn11 [ i ] [ 0 ] , data - > intel_fn11 [ i ] [ 1 ] , <nl> + data - > intel_fn11 [ i ] [ 2 ] , data - > intel_fn11 [ i ] [ 3 ] ) ; <nl> + <nl> + if ( strcmp ( filename , " " ) ) <nl> + fclose ( f ) ; <nl> + return set_error ( ERR_OK ) ; <nl> + } <nl> + <nl> + int cpuid_deserialize_raw_data ( struct cpu_raw_data_t * data , const char * filename ) <nl> + { <nl> + int i , len ; <nl> + char line [ 100 ] ; <nl> + char token [ 100 ] ; <nl> + char * value ; <nl> + int syntax ; <nl> + int cur_line = 0 ; <nl> + int recognized ; <nl> + FILE * f ; <nl> + <nl> + raw_data_t_constructor ( data ) ; <nl> + <nl> + if ( ! strcmp ( filename , " " ) ) <nl> + f = stdin ; <nl> + else <nl> + f = fopen ( filename , " rt " ) ; <nl> + if ( ! f ) return set_error ( ERR_OPEN ) ; <nl> + while ( fgets ( line , sizeof ( line ) , f ) ) { <nl> + + + cur_line ; <nl> + len = ( int ) strlen ( line ) ; <nl> + if ( len < 2 ) continue ; <nl> + if ( line [ len - 1 ] = = ' \ n ' ) <nl> + line [ - - len ] = ' \ 0 ' ; <nl> + for ( i = 0 ; i < len & & line [ i ] ! = ' = ' ; i + + ) <nl> + if ( i > = len & & i < 1 & & len - i - 1 < = 0 ) { <nl> + fclose ( f ) ; <nl> + return set_error ( ERR_BADFMT ) ; <nl> + } <nl> + strncpy ( token , line , i ) ; <nl> + token [ i ] = ' \ 0 ' ; <nl> + value = & line [ i + 1 ] ; <nl> + / * try to recognize the line * / <nl> + recognized = 0 ; <nl> + if ( ! strcmp ( token , " version " ) | | ! strcmp ( token , " build_date " ) ) { <nl> + recognized = 1 ; <nl> + } <nl> + syntax = 1 ; <nl> + syntax = syntax & & parse_token ( " basic_cpuid " , token , value , data - > basic_cpuid , 32 , & recognized ) ; <nl> + syntax = syntax & & parse_token ( " ext_cpuid " , token , value , data - > ext_cpuid , 32 , & recognized ) ; <nl> + syntax = syntax & & parse_token ( " intel_fn4 " , token , value , data - > intel_fn4 , 4 , & recognized ) ; <nl> + syntax = syntax & & parse_token ( " intel_fn11 " , token , value , data - > intel_fn11 , 4 , & recognized ) ; <nl> + if ( ! syntax ) { <nl> + warnf ( " Error : % s : % d : Syntax error \ n " , filename , cur_line ) ; <nl> + fclose ( f ) ; <nl> + return set_error ( ERR_BADFMT ) ; <nl> + } <nl> + if ( ! recognized ) { <nl> + warnf ( " Warning : % s : % d not understood ! \ n " , filename , cur_line ) ; <nl> + } <nl> + } <nl> + <nl> + if ( strcmp ( filename , " " ) ) <nl> + fclose ( f ) ; <nl> + return set_error ( ERR_OK ) ; <nl> + } <nl> + <nl> + int cpu_identify ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + int r ; <nl> + struct cpu_raw_data_t myraw ; <nl> + if ( ! raw ) { <nl> + if ( ( r = cpuid_get_raw_data ( & myraw ) ) < 0 ) <nl> + return set_error ( r ) ; <nl> + raw = & myraw ; <nl> + } <nl> + cpu_id_t_constructor ( data ) ; <nl> + if ( ( r = cpuid_basic_identify ( raw , data ) ) < 0 ) <nl> + return set_error ( r ) ; <nl> + switch ( data - > vendor ) { <nl> + case VENDOR_INTEL : <nl> + r = cpuid_identify_intel ( raw , data ) ; <nl> + break ; <nl> + case VENDOR_AMD : <nl> + r = cpuid_identify_amd ( raw , data ) ; <nl> + break ; <nl> + default : <nl> + break ; <nl> + } <nl> + return set_error ( r ) ; <nl> + } <nl> + <nl> + const char * cpu_feature_str ( cpu_feature_t feature ) <nl> + { <nl> + const struct { cpu_feature_t feature ; const char * name ; } <nl> + matchtable [ ] = { <nl> + { CPU_FEATURE_FPU , " fpu " } , <nl> + { CPU_FEATURE_VME , " vme " } , <nl> + { CPU_FEATURE_DE , " de " } , <nl> + { CPU_FEATURE_PSE , " pse " } , <nl> + { CPU_FEATURE_TSC , " tsc " } , <nl> + { CPU_FEATURE_MSR , " msr " } , <nl> + { CPU_FEATURE_PAE , " pae " } , <nl> + { CPU_FEATURE_MCE , " mce " } , <nl> + { CPU_FEATURE_CX8 , " cx8 " } , <nl> + { CPU_FEATURE_APIC , " apic " } , <nl> + { CPU_FEATURE_MTRR , " mtrr " } , <nl> + { CPU_FEATURE_SEP , " sep " } , <nl> + { CPU_FEATURE_PGE , " pge " } , <nl> + { CPU_FEATURE_MCA , " mca " } , <nl> + { CPU_FEATURE_CMOV , " cmov " } , <nl> + { CPU_FEATURE_PAT , " pat " } , <nl> + { CPU_FEATURE_PSE36 , " pse36 " } , <nl> + { CPU_FEATURE_PN , " pn " } , <nl> + { CPU_FEATURE_CLFLUSH , " clflush " } , <nl> + { CPU_FEATURE_DTS , " dts " } , <nl> + { CPU_FEATURE_ACPI , " acpi " } , <nl> + { CPU_FEATURE_MMX , " mmx " } , <nl> + { CPU_FEATURE_FXSR , " fxsr " } , <nl> + { CPU_FEATURE_SSE , " sse " } , <nl> + { CPU_FEATURE_SSE2 , " sse2 " } , <nl> + { CPU_FEATURE_SS , " ss " } , <nl> + { CPU_FEATURE_HT , " ht " } , <nl> + { CPU_FEATURE_TM , " tm " } , <nl> + { CPU_FEATURE_IA64 , " ia64 " } , <nl> + { CPU_FEATURE_PBE , " pbe " } , <nl> + { CPU_FEATURE_PNI , " pni " } , <nl> + { CPU_FEATURE_PCLMUL , " pclmul " } , <nl> + { CPU_FEATURE_DTS64 , " dts64 " } , <nl> + { CPU_FEATURE_MONITOR , " monitor " } , <nl> + { CPU_FEATURE_DS_CPL , " ds_cpl " } , <nl> + { CPU_FEATURE_VMX , " vmx " } , <nl> + { CPU_FEATURE_SMX , " smx " } , <nl> + { CPU_FEATURE_EST , " est " } , <nl> + { CPU_FEATURE_TM2 , " tm2 " } , <nl> + { CPU_FEATURE_SSSE3 , " ssse3 " } , <nl> + { CPU_FEATURE_CID , " cid " } , <nl> + { CPU_FEATURE_CX16 , " cx16 " } , <nl> + { CPU_FEATURE_XTPR , " xtpr " } , <nl> + { CPU_FEATURE_PDCM , " pdcm " } , <nl> + { CPU_FEATURE_DCA , " dca " } , <nl> + { CPU_FEATURE_SSE4_1 , " sse4_1 " } , <nl> + { CPU_FEATURE_SSE4_2 , " sse4_2 " } , <nl> + { CPU_FEATURE_SYSCALL , " syscall " } , <nl> + { CPU_FEATURE_XD , " xd " } , <nl> + { CPU_FEATURE_X2APIC , " x2apic " } , <nl> + { CPU_FEATURE_MOVBE , " movbe " } , <nl> + { CPU_FEATURE_POPCNT , " popcnt " } , <nl> + { CPU_FEATURE_AES , " aes " } , <nl> + { CPU_FEATURE_XSAVE , " xsave " } , <nl> + { CPU_FEATURE_OSXSAVE , " osxsave " } , <nl> + { CPU_FEATURE_AVX , " avx " } , <nl> + { CPU_FEATURE_MMXEXT , " mmxext " } , <nl> + { CPU_FEATURE_3DNOW , " 3dnow " } , <nl> + { CPU_FEATURE_3DNOWEXT , " 3dnowext " } , <nl> + { CPU_FEATURE_NX , " nx " } , <nl> + { CPU_FEATURE_FXSR_OPT , " fxsr_opt " } , <nl> + { CPU_FEATURE_RDTSCP , " rdtscp " } , <nl> + { CPU_FEATURE_LM , " lm " } , <nl> + { CPU_FEATURE_LAHF_LM , " lahf_lm " } , <nl> + { CPU_FEATURE_CMP_LEGACY , " cmp_legacy " } , <nl> + { CPU_FEATURE_SVM , " svm " } , <nl> + { CPU_FEATURE_SSE4A , " sse4a " } , <nl> + { CPU_FEATURE_MISALIGNSSE , " misalignsse " } , <nl> + { CPU_FEATURE_ABM , " abm " } , <nl> + { CPU_FEATURE_3DNOWPREFETCH , " 3dnowprefetch " } , <nl> + { CPU_FEATURE_OSVW , " osvw " } , <nl> + { CPU_FEATURE_IBS , " ibs " } , <nl> + { CPU_FEATURE_SSE5 , " sse5 " } , <nl> + { CPU_FEATURE_SKINIT , " skinit " } , <nl> + { CPU_FEATURE_WDT , " wdt " } , <nl> + { CPU_FEATURE_TS , " ts " } , <nl> + { CPU_FEATURE_FID , " fid " } , <nl> + { CPU_FEATURE_VID , " vid " } , <nl> + { CPU_FEATURE_TTP , " ttp " } , <nl> + { CPU_FEATURE_TM_AMD , " tm_amd " } , <nl> + { CPU_FEATURE_STC , " stc " } , <nl> + { CPU_FEATURE_100MHZSTEPS , " 100mhzsteps " } , <nl> + { CPU_FEATURE_HWPSTATE , " hwpstate " } , <nl> + { CPU_FEATURE_CONSTANT_TSC , " constant_tsc " } , <nl> + { CPU_FEATURE_XOP , " xop " } , <nl> + { CPU_FEATURE_FMA3 , " fma3 " } , <nl> + { CPU_FEATURE_FMA4 , " fma4 " } , <nl> + { CPU_FEATURE_TBM , " tbm " } , <nl> + { CPU_FEATURE_F16C , " f16c " } , <nl> + { CPU_FEATURE_RDRAND , " rdrand " } , <nl> + { CPU_FEATURE_CPB , " cpb " } , <nl> + { CPU_FEATURE_APERFMPERF , " aperfmperf " } , <nl> + { CPU_FEATURE_PFI , " pfi " } , <nl> + { CPU_FEATURE_PA , " pa " } , <nl> + { CPU_FEATURE_AVX2 , " avx2 " } , <nl> + } ; <nl> + unsigned i , n = COUNT_OF ( matchtable ) ; <nl> + if ( n ! = NUM_CPU_FEATURES ) { <nl> + warnf ( " Warning : incomplete library , feature matchtable size differs from the actual number of features . \ n " ) ; <nl> + } <nl> + for ( i = 0 ; i < n ; i + + ) <nl> + if ( matchtable [ i ] . feature = = feature ) <nl> + return matchtable [ i ] . name ; <nl> + return " " ; <nl> + } <nl> + <nl> + const char * cpuid_error ( void ) <nl> + { <nl> + const struct { cpu_error_t error ; const char * description ; } <nl> + matchtable [ ] = { <nl> + { ERR_OK , " No error " } , <nl> + { ERR_NO_CPUID , " CPUID instruction is not supported " } , <nl> + { ERR_NO_RDTSC , " RDTSC instruction is not supported " } , <nl> + { ERR_NO_MEM , " Memory allocation failed " } , <nl> + { ERR_OPEN , " File open operation failed " } , <nl> + { ERR_BADFMT , " Bad file format " } , <nl> + { ERR_NOT_IMP , " Not implemented " } , <nl> + { ERR_CPU_UNKN , " Unsupported processor " } , <nl> + } ; <nl> + unsigned i ; <nl> + for ( i = 0 ; i < COUNT_OF ( matchtable ) ; i + + ) <nl> + if ( _libcpiud_errno = = matchtable [ i ] . error ) <nl> + return matchtable [ i ] . description ; <nl> + return " Unknown error " ; <nl> + } <nl> + <nl> + <nl> + const char * cpuid_lib_version ( void ) <nl> + { <nl> + return VERSION ; <nl> + } <nl> + <nl> + libcpuid_warn_fn_t cpuid_set_warn_function ( libcpuid_warn_fn_t new_fn ) <nl> + { <nl> + libcpuid_warn_fn_t ret = _warn_fun ; <nl> + _warn_fun = new_fn ; <nl> + return ret ; <nl> + } <nl> + <nl> + void cpuid_set_verbosiness_level ( int level ) <nl> + { <nl> + _current_verboselevel = level ; <nl> + } <nl> + <nl> + void cpuid_get_cpu_list ( cpu_vendor_t vendor , struct cpu_list_t * list ) <nl> + { <nl> + switch ( vendor ) { <nl> + case VENDOR_INTEL : <nl> + cpuid_get_list_intel ( list ) ; <nl> + break ; <nl> + case VENDOR_AMD : <nl> + cpuid_get_list_amd ( list ) ; <nl> + break ; <nl> + case VENDOR_CYRIX : <nl> + make_list_from_string ( " Cx486 , Cx5x86 , 6x86 , 6x86MX , M II , MediaGX , MediaGXi , MediaGXm " , list ) ; <nl> + break ; <nl> + case VENDOR_NEXGEN : <nl> + make_list_from_string ( " Nx586 " , list ) ; <nl> + break ; <nl> + case VENDOR_TRANSMETA : <nl> + make_list_from_string ( " Crusoe , Efficeon " , list ) ; <nl> + break ; <nl> + case VENDOR_UMC : <nl> + make_list_from_string ( " UMC x86 CPU " , list ) ; <nl> + break ; <nl> + case VENDOR_CENTAUR : <nl> + make_list_from_string ( " VIA C3 , VIA C7 , VIA Nano " , list ) ; <nl> + break ; <nl> + case VENDOR_RISE : <nl> + make_list_from_string ( " Rise mP6 " , list ) ; <nl> + break ; <nl> + case VENDOR_SIS : <nl> + make_list_from_string ( " SiS mP6 " , list ) ; <nl> + break ; <nl> + case VENDOR_NSC : <nl> + make_list_from_string ( " Geode GXm , Geode GXLV , Geode GX1 , Geode GX2 " , list ) ; <nl> + break ; <nl> + default : <nl> + warnf ( " Unknown vendor passed to cpuid_get_cpu_list ( ) \ n " ) ; <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + void cpuid_free_cpu_list ( struct cpu_list_t * list ) <nl> + { <nl> + int i ; <nl> + if ( list - > num_entries < = 0 ) return ; <nl> + for ( i = 0 ; i < list - > num_entries ; i + + ) <nl> + free ( list - > names [ i ] ) ; <nl> + free ( list - > names ) ; <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . b78b0d6f514 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / libcpuid . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # ifndef __LIBCPUID_H__ <nl> + # define __LIBCPUID_H__ <nl> + / * * <nl> + * @ File libcpuid . h <nl> + * @ Author Veselin Georgiev <nl> + * @ Date Oct 2008 <nl> + * @ Version 0 . 2 . 1 <nl> + * <nl> + * Version history : <nl> + * <nl> + * 0 . 1 . 0 ( 2008 - 10 - 15 ) : initial adaptation from wxfractgui sources <nl> + * 0 . 1 . 1 ( 2009 - 07 - 06 ) : Added intel_fn11 fields to cpu_raw_data_t to handle <nl> + * new processor topology enumeration required on Core i7 <nl> + * 0 . 1 . 2 ( 2009 - 09 - 26 ) : Added support for MSR reading through self - extracting <nl> + * kernel driver on Win32 . <nl> + * 0 . 1 . 3 ( 2010 - 04 - 20 ) : Added support for greater more accurate CPU clock <nl> + * measurements with cpu_clock_by_ic ( ) <nl> + * 0 . 2 . 0 ( 2011 - 10 - 11 ) : Support for AMD Bulldozer CPUs , 128 - bit SSE unit size <nl> + * checking . A backwards - incompatible change , since the <nl> + * sizeof cpu_id_t is now different . <nl> + * 0 . 2 . 1 ( 2012 - 05 - 26 ) : Support for Ivy Bridge , and detecting the presence of <nl> + * the RdRand instruction . <nl> + * / <nl> + <nl> + / * * @ mainpage A simple libcpuid introduction <nl> + * <nl> + * LibCPUID provides CPU identification and access to the CPUID and RDTSC <nl> + * instructions on the x86 . <nl> + * < p > <nl> + * To execute CPUID , use \ ref cpu_exec_cpuid < br > <nl> + * To execute RDTSC , use \ ref cpu_rdtsc < br > <nl> + * To fetch the CPUID info needed for CPU identification , use <nl> + * \ ref cpuid_get_raw_data < br > <nl> + * To make sense of that data ( decode , extract features ) , use \ ref cpu_identify < br > <nl> + * < / p > <nl> + * / <nl> + <nl> + / * * @ defgroup libcpuid LibCPUID <nl> + @ { * / <nl> + <nl> + / * Include some integer type specifications : * / <nl> + # include " libcpuid_types . h " <nl> + <nl> + / * Some limits and other constants * / <nl> + # include " libcpuid_constants . h " <nl> + <nl> + # ifdef __cplusplus <nl> + extern " C " { <nl> + # endif <nl> + <nl> + / * * <nl> + * @ brief CPU vendor , as guessed from the Vendor String . <nl> + * / <nl> + typedef enum { <nl> + VENDOR_INTEL = 0 , / * ! < Intel CPU * / <nl> + VENDOR_AMD , / * ! < AMD CPU * / <nl> + VENDOR_CYRIX , / * ! < Cyrix CPU * / <nl> + VENDOR_NEXGEN , / * ! < NexGen CPU * / <nl> + VENDOR_TRANSMETA , / * ! < Transmeta CPU * / <nl> + VENDOR_UMC , / * ! < x86 CPU by UMC * / <nl> + VENDOR_CENTAUR , / * ! < x86 CPU by IDT * / <nl> + VENDOR_RISE , / * ! < x86 CPU by Rise Technology * / <nl> + VENDOR_SIS , / * ! < x86 CPU by SiS * / <nl> + VENDOR_NSC , / * ! < x86 CPU by National Semiconductor * / <nl> + <nl> + NUM_CPU_VENDORS , / * ! < Valid CPU vendor ids : 0 . . NUM_CPU_VENDORS - 1 * / <nl> + VENDOR_UNKNOWN = - 1 , <nl> + } cpu_vendor_t ; <nl> + # define NUM_CPU_VENDORS NUM_CPU_VENDORS <nl> + <nl> + / * * <nl> + * @ brief Contains just the raw CPUID data . <nl> + * <nl> + * This contains only the most basic CPU data , required to do identification <nl> + * and feature recognition . Every processor should be identifiable using this <nl> + * data only . <nl> + * / <nl> + struct cpu_raw_data_t { <nl> + / * * contains results of CPUID for eax = 0 , 1 , . . . * / <nl> + uint32_t basic_cpuid [ MAX_CPUID_LEVEL ] [ 4 ] ; <nl> + <nl> + / * * contains results of CPUID for eax = 0x80000000 , 0x80000001 , . . . * / <nl> + uint32_t ext_cpuid [ MAX_EXT_CPUID_LEVEL ] [ 4 ] ; <nl> + <nl> + / * * when the CPU is intel and it supports deterministic cache <nl> + information : this contains the results of CPUID for eax = 4 <nl> + and ecx = 0 , 1 , . . . * / <nl> + uint32_t intel_fn4 [ MAX_INTELFN4_LEVEL ] [ 4 ] ; <nl> + <nl> + / * * when the CPU is intel and it supports leaf 0Bh ( Extended Topology <nl> + enumeration leaf ) , this stores the result of CPUID with <nl> + eax = 11 and ecx = 0 , 1 , 2 . . . * / <nl> + uint32_t intel_fn11 [ MAX_INTELFN11_LEVEL ] [ 4 ] ; <nl> + } ; <nl> + <nl> + / * * <nl> + * @ brief This contains the recognized CPU features / info <nl> + * / <nl> + struct cpu_id_t { <nl> + / * * contains the CPU vendor string , e . g . " GenuineIntel " * / <nl> + char vendor_str [ VENDOR_STR_MAX ] ; <nl> + <nl> + / * * contains the brand string , e . g . " Intel ( R ) Xeon ( TM ) CPU 2 . 40GHz " * / <nl> + char brand_str [ BRAND_STR_MAX ] ; <nl> + <nl> + / * * contains the recognized CPU vendor * / <nl> + cpu_vendor_t vendor ; <nl> + <nl> + / * * <nl> + * contain CPU flags . Used to test for features . See <nl> + * the CPU_FEATURE_ * macros below . @ see Features <nl> + * / <nl> + uint8_t flags [ CPU_FLAGS_MAX ] ; <nl> + <nl> + / * * CPU family * / <nl> + int32_t family ; <nl> + <nl> + / * * CPU model * / <nl> + int32_t model ; <nl> + <nl> + / * * CPU stepping * / <nl> + int32_t stepping ; <nl> + <nl> + / * * CPU extended family * / <nl> + int32_t ext_family ; <nl> + <nl> + / * * CPU extended model * / <nl> + int32_t ext_model ; <nl> + <nl> + / * * Number of CPU cores on the current processor * / <nl> + int32_t num_cores ; <nl> + <nl> + / * * <nl> + * Number of logical processors on the current processor . <nl> + * Could be more than the number of physical cores , <nl> + * e . g . when the processor has HyperThreading . <nl> + * / <nl> + int32_t num_logical_cpus ; <nl> + <nl> + / * * <nl> + * The total number of logical processors . <nl> + * <nl> + * This is num_logical_cpus * { total physical processors in the system } <nl> + * <nl> + * If you ' re writing a multithreaded program and you want to run it on <nl> + * all CPUs , this is the number of threads you need . <nl> + * / <nl> + int32_t total_logical_cpus ; <nl> + <nl> + / * * <nl> + * L1 data cache size in KB . Could be zero , if the CPU lacks cache . <nl> + * If the size cannot be determined , it will be - 1 . <nl> + * / <nl> + int32_t l1_data_cache ; <nl> + <nl> + / * * <nl> + * L1 instruction cache size in KB . Could be zero , if the CPU lacks <nl> + * cache . If the size cannot be determined , it will be - 1 . <nl> + * @ note On some Intel CPUs , whose instruction cache is in fact <nl> + * a trace cache , the size will be expressed in K uOps . <nl> + * / <nl> + int32_t l1_instruction_cache ; <nl> + <nl> + / * * <nl> + * L2 cache size in KB . Could be zero , if the CPU lacks L2 cache . <nl> + * If the size of the cache could not be determined , it will be - 1 <nl> + * / <nl> + int32_t l2_cache ; <nl> + <nl> + / * * L3 cache size in KB . Zero on most systems * / <nl> + int32_t l3_cache ; <nl> + <nl> + / * * Cache associativity for the L1 data cache . - 1 if undetermined * / <nl> + int32_t l1_assoc ; <nl> + <nl> + / * * Cache associativity for the L2 cache . - 1 if undetermined * / <nl> + int32_t l2_assoc ; <nl> + <nl> + / * * Cache associativity for the L3 cache . - 1 if undetermined * / <nl> + int32_t l3_assoc ; <nl> + <nl> + / * * Cache - line size for L1 data cache . - 1 if undetermined * / <nl> + int32_t l1_cacheline ; <nl> + <nl> + / * * Cache - line size for L2 cache . - 1 if undetermined * / <nl> + int32_t l2_cacheline ; <nl> + <nl> + / * * Cache - line size for L3 cache . - 1 if undetermined * / <nl> + int32_t l3_cacheline ; <nl> + <nl> + / * * <nl> + * The brief and human - friendly CPU codename , which was recognized . < br > <nl> + * Examples : <nl> + * @ code <nl> + * + mmmmmm - - + mmmmmm - - + mmmmmm - + mmmmmm - + mmmmmm - + mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + mmmmmmmmmmmmmmmmmmmmm - - + <nl> + * | Vendor | Family | Model | Step . | Cache | Brand String | cpu_id_t . cpu_codename | <nl> + * + mmmmmm - - + mmmmmm - - + mmmmmm - + mmmmmm - + mmmmmm - + mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + mmmmmmmmmmmmmmmmmmmmm - - + <nl> + * | AMD | 6 | 8 | 0 | 256 | ( not available - will be ignored ) | " K6 - 2 " | <nl> + * | Intel | 15 | 2 | 5 | 512 | " Intel ( R ) Xeon ( TM ) CPU 2 . 40GHz " | " Xeon ( Prestonia ) " | <nl> + * | Intel | 6 | 15 | 11 | 4096 | " Intel ( R ) Core ( TM ) 2 Duo CPU E6550 . . . " | " Conroe ( Core 2 Duo ) " | <nl> + * | AMD | 15 | 35 | 2 | 1024 | " Dual Core AMD Opteron ( tm ) Proces . . . " | " Opteron ( Dual Core ) " | <nl> + * + mmmmmm - - + mmmmmm - - + mmmmmm - + mmmmmm - + mmmmmm - + mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + mmmmmmmmmmmmmmmmmmmmm - - + <nl> + * @ endcode <nl> + * / <nl> + char cpu_codename [ 64 ] ; <nl> + <nl> + / * * SSE execution unit size ( 64 or 128 ; - 1 if N / A ) * / <nl> + int32_t sse_size ; <nl> + <nl> + / * * <nl> + * contain miscellaneous detection information . Used to test about specifics of <nl> + * certain detected features . See CPU_HINT_ * macros below . @ see Hints <nl> + * / <nl> + uint8_t detection_hints [ CPU_HINTS_MAX ] ; <nl> + } ; <nl> + <nl> + / * * <nl> + * @ brief CPU feature identifiers <nl> + * <nl> + * Usage : <nl> + * @ code <nl> + * . . . <nl> + * struct cpu_raw_data_t raw ; <nl> + * struct cpu_id_t id ; <nl> + * if ( cpuid_get_raw_data ( & raw ) = = 0 & & cpu_identify ( & raw , & id ) = = 0 ) { <nl> + * if ( id . flags [ CPU_FEATURE_SSE2 ] ) { <nl> + * / / The CPU has SSE2 . . . <nl> + * . . . <nl> + * } else { <nl> + * / / no SSE2 <nl> + * } <nl> + * } else { <nl> + * / / processor cannot be determined . <nl> + * } <nl> + * @ endcode <nl> + * / <nl> + typedef enum { <nl> + CPU_FEATURE_FPU = 0 , / * ! < Floating point unit * / <nl> + CPU_FEATURE_VME , / * ! < Virtual mode extension * / <nl> + CPU_FEATURE_DE , / * ! < Debugging extension * / <nl> + CPU_FEATURE_PSE , / * ! < Page size extension * / <nl> + CPU_FEATURE_TSC , / * ! < Time - stamp counter * / <nl> + CPU_FEATURE_MSR , / * ! < Model - specific regsisters , RDMSR / WRMSR supported * / <nl> + CPU_FEATURE_PAE , / * ! < Physical address extension * / <nl> + CPU_FEATURE_MCE , / * ! < Machine check exception * / <nl> + CPU_FEATURE_CX8 , / * ! < CMPXCHG8B instruction supported * / <nl> + CPU_FEATURE_APIC , / * ! < APIC support * / <nl> + CPU_FEATURE_MTRR , / * ! < Memory type range registers * / <nl> + CPU_FEATURE_SEP , / * ! < SYSENTER / SYSEXIT instructions supported * / <nl> + CPU_FEATURE_PGE , / * ! < Page global enable * / <nl> + CPU_FEATURE_MCA , / * ! < Machine check architecture * / <nl> + CPU_FEATURE_CMOV , / * ! < CMOVxx instructions supported * / <nl> + CPU_FEATURE_PAT , / * ! < Page attribute table * / <nl> + CPU_FEATURE_PSE36 , / * ! < 36 - bit page address extension * / <nl> + CPU_FEATURE_PN , / * ! < Processor serial # implemented ( Intel P3 only ) * / <nl> + CPU_FEATURE_CLFLUSH , / * ! < CLFLUSH instruction supported * / <nl> + CPU_FEATURE_DTS , / * ! < Debug store supported * / <nl> + CPU_FEATURE_ACPI , / * ! < ACPI support ( power states ) * / <nl> + CPU_FEATURE_MMX , / * ! < MMX instruction set supported * / <nl> + CPU_FEATURE_FXSR , / * ! < FXSAVE / FXRSTOR supported * / <nl> + CPU_FEATURE_SSE , / * ! < Streaming - SIMD Extensions ( SSE ) supported * / <nl> + CPU_FEATURE_SSE2 , / * ! < SSE2 instructions supported * / <nl> + CPU_FEATURE_SS , / * ! < Self - snoop * / <nl> + CPU_FEATURE_HT , / * ! < Hyper - threading supported ( but might be disabled ) * / <nl> + CPU_FEATURE_TM , / * ! < Thermal monitor * / <nl> + CPU_FEATURE_IA64 , / * ! < IA64 supported ( Itanium only ) * / <nl> + CPU_FEATURE_PBE , / * ! < Pending - break enable * / <nl> + CPU_FEATURE_PNI , / * ! < PNI ( SSE3 ) instructions supported * / <nl> + CPU_FEATURE_PCLMUL , / * ! < PCLMULQDQ instruction supported * / <nl> + CPU_FEATURE_DTS64 , / * ! < 64 - bit Debug store supported * / <nl> + CPU_FEATURE_MONITOR , / * ! < MONITOR / MWAIT supported * / <nl> + CPU_FEATURE_DS_CPL , / * ! < CPL Qualified Debug Store * / <nl> + CPU_FEATURE_VMX , / * ! < Virtualization technology supported * / <nl> + CPU_FEATURE_SMX , / * ! < Safer mode exceptions * / <nl> + CPU_FEATURE_EST , / * ! < Enhanced SpeedStep * / <nl> + CPU_FEATURE_TM2 , / * ! < Thermal monitor 2 * / <nl> + CPU_FEATURE_SSSE3 , / * ! < SSSE3 instructionss supported ( this is different from SSE3 ! ) * / <nl> + CPU_FEATURE_CID , / * ! < Context ID supported * / <nl> + CPU_FEATURE_CX16 , / * ! < CMPXCHG16B instruction supported * / <nl> + CPU_FEATURE_XTPR , / * ! < Send Task Priority Messages disable * / <nl> + CPU_FEATURE_PDCM , / * ! < Performance capabilities MSR supported * / <nl> + CPU_FEATURE_DCA , / * ! < Direct cache access supported * / <nl> + CPU_FEATURE_SSE4_1 , / * ! < SSE 4 . 1 instructions supported * / <nl> + CPU_FEATURE_SSE4_2 , / * ! < SSE 4 . 2 instructions supported * / <nl> + CPU_FEATURE_SYSCALL , / * ! < SYSCALL / SYSRET instructions supported * / <nl> + CPU_FEATURE_XD , / * ! < Execute disable bit supported * / <nl> + CPU_FEATURE_MOVBE , / * ! < MOVBE instruction supported * / <nl> + CPU_FEATURE_POPCNT , / * ! < POPCNT instruction supported * / <nl> + CPU_FEATURE_AES , / * ! < AES * instructions supported * / <nl> + CPU_FEATURE_XSAVE , / * ! < XSAVE / XRSTOR / etc instructions supported * / <nl> + CPU_FEATURE_OSXSAVE , / * ! < non - privileged copy of OSXSAVE supported * / <nl> + CPU_FEATURE_AVX , / * ! < Advanced vector extensions supported * / <nl> + CPU_FEATURE_MMXEXT , / * ! < AMD MMX - extended instructions supported * / <nl> + CPU_FEATURE_3DNOW , / * ! < AMD 3DNow ! instructions supported * / <nl> + CPU_FEATURE_3DNOWEXT , / * ! < AMD 3DNow ! extended instructions supported * / <nl> + CPU_FEATURE_NX , / * ! < No - execute bit supported * / <nl> + CPU_FEATURE_FXSR_OPT , / * ! < FFXSR : FXSAVE and FXRSTOR optimizations * / <nl> + CPU_FEATURE_RDTSCP , / * ! < RDTSCP instruction supported ( AMD - only ) * / <nl> + CPU_FEATURE_LM , / * ! < Long mode ( x86_64 / EM64T ) supported * / <nl> + CPU_FEATURE_LAHF_LM , / * ! < LAHF / SAHF supported in 64 - bit mode * / <nl> + CPU_FEATURE_CMP_LEGACY , / * ! < core multi - processing legacy mode * / <nl> + CPU_FEATURE_SVM , / * ! < AMD Secure virtual machine * / <nl> + CPU_FEATURE_ABM , / * ! < LZCNT instruction support * / <nl> + CPU_FEATURE_MISALIGNSSE , / * ! < Misaligned SSE supported * / <nl> + CPU_FEATURE_SSE4A , / * ! < SSE 4a from AMD * / <nl> + CPU_FEATURE_3DNOWPREFETCH , / * ! < PREFETCH / PREFETCHW support * / <nl> + CPU_FEATURE_OSVW , / * ! < OS Visible Workaround ( AMD ) * / <nl> + CPU_FEATURE_IBS , / * ! < Instruction - based sampling * / <nl> + CPU_FEATURE_SSE5 , / * ! < SSE 5 instructions supported ( deprecated , will never be 1 ) * / <nl> + CPU_FEATURE_SKINIT , / * ! < SKINIT / STGI supported * / <nl> + CPU_FEATURE_WDT , / * ! < Watchdog timer support * / <nl> + CPU_FEATURE_TS , / * ! < Temperature sensor * / <nl> + CPU_FEATURE_FID , / * ! < Frequency ID control * / <nl> + CPU_FEATURE_VID , / * ! < Voltage ID control * / <nl> + CPU_FEATURE_TTP , / * ! < THERMTRIP * / <nl> + CPU_FEATURE_TM_AMD , / * ! < AMD - specified hardware thermal control * / <nl> + CPU_FEATURE_STC , / * ! < Software thermal control * / <nl> + CPU_FEATURE_100MHZSTEPS , / * ! < 100 MHz multiplier control * / <nl> + CPU_FEATURE_HWPSTATE , / * ! < Hardware P - state control * / <nl> + CPU_FEATURE_CONSTANT_TSC , / * ! < TSC ticks at constant rate * / <nl> + CPU_FEATURE_XOP , / * ! < The XOP instruction set ( same as the old CPU_FEATURE_SSE5 ) * / <nl> + CPU_FEATURE_FMA3 , / * ! < The FMA3 instruction set * / <nl> + CPU_FEATURE_FMA4 , / * ! < The FMA4 instruction set * / <nl> + CPU_FEATURE_TBM , / * ! < Trailing bit manipulation instruction support * / <nl> + CPU_FEATURE_F16C , / * ! < 16 - bit FP convert instruction support * / <nl> + CPU_FEATURE_RDRAND , / * ! < RdRand instruction * / <nl> + CPU_FEATURE_X2APIC , / * ! < x2APIC , APIC_BASE . EXTD , MSRs 0000_0800h . . . 0000_0BFFh 64 - bit ICR ( + 030h but not + 031h ) , no DFR ( + 00Eh ) , SELF_IPI ( + 040h ) also see standard level 0000_000Bh * / <nl> + CPU_FEATURE_CPB , / * ! < Core performance boost * / <nl> + CPU_FEATURE_APERFMPERF , / * ! < MPERF / APERF MSRs support * / <nl> + CPU_FEATURE_PFI , / * ! < Processor Feedback Interface support * / <nl> + CPU_FEATURE_PA , / * ! < Processor accumulator * / <nl> + CPU_FEATURE_AVX2 , / * ! < AVX2 instructions * / <nl> + / * termination : * / <nl> + NUM_CPU_FEATURES , <nl> + } cpu_feature_t ; <nl> + <nl> + / * * <nl> + * @ brief CPU detection hints identifiers <nl> + * <nl> + * Usage : similar to the flags usage <nl> + * / <nl> + typedef enum { <nl> + CPU_HINT_SSE_SIZE_AUTH = 0 , / * ! < SSE unit size is authoritative ( not only a Family / Model guesswork , but based on an actual CPUID bit ) * / <nl> + / * termination * / <nl> + NUM_CPU_HINTS , <nl> + } cpu_hint_t ; <nl> + <nl> + / * * <nl> + * @ brief Describes common library error codes <nl> + * / <nl> + typedef enum { <nl> + ERR_OK = 0 , / * ! < " No error " * / <nl> + ERR_NO_CPUID = - 1 , / * ! < " CPUID instruction is not supported " * / <nl> + ERR_NO_RDTSC = - 2 , / * ! < " RDTSC instruction is not supported " * / <nl> + ERR_NO_MEM = - 3 , / * ! < " Memory allocation failed " * / <nl> + ERR_OPEN = - 4 , / * ! < " File open operation failed " * / <nl> + ERR_BADFMT = - 5 , / * ! < " Bad file format " * / <nl> + ERR_NOT_IMP = - 6 , / * ! < " Not implemented " * / <nl> + ERR_CPU_UNKN = - 7 , / * ! < " Unsupported processor " * / <nl> + ERR_NO_RDMSR = - 8 , / * ! < " RDMSR instruction is not supported " * / <nl> + ERR_NO_DRIVER = - 9 , / * ! < " RDMSR driver error ( generic ) " * / <nl> + ERR_NO_PERMS = - 10 , / * ! < " No permissions to install RDMSR driver " * / <nl> + ERR_EXTRACT = - 11 , / * ! < " Cannot extract RDMSR driver ( read only media ? ) " * / <nl> + ERR_HANDLE = - 12 , / * ! < " Bad handle " * / <nl> + ERR_INVMSR = - 13 , / * ! < " Invalid MSR " * / <nl> + } cpu_error_t ; <nl> + <nl> + / * * <nl> + * @ brief Internal structure , used in cpu_tsc_mark , cpu_tsc_unmark and <nl> + * cpu_clock_by_mark <nl> + * / <nl> + struct cpu_mark_t { <nl> + uint64_t tsc ; / * ! < Time - stamp from RDTSC * / <nl> + uint64_t sys_clock ; / * ! < In microsecond resolution * / <nl> + } ; <nl> + <nl> + / * * <nl> + * @ brief Returns the total number of CPUs even if CPUID is not present <nl> + * @ retval Number of CPUs available <nl> + * / <nl> + int cpuid_get_total_cpus ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Checks if the CPUID instruction is supported <nl> + * @ retval 1 if CPUID is present <nl> + * @ retval 0 the CPU doesn ' t have CPUID . <nl> + * / <nl> + int cpuid_present ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Executes the CPUID instruction <nl> + * @ param eax - the value of the EAX register when executing CPUID <nl> + * @ param regs - the results will be stored here . regs [ 0 ] = EAX , regs [ 1 ] = EBX , . . . <nl> + * @ note CPUID will be executed with EAX set to the given value and EBX , ECX , <nl> + * EDX set to zero . <nl> + * / <nl> + void cpu_exec_cpuid ( uint32_t eax , uint32_t * regs ) ; <nl> + <nl> + / * * <nl> + * @ brief Executes the CPUID instruction with the given input registers <nl> + * @ note This is just a bit more generic version of cpu_exec_cpuid - it allows <nl> + * you to control all the registers . <nl> + * @ param regs - Input / output . Prior to executing CPUID , EAX , EBX , ECX and <nl> + * EDX will be set to regs [ 0 ] , regs [ 1 ] , regs [ 2 ] and regs [ 3 ] . <nl> + * After CPUID , this array will contain the results . <nl> + * / <nl> + void cpu_exec_cpuid_ext ( uint32_t * regs ) ; <nl> + <nl> + / * * <nl> + * @ brief Obtains the raw CPUID data from the current CPU <nl> + * @ param data - a pointer to cpu_raw_data_t structure <nl> + * @ returns zero if successful , and some negative number on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + int cpuid_get_raw_data ( struct cpu_raw_data_t * data ) ; <nl> + <nl> + / * * <nl> + * @ brief Writes the raw CPUID data to a text file <nl> + * @ param data - a pointer to cpu_raw_data_t structure <nl> + * @ param filename - the path of the file , where the serialized data should be <nl> + * written . If empty , stdout will be used . <nl> + * @ note This is intended primarily for debugging . On some processor , which is <nl> + * not currently supported or not completely recognized by cpu_identify , <nl> + * one can still successfully get the raw data and write it to a file . <nl> + * libcpuid developers can later import this file and debug the detection <nl> + * code as if running on the actual hardware . <nl> + * The file is simple text format of " something = value " pairs . Version info <nl> + * is also written , but the format is not intended to be neither backward - <nl> + * nor forward compatible . <nl> + * @ returns zero if successful , and some negative number on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + int cpuid_serialize_raw_data ( struct cpu_raw_data_t * data , const char * filename ) ; <nl> + <nl> + / * * <nl> + * @ brief Reads raw CPUID data from file <nl> + * @ param data - a pointer to cpu_raw_data_t structure . The deserialized data will <nl> + * be written here . <nl> + * @ param filename - the path of the file , containing the serialized raw data . <nl> + * If empty , stdin will be used . <nl> + * @ note This function may fail , if the file is created by different version of <nl> + * the library . Also , see the notes on cpuid_serialize_raw_data . <nl> + * @ returns zero if successful , and some negative number on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + int cpuid_deserialize_raw_data ( struct cpu_raw_data_t * data , const char * filename ) ; <nl> + <nl> + / * * <nl> + * @ brief Identifies the CPU <nl> + * @ param raw - Input - a pointer to the raw CPUID data , which is obtained <nl> + * either by cpuid_get_raw_data or cpuid_deserialize_raw_data . <nl> + * Can also be NULL , in which case the functions calls <nl> + * cpuid_get_raw_data itself . <nl> + * @ param data - Output - the decoded CPU features / info is written here . <nl> + * @ note The function will not fail , even if some of the information <nl> + * cannot be obtained . Even when the CPU is new and thus unknown to <nl> + * libcpuid , some generic info , such as " AMD K9 family CPU " will be <nl> + * written to data . cpu_codename , and most other things , such as the <nl> + * CPU flags , cache sizes , etc . should be detected correctly anyway . <nl> + * However , the function CAN fail , if the CPU is completely alien to <nl> + * libcpuid . <nl> + * @ note While cpu_identify ( ) and cpuid_get_raw_data ( ) are fast for most <nl> + * purposes , running them several thousand times per second can hamper <nl> + * performance significantly . Specifically , avoid writing " cpu feature <nl> + * checker " wrapping function , which calls cpu_identify and returns the <nl> + * value of some flag , if that function is going to be called frequently . <nl> + * @ returns zero if successful , and some negative number on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + int cpu_identify ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) ; <nl> + <nl> + / * * <nl> + * @ brief Returns the short textual representation of a CPU flag <nl> + * @ param feature - the feature , whose textual representation is wanted . <nl> + * @ returns a constant string like " fpu " , " tsc " , " sse2 " , etc . <nl> + * @ note the names of the returned flags are compatible with those from <nl> + * / proc / cpuinfo in Linux , with the exception of ` tm_amd ' <nl> + * / <nl> + const char * cpu_feature_str ( cpu_feature_t feature ) ; <nl> + <nl> + / * * <nl> + * @ brief Returns textual description of the last error <nl> + * <nl> + * libcpuid stores an ` errno ' - style error status , whose description <nl> + * can be obtained with this function . <nl> + * @ note This function is not thread - safe <nl> + * @ see cpu_error_t <nl> + * / <nl> + const char * cpuid_error ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Executes RDTSC <nl> + * <nl> + * The RDTSC ( ReaD Time Stamp Counter ) instruction gives access to an <nl> + * internal 64 - bit counter , which usually increments at each clock cycle . <nl> + * This can be used for various timing routines , and as a very precise <nl> + * clock source . It is set to zero on system startup . Beware that may not <nl> + * increment at the same frequency as the CPU . Consecutive calls of RDTSC <nl> + * are , however , guaranteed to return monotonically - increasing values . <nl> + * <nl> + * @ param result - a pointer to a 64 - bit unsigned integer , where the TSC value <nl> + * will be stored <nl> + * <nl> + * @ note If 100 % compatibility is a concern , you must first check if the <nl> + * RDTSC instruction is present ( if it is not , your program will crash <nl> + * with " invalid opcode " exception ) . Only some very old processors ( i486 , <nl> + * early AMD K5 and some Cyrix CPUs ) lack that instruction - they should <nl> + * have become exceedingly rare these days . To verify RDTSC presence , <nl> + * run cpu_identify ( ) and check flags [ CPU_FEATURE_TSC ] . <nl> + * <nl> + * @ note The monotonically increasing nature of the TSC may be violated <nl> + * on SMP systems , if their TSC clocks run at different rate . If the OS <nl> + * doesn ' t account for that , the TSC drift may become arbitrary large . <nl> + * / <nl> + void cpu_rdtsc ( uint64_t * result ) ; <nl> + <nl> + / * * <nl> + * @ brief Store TSC and timing info <nl> + * <nl> + * This function stores the current TSC value and current <nl> + * time info from a precise OS - specific clock source in the cpu_mark_t <nl> + * structure . The sys_clock field contains time with microsecond resolution . <nl> + * The values can later be used to measure time intervals , number of clocks , <nl> + * FPU frequency , etc . <nl> + * @ see cpu_rdtsc <nl> + * <nl> + * @ param mark [ out ] - a pointer to a cpu_mark_t structure <nl> + * / <nl> + void cpu_tsc_mark ( struct cpu_mark_t * mark ) ; <nl> + <nl> + / * * <nl> + * @ brief Calculate TSC and timing difference <nl> + * <nl> + * @ param mark - input / output : a pointer to a cpu_mark_t sturcture , which has <nl> + * already been initialized by cpu_tsc_mark . The difference in <nl> + * TSC and time will be written here . <nl> + * <nl> + * This function calculates the TSC and time difference , by obtaining the <nl> + * current TSC and timing values and subtracting the contents of the ` mark ' <nl> + * structure from them . Results are written in the same structure . <nl> + * <nl> + * Example : <nl> + * @ code <nl> + * . . . <nl> + * struct cpu_mark_t mark ; <nl> + * cpu_tsc_mark ( & mark ) ; <nl> + * foo ( ) ; <nl> + * cpu_tsc_unmark ( & mark ) ; <nl> + * printf ( " Foo finished . Executed in % llu cycles and % llu usecs \ n " , <nl> + * mark . tsc , mark . sys_clock ) ; <nl> + * . . . <nl> + * @ endcode <nl> + * / <nl> + void cpu_tsc_unmark ( struct cpu_mark_t * mark ) ; <nl> + <nl> + / * * <nl> + * @ brief Calculates the CPU clock <nl> + * <nl> + * @ param mark - pointer to a cpu_mark_t structure , which has been initialized <nl> + * with cpu_tsc_mark and later ` stopped ' with cpu_tsc_unmark . <nl> + * <nl> + * @ note For reliable results , the marked time interval should be at least about <nl> + * 10 ms . <nl> + * <nl> + * @ returns the CPU clock frequency , in MHz . Due to measurement error , it will <nl> + * differ from the true value in a few least - significant bits . Accuracy depends <nl> + * on the timing interval - the more , the better . If the timing interval is <nl> + * insufficient , the result is - 1 . Also , see the comment on cpu_clock_measure <nl> + * for additional issues and pitfalls in using RDTSC for CPU frequency <nl> + * measurements . <nl> + * / <nl> + int cpu_clock_by_mark ( struct cpu_mark_t * mark ) ; <nl> + <nl> + / * * <nl> + * @ brief Returns the CPU clock , as reported by the OS <nl> + * <nl> + * This function uses OS - specific functions to obtain the CPU clock . It may <nl> + * differ from the true clock for several reasons : < br > < br > <nl> + * <nl> + * i ) The CPU might be in some power saving state , while the OS reports its <nl> + * full - power frequency , or vice - versa . < br > <nl> + * ii ) In some cases you can raise or lower the CPU frequency with overclocking <nl> + * utilities and the OS will not notice . <nl> + * <nl> + * @ returns the CPU clock frequency in MHz . If the OS is not ( yet ) supported <nl> + * or lacks the necessary reporting machinery , the return value is - 1 <nl> + * / <nl> + int cpu_clock_by_os ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Measure the CPU clock frequency <nl> + * <nl> + * @ param millis - How much time to waste in the busy - wait cycle . In millisecs . <nl> + * Useful values 10 - 1000 <nl> + * @ param quad_check - Do a more thorough measurement if nonzero <nl> + * ( see the explanation ) . <nl> + * <nl> + * The function performs a busy - wait cycle for the given time and calculates <nl> + * the CPU frequency by the difference of the TSC values . The accuracy of the <nl> + * calculation depends on the length of the busy - wait cycle : more is better , <nl> + * but 100ms should be enough for most purposes . <nl> + * <nl> + * While this will calculate the CPU frequency correctly in most cases , there are <nl> + * several reasons why it might be incorrect : < br > <nl> + * <nl> + * i ) RDTSC doesn ' t guarantee it will run at the same clock as the CPU . <nl> + * Apparently there aren ' t CPUs at the moment , but still , there ' s no <nl> + * guarantee . < br > <nl> + * ii ) The CPU might be in a low - frequency power saving mode , and the CPU <nl> + * might be switched to higher frequency at any time . If this happens <nl> + * during the measurement , the result can be anywhere between the <nl> + * low and high frequencies . Also , if you ' re interested in the <nl> + * high frequency value only , this function might return the low one <nl> + * instead . < br > <nl> + * iii ) On SMP systems exhibiting TSC drift ( see \ ref cpu_rdtsc ) <nl> + * <nl> + * the quad_check option will run four consecutive measurements and <nl> + * then return the average of the two most - consistent results . The total <nl> + * runtime of the function will still be ` millis ' - consider using <nl> + * a bit more time for the timing interval . <nl> + * <nl> + * Finally , for benchmarking / CPU intensive applications , the best strategy is <nl> + * to use the cpu_tsc_mark ( ) / cpu_tsc_unmark ( ) / cpu_clock_by_mark ( ) method . <nl> + * Begin by mark ( ) - ing about one second after application startup ( allowing the <nl> + * power - saving manager to kick in and rise the frequency during that time ) , <nl> + * then unmark ( ) just before application finishing . The result will most <nl> + * acurately represent at what frequency your app was running . <nl> + * <nl> + * @ returns the CPU clock frequency in MHz ( within some measurement error <nl> + * margin ) . If RDTSC is not supported , the result is - 1 . <nl> + * / <nl> + int cpu_clock_measure ( int millis , int quad_check ) ; <nl> + <nl> + / * * <nl> + * @ brief Measure the CPU clock frequency using instruction - counting <nl> + * <nl> + * @ param millis - how much time to allocate for each run , in milliseconds <nl> + * @ param runs - how many runs to perform <nl> + * <nl> + * The function performs a busy - wait cycle using a known number of " heavy " ( SSE ) <nl> + * instructions . These instructions run at ( more or less guaranteed ) 1 IPC rate , <nl> + * so by running a busy loop for a fixed amount of time , and measuring the <nl> + * amount of instructions done , the CPU clock is accurately measured . <nl> + * <nl> + * Of course , this function is still affected by the power - saving schemes , so <nl> + * the warnings as of cpu_clock_measure ( ) still apply . However , this function is <nl> + * immune to problems with detection , related to the Intel Nehalem ' s " Turbo " <nl> + * mode , where the internal clock is raised , but the RDTSC rate is unaffected . <nl> + * <nl> + * The function will run for about ( millis * runs ) milliseconds . <nl> + * You can make only a single busy - wait run ( runs = = 1 ) ; however , this can <nl> + * be affected by task scheduling ( which will break the counting ) , so allowing <nl> + * more than one run is recommended . As run length is not imperative for <nl> + * accurate readings ( e . g . , 50ms is sufficient ) , you can afford a lot of short <nl> + * runs , e . g . 10 runs of 50ms or 20 runs of 25ms . <nl> + * <nl> + * Recommended values - millis = 50 , runs = 4 . For more robustness , <nl> + * increase the number of runs . <nl> + * <nl> + * NOTE : on Bulldozer and later CPUs , the busy - wait cycle runs at 1 . 4 IPC , thus <nl> + * the results are skewed . This is corrected internally by dividing the resulting <nl> + * value by 1 . 4 . <nl> + * However , this only occurs if the thread is executed on a single CMT <nl> + * module - if there are other threads competing for resources , the results are <nl> + * unpredictable . Make sure you run cpu_clock_by_ic ( ) on a CPU that is free from <nl> + * competing threads , or if there are such threads , they shouldn ' t exceed the <nl> + * number of modules . On a Bulldozer X8 , that means 4 threads . <nl> + * <nl> + * @ returns the CPU clock frequency in MHz ( within some measurement error <nl> + * margin ) . If SSE is not supported , the result is - 1 . If the input parameters <nl> + * are incorrect , or some other internal fault is detected , the result is - 2 . <nl> + * / <nl> + int cpu_clock_by_ic ( int millis , int runs ) ; <nl> + <nl> + / * * <nl> + * @ brief Get the CPU clock frequency ( all - in - one method ) <nl> + * <nl> + * This is an all - in - one method for getting the CPU clock frequency . <nl> + * It tries to use the OS for that . If the OS doesn ' t have this info , it <nl> + * uses cpu_clock_measure with 200ms time interval and quadruple checking . <nl> + * <nl> + * @ returns the CPU clock frequency in MHz . If every possible method fails , <nl> + * the result is - 1 . <nl> + * / <nl> + int cpu_clock ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Returns the libcpuid version <nl> + * <nl> + * @ returns the string representation of the libcpuid version , like " 0 . 1 . 1 " <nl> + * / <nl> + const char * cpuid_lib_version ( void ) ; <nl> + <nl> + typedef void ( * libcpuid_warn_fn_t ) ( const char * msg ) ; <nl> + / * * <nl> + * @ brief Sets the warning print function <nl> + * <nl> + * In some cases , the internal libcpuid machinery would like to emit useful <nl> + * debug warnings . By default , these warnings are written to stderr . However , <nl> + * you can set a custom function that will receive those warnings . <nl> + * <nl> + * @ param warn_fun - the warning function you want to set . If NULL , warnings <nl> + * are disabled . The function takes const char * argument . <nl> + * <nl> + * @ returns the current warning function . You can use the return value to <nl> + * keep the previous warning function and restore it at your discretion . <nl> + * / <nl> + libcpuid_warn_fn_t cpuid_set_warn_function ( libcpuid_warn_fn_t warn_fun ) ; <nl> + <nl> + / * * <nl> + * @ brief Sets the verbosiness level <nl> + * <nl> + * When the verbosiness level is above zero , some functions might print <nl> + * diagnostic information about what are they doing . The higher the level is , <nl> + * the more detail is printed . Level zero is guaranteed to omit all such <nl> + * output . The output is written using the same machinery as the warnings , <nl> + * @ see cpuid_set_warn_function ( ) <nl> + * <nl> + * @ param level the desired verbosiness level . Useful values 0 . . 2 inclusive <nl> + * / <nl> + void cpuid_set_verbosiness_level ( int level ) ; <nl> + <nl> + <nl> + / * * <nl> + * @ brief a structure that holds a list of processor names <nl> + * / <nl> + struct cpu_list_t { <nl> + / * * Number of entries in the list * / <nl> + int num_entries ; <nl> + / * * Pointers to names . There will be num_entries of them * / <nl> + char * * names ; <nl> + } ; <nl> + <nl> + / * * <nl> + * @ brief Gets a list of all known CPU names from a specific vendor . <nl> + * <nl> + * This function compiles a list of all known CPU ( code ) names <nl> + * ( i . e . the possible values of cpu_id_t : : cpu_codename ) for the given vendor . <nl> + * <nl> + * There are about 100 entries for Intel and AMD , and a few for the other <nl> + * vendors . The list is written out in approximate chronological introduction <nl> + * order of the parts . <nl> + * <nl> + * @ param vendor the vendor to be queried <nl> + * @ param list [ out ] the resulting list will be written here . <nl> + * NOTE : As the memory is dynamically allocated , be sure to call <nl> + * cpuid_free_cpu_list ( ) after you ' re done with the data <nl> + * @ see cpu_list_t <nl> + * / <nl> + void cpuid_get_cpu_list ( cpu_vendor_t vendor , struct cpu_list_t * list ) ; <nl> + <nl> + / * * <nl> + * @ brief Frees a CPU list <nl> + * <nl> + * This function deletes all the memory associated with a CPU list , as obtained <nl> + * by cpuid_get_cpu_list ( ) <nl> + * <nl> + * @ param list - the list to be free ( ) ' d . <nl> + * / <nl> + void cpuid_free_cpu_list ( struct cpu_list_t * list ) ; <nl> + <nl> + / * * <nl> + * @ brief Starts / opens a driver , needed to read MSRs ( Model Specific Registers ) <nl> + * <nl> + * On systems that support it , this function will create a temporary <nl> + * system driver , that has privileges to execute the RDMSR instruction . <nl> + * After the driver is created , you can read MSRs by calling \ ref cpu_rdmsr <nl> + * <nl> + * @ returns a handle to the driver on success , and NULL on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + struct msr_driver_t ; <nl> + struct msr_driver_t * cpu_msr_driver_open ( void ) ; <nl> + <nl> + / * * <nl> + * @ brief Reads a Model - Specific Register ( MSR ) <nl> + * <nl> + * If the CPU has MSRs ( as indicated by the CPU_FEATURE_MSR flag ) , you can <nl> + * read a MSR with the given index by calling this function . <nl> + * <nl> + * There are several prerequisites you must do before reading MSRs : <nl> + * 1 ) You must ensure the CPU has RDMSR . Check the CPU_FEATURE_MSR flag <nl> + * in cpu_id_t : : flags <nl> + * 2 ) You must ensure that the CPU implements the specific MSR you intend to <nl> + * read . <nl> + * 3 ) You must open a MSR - reader driver . RDMSR is a privileged instruction and <nl> + * needs ring - 0 access in order to work . This temporary driver is created <nl> + * by calling \ ref cpu_msr_driver_open <nl> + * <nl> + * @ param handle - a handle to the MSR reader driver , as created by <nl> + * cpu_msr_driver_open <nl> + * @ param msr_index - the numeric ID of the MSR you want to read <nl> + * @ param result - a pointer to a 64 - bit integer , where the MSR value is stored <nl> + * <nl> + * @ returns zero if successful , and some negative number on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + int cpu_rdmsr ( struct msr_driver_t * handle , int msr_index , uint64_t * result ) ; <nl> + <nl> + <nl> + typedef enum { <nl> + INFO_MPERF , / * ! < Maximum performance frequency clock . This <nl> + is a counter , which increments as a <nl> + proportion of the actual processor speed * / <nl> + INFO_APERF , / * ! < Actual performance frequency clock . This <nl> + accumulates the core clock counts when the <nl> + core is active . * / <nl> + INFO_CUR_MULTIPLIER , / * ! < Current CPU : FSB ratio , multiplied by 100 . <nl> + e . g . , a CPU : FSB value of 18 . 5 reads as <nl> + 1850 . * / <nl> + INFO_MAX_MULTIPLIER , / * ! < Maxumum CPU : FSB ratio for this CPU , <nl> + multiplied by 100 * / <nl> + INFO_TEMPERATURE , / * ! < The current core temperature in Celsius * / <nl> + INFO_THROTTLING , / * ! < 1 if the current logical processor is <nl> + throttling . 0 if it is running normally . * / <nl> + } cpu_msrinfo_request_t ; <nl> + <nl> + / * * <nl> + * @ brief Reads extended CPU information from Model - Specific Registers . <nl> + * @ param handle - a handle to an open MSR driver , @ see cpu_msr_driver_open <nl> + * @ param which - which info field should be returned . A list of <nl> + * available information entities is listed in the <nl> + * cpu_msrinfo_request_t enum . <nl> + * @ retval - if the requested information is available for the current <nl> + * processor model , the respective value is returned . <nl> + * if no information is available , or the CPU doesn ' t support <nl> + * the query , the special value CPU_INVALID_VALUE is returned <nl> + * / <nl> + int cpu_msrinfo ( struct msr_driver_t * handle , cpu_msrinfo_request_t which ) ; <nl> + # define CPU_INVALID_VALUE 0x3fffffff <nl> + <nl> + / * * <nl> + * @ brief Closes an open MSR driver <nl> + * <nl> + * This function unloads the MSR driver opened by cpu_msr_driver_open and <nl> + * frees any resources associated with it . <nl> + * <nl> + * @ param handle - a handle to the MSR reader driver , as created by <nl> + * cpu_msr_driver_open <nl> + * <nl> + * @ returns zero if successful , and some negative number on error . <nl> + * The error message can be obtained by calling \ ref cpuid_error . <nl> + * @ see cpu_error_t <nl> + * / <nl> + int cpu_msr_driver_close ( struct msr_driver_t * handle ) ; <nl> + <nl> + # ifdef __cplusplus <nl> + } ; / * extern " C " * / <nl> + # endif <nl> + <nl> + <nl> + / * * @ } * / <nl> + <nl> + # endif / * __LIBCPUID_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . 8af4718c906 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / libcpuid_constants . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + / * * <nl> + * @ File libcpuid_constants . h <nl> + * @ Author Veselin Georgiev <nl> + * @ Brief Some limits and constants for libcpuid <nl> + * / <nl> + <nl> + # ifndef __LIBCPUID_CONSTANTS_H__ <nl> + # define __LIBCPUID_CONSTANTS_H__ <nl> + <nl> + # define VENDOR_STR_MAX 16 <nl> + # define BRAND_STR_MAX 64 <nl> + # define CPU_FLAGS_MAX 128 <nl> + # define MAX_CPUID_LEVEL 32 <nl> + # define MAX_EXT_CPUID_LEVEL 32 <nl> + # define MAX_INTELFN4_LEVEL 4 <nl> + # define MAX_INTELFN11_LEVEL 4 <nl> + # define CPU_HINTS_MAX 16 <nl> + <nl> + # endif / * __LIBCPUID_CONSTANTS_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . 6dd18a97724 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / libcpuid_types . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + / * * <nl> + * @ File libcpuid_types . h <nl> + * @ Author Veselin Georgiev <nl> + * @ Brief Type specifications for libcpuid . <nl> + * / <nl> + <nl> + # ifndef __LIBCPUID_TYPES_H__ <nl> + # define __LIBCPUID_TYPES_H__ <nl> + <nl> + # include < stdint . h > <nl> + <nl> + # endif / * __LIBCPUID_TYPES_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . c08f63a4d2a <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / libcpuid_util . c <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + <nl> + # include < stdio . h > <nl> + # include < stdlib . h > <nl> + # include < stdarg . h > <nl> + # include < string . h > <nl> + # include < ctype . h > <nl> + # include " libcpuid . h " <nl> + # include " libcpuid_util . h " <nl> + <nl> + int _current_verboselevel ; <nl> + <nl> + void match_features ( const struct feature_map_t * matchtable , int count , uint32_t reg , struct cpu_id_t * data ) <nl> + { <nl> + int i ; <nl> + for ( i = 0 ; i < count ; i + + ) <nl> + if ( reg & ( 1 < < matchtable [ i ] . bit ) ) <nl> + data - > flags [ matchtable [ i ] . feature ] = 1 ; <nl> + } <nl> + <nl> + static void default_warn ( const char * msg ) <nl> + { <nl> + fprintf ( stderr , " % s " , msg ) ; <nl> + } <nl> + <nl> + libcpuid_warn_fn_t _warn_fun = default_warn ; <nl> + <nl> + # if defined ( _MSC_VER ) <nl> + # define vsnprintf _vsnprintf <nl> + # endif <nl> + void warnf ( const char * format , . . . ) <nl> + { <nl> + char buff [ 1024 ] ; <nl> + va_list va ; <nl> + if ( ! _warn_fun ) return ; <nl> + va_start ( va , format ) ; <nl> + vsnprintf ( buff , sizeof ( buff ) , format , va ) ; <nl> + va_end ( va ) ; <nl> + _warn_fun ( buff ) ; <nl> + } <nl> + <nl> + void debugf ( int verboselevel , const char * format , . . . ) <nl> + { <nl> + char buff [ 1024 ] ; <nl> + va_list va ; <nl> + if ( verboselevel > _current_verboselevel ) return ; <nl> + va_start ( va , format ) ; <nl> + vsnprintf ( buff , sizeof ( buff ) , format , va ) ; <nl> + va_end ( va ) ; <nl> + _warn_fun ( buff ) ; <nl> + } <nl> + <nl> + static int score ( const struct match_entry_t * entry , const struct cpu_id_t * data , <nl> + int brand_code , int model_code ) <nl> + { <nl> + int res = 0 ; <nl> + if ( entry - > family = = data - > family ) res + + ; <nl> + if ( entry - > model = = data - > model ) res + + ; <nl> + if ( entry - > stepping = = data - > stepping ) res + + ; <nl> + if ( entry - > ext_family = = data - > ext_family ) res + + ; <nl> + if ( entry - > ext_model = = data - > ext_model ) res + + ; <nl> + if ( entry - > ncores = = data - > num_cores ) res + + ; <nl> + if ( entry - > l2cache = = data - > l2_cache ) res + + ; <nl> + if ( entry - > l3cache = = data - > l3_cache ) res + + ; <nl> + if ( entry - > brand_code = = brand_code ) res + + ; <nl> + if ( entry - > model_code = = model_code ) res + + ; <nl> + return res ; <nl> + } <nl> + <nl> + void match_cpu_codename ( const struct match_entry_t * matchtable , int count , <nl> + struct cpu_id_t * data , int brand_code , int model_code ) <nl> + { <nl> + int bestscore = - 1 ; <nl> + int bestindex = 0 ; <nl> + int i , t ; <nl> + <nl> + debugf ( 3 , " Matching cpu f : % d , m : % d , s : % d , xf : % d , xm : % d , ncore : % d , l2 : % d , bcode : % d , code : % d \ n " , <nl> + data - > family , data - > model , data - > stepping , data - > ext_family , <nl> + data - > ext_model , data - > num_cores , data - > l2_cache , brand_code , model_code ) ; <nl> + <nl> + for ( i = 0 ; i < count ; i + + ) { <nl> + t = score ( & matchtable [ i ] , data , brand_code , model_code ) ; <nl> + debugf ( 3 , " Entry % d , ` % s ' , score % d \ n " , i , matchtable [ i ] . name , t ) ; <nl> + if ( t > bestscore ) { <nl> + debugf ( 2 , " Entry ` % s ' selected - best score so far ( % d ) \ n " , matchtable [ i ] . name , t ) ; <nl> + bestscore = t ; <nl> + bestindex = i ; <nl> + } <nl> + } <nl> + strcpy ( data - > cpu_codename , matchtable [ bestindex ] . name ) ; <nl> + } <nl> + <nl> + void generic_get_cpu_list ( const struct match_entry_t * matchtable , int count , <nl> + struct cpu_list_t * list ) <nl> + { <nl> + int i , j , n , good ; <nl> + n = 0 ; <nl> + list - > names = ( char * * ) malloc ( sizeof ( char * ) * count ) ; <nl> + for ( i = 0 ; i < count ; i + + ) { <nl> + if ( strstr ( matchtable [ i ] . name , " Unknown " ) ) continue ; <nl> + good = 1 ; <nl> + for ( j = n - 1 ; j > = 0 ; j - - ) <nl> + if ( ! strcmp ( list - > names [ j ] , matchtable [ i ] . name ) ) { <nl> + good = 0 ; <nl> + break ; <nl> + } <nl> + if ( ! good ) continue ; <nl> + list - > names [ n + + ] = strdup ( matchtable [ i ] . name ) ; <nl> + } <nl> + list - > num_entries = n ; <nl> + } <nl> + <nl> + static int xmatch_entry ( char c , const char * p ) <nl> + { <nl> + int i , j ; <nl> + if ( c = = 0 ) return - 1 ; <nl> + if ( c = = p [ 0 ] ) return 1 ; <nl> + if ( p [ 0 ] = = ' . ' ) return 1 ; <nl> + if ( p [ 0 ] = = ' # ' & & isdigit ( c ) ) return 1 ; <nl> + if ( p [ 0 ] = = ' [ ' ) { <nl> + j = 1 ; <nl> + while ( p [ j ] & & p [ j ] ! = ' ] ' ) j + + ; <nl> + if ( ! p [ j ] ) return - 1 ; <nl> + for ( i = 1 ; i < j ; i + + ) <nl> + if ( p [ i ] = = c ) return j + 1 ; <nl> + } <nl> + return - 1 ; <nl> + } <nl> + <nl> + int match_pattern ( const char * s , const char * p ) <nl> + { <nl> + int i , j , dj , k , n , m ; <nl> + n = ( int ) strlen ( s ) ; <nl> + m = ( int ) strlen ( p ) ; <nl> + for ( i = 0 ; i < n ; i + + ) { <nl> + if ( xmatch_entry ( s [ i ] , p ) ! = - 1 ) { <nl> + j = 0 ; <nl> + k = 0 ; <nl> + while ( j < m & & ( ( dj = xmatch_entry ( s [ i + k ] , p + j ) ) ! = - 1 ) ) { <nl> + k + + ; <nl> + j + = dj ; <nl> + } <nl> + if ( j = = m ) return i + 1 ; <nl> + } <nl> + } <nl> + return 0 ; <nl> + } <nl> + <nl> + struct cpu_id_t * get_cached_cpuid ( void ) <nl> + { <nl> + static int initialized = 0 ; <nl> + static struct cpu_id_t id ; <nl> + if ( initialized ) return & id ; <nl> + if ( cpu_identify ( NULL , & id ) ) <nl> + memset ( & id , 0 , sizeof ( id ) ) ; <nl> + initialized = 1 ; <nl> + return & id ; <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 34e1efe960a <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / libcpuid_util . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # ifndef __LIBCPUID_UTIL_H__ <nl> + # define __LIBCPUID_UTIL_H__ <nl> + <nl> + # define COUNT_OF ( array ) ( sizeof ( array ) / sizeof ( array [ 0 ] ) ) <nl> + <nl> + struct feature_map_t { <nl> + unsigned bit ; <nl> + cpu_feature_t feature ; <nl> + } ; <nl> + <nl> + void match_features ( const struct feature_map_t * matchtable , int count , <nl> + uint32_t reg , struct cpu_id_t * data ) ; <nl> + <nl> + struct match_entry_t { <nl> + int family , model , stepping , ext_family , ext_model ; <nl> + int ncores , l2cache , l3cache , brand_code , model_code ; <nl> + char name [ 32 ] ; <nl> + } ; <nl> + <nl> + void match_cpu_codename ( const struct match_entry_t * matchtable , int count , <nl> + struct cpu_id_t * data , int brand_code , int model_code ) ; <nl> + <nl> + void warnf ( const char * format , . . . ) <nl> + # ifdef __GNUC__ <nl> + __attribute__ ( ( format ( printf , 1 , 2 ) ) ) <nl> + # endif <nl> + ; <nl> + void debugf ( int verboselevel , const char * format , . . . ) <nl> + # ifdef __GNUC__ <nl> + __attribute__ ( ( format ( printf , 2 , 3 ) ) ) <nl> + # endif <nl> + ; <nl> + void generic_get_cpu_list ( const struct match_entry_t * matchtable , int count , <nl> + struct cpu_list_t * list ) ; <nl> + <nl> + / * <nl> + * Seek for a pattern in ` haystack ' . <nl> + * Pattern may be an fixed string , or contain the special metacharacters <nl> + * ' . ' - match any single character <nl> + * ' # ' - match any digit <nl> + * ' [ < chars > ] - match any of the given chars ( regex - like ranges are not <nl> + * supported ) <nl> + * Return val : 0 if the pattern is not found . Nonzero if it is found ( actually , <nl> + * x + 1 where x is the index where the match is found ) . <nl> + * / <nl> + int match_pattern ( const char * haystack , const char * pattern ) ; <nl> + <nl> + / * <nl> + * Gets an initialized cpu_id_t . It is cached , so that internal libcpuid <nl> + * machinery doesn ' t need to issue cpu_identify more than once . <nl> + * / <nl> + struct cpu_id_t * get_cached_cpuid ( void ) ; <nl> + <nl> + / * <nl> + * Sets the current errno <nl> + * / <nl> + int set_error ( cpu_error_t err ) ; <nl> + <nl> + extern libcpuid_warn_fn_t _warn_fun ; <nl> + extern int _current_verboselevel ; <nl> + <nl> + # endif / * __LIBCPUID_UTIL_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . 5930681561a <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / rdtsc . c <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # include < stdio . h > <nl> + # include < string . h > <nl> + # include " libcpuid . h " <nl> + # include " libcpuid_util . h " <nl> + # include " asm - bits . h " <nl> + # include " rdtsc . h " <nl> + <nl> + # ifdef _WIN32 <nl> + # include < windows . h > <nl> + void sys_precise_clock ( uint64_t * result ) <nl> + { <nl> + double c , f ; <nl> + LARGE_INTEGER freq , counter ; <nl> + QueryPerformanceCounter ( & counter ) ; <nl> + QueryPerformanceFrequency ( & freq ) ; <nl> + c = ( double ) counter . QuadPart ; <nl> + f = ( double ) freq . QuadPart ; <nl> + * result = ( uint64_t ) ( c * 1000000 . 0 / f ) ; <nl> + } <nl> + # else <nl> + / * assuming Linux , Mac OS or other POSIX * / <nl> + # include < sys / time . h > <nl> + void sys_precise_clock ( uint64_t * result ) <nl> + { <nl> + struct timeval tv ; <nl> + gettimeofday ( & tv , NULL ) ; <nl> + * result = ( uint64_t ) tv . tv_sec * ( uint64_t ) 1000000 + <nl> + ( uint64_t ) tv . tv_usec ; <nl> + } <nl> + # endif / * _WIN32 * / <nl> + <nl> + / * out = a - b * / <nl> + static void mark_t_subtract ( struct cpu_mark_t * a , struct cpu_mark_t * b , struct cpu_mark_t * out ) <nl> + { <nl> + out - > tsc = a - > tsc - b - > tsc ; <nl> + out - > sys_clock = a - > sys_clock - b - > sys_clock ; <nl> + } <nl> + <nl> + void cpu_tsc_mark ( struct cpu_mark_t * mark ) <nl> + { <nl> + cpu_rdtsc ( & mark - > tsc ) ; <nl> + sys_precise_clock ( & mark - > sys_clock ) ; <nl> + } <nl> + <nl> + void cpu_tsc_unmark ( struct cpu_mark_t * mark ) <nl> + { <nl> + struct cpu_mark_t temp ; <nl> + cpu_tsc_mark ( & temp ) ; <nl> + mark_t_subtract ( & temp , mark , mark ) ; <nl> + } <nl> + <nl> + <nl> + int cpu_clock_by_mark ( struct cpu_mark_t * mark ) <nl> + { <nl> + uint64_t result ; <nl> + <nl> + / * Check if some subtraction resulted in a negative number : * / <nl> + if ( ( mark - > tsc > > 63 ) ! = 0 | | ( mark - > sys_clock > > 63 ) ! = 0 ) return - 1 ; <nl> + <nl> + / * Divide - by - zero check : * / <nl> + if ( mark - > sys_clock = = 0 ) return - 1 ; <nl> + <nl> + / * Check if the result fits in 32bits * / <nl> + result = mark - > tsc / mark - > sys_clock ; <nl> + if ( result > ( uint64_t ) 0x7fffffff ) return - 1 ; <nl> + return ( int ) result ; <nl> + } <nl> + <nl> + # ifdef _WIN32 <nl> + int cpu_clock_by_os ( void ) <nl> + { <nl> + HKEY key ; <nl> + DWORD result ; <nl> + DWORD size = 4 ; <nl> + <nl> + if ( RegOpenKeyEx ( HKEY_LOCAL_MACHINE , TEXT ( " HARDWARE \ \ DESCRIPTION \ \ System \ \ CentralProcessor \ \ 0 " ) , 0 , KEY_READ , & key ) ! = ERROR_SUCCESS ) <nl> + return - 1 ; <nl> + <nl> + if ( RegQueryValueEx ( key , TEXT ( " ~ MHz " ) , NULL , NULL , ( LPBYTE ) & result , ( LPDWORD ) & size ) ! = ERROR_SUCCESS ) { <nl> + RegCloseKey ( key ) ; <nl> + return - 1 ; <nl> + } <nl> + RegCloseKey ( key ) ; <nl> + <nl> + return ( int ) result ; <nl> + } <nl> + # else <nl> + # ifdef __APPLE__ <nl> + # include < sys / types . h > <nl> + # include < sys / sysctl . h > <nl> + / * Assuming Mac OS X with hw . cpufrequency sysctl * / <nl> + int cpu_clock_by_os ( void ) <nl> + { <nl> + long long result = - 1 ; <nl> + size_t size = sizeof ( result ) ; <nl> + if ( sysctlbyname ( " hw . cpufrequency " , & result , & size , NULL , 0 ) ) <nl> + return - 1 ; <nl> + return ( int ) ( result / ( long long ) 1000000 ) ; <nl> + } <nl> + # else <nl> + / * Assuming Linux with / proc / cpuinfo * / <nl> + int cpu_clock_by_os ( void ) <nl> + { <nl> + FILE * f ; <nl> + char line [ 1024 ] , * s ; <nl> + int result ; <nl> + <nl> + f = fopen ( " / proc / cpuinfo " , " rt " ) ; <nl> + if ( ! f ) return - 1 ; <nl> + <nl> + while ( fgets ( line , sizeof ( line ) , f ) ) { <nl> + if ( ! strncmp ( line , " cpu MHz " , 7 ) ) { <nl> + s = strchr ( line , ' : ' ) ; <nl> + if ( s & & 1 = = sscanf ( s , " : % d . " , & result ) ) { <nl> + fclose ( f ) ; <nl> + return result ; <nl> + } <nl> + } <nl> + } <nl> + fclose ( f ) ; <nl> + return - 1 ; <nl> + } <nl> + # endif / * __APPLE__ * / <nl> + # endif / * _WIN32 * / <nl> + <nl> + / * Emulate doing useful CPU intensive work * / <nl> + static int busy_loop ( int amount ) <nl> + { <nl> + int i , j , k , s = 0 ; <nl> + static volatile int data [ 42 ] = { 32 , 12 , - 1 , 5 , 23 , 0 } ; <nl> + for ( i = 0 ; i < amount ; i + + ) <nl> + for ( j = 0 ; j < 65536 ; j + + ) <nl> + for ( k = 0 ; k < 42 ; k + + ) <nl> + s + = data [ k ] ; <nl> + return s ; <nl> + } <nl> + <nl> + int busy_loop_delay ( int milliseconds ) <nl> + { <nl> + int cycles = 0 , r = 0 , first = 1 ; <nl> + uint64_t a , b , c ; <nl> + sys_precise_clock ( & a ) ; <nl> + while ( 1 ) { <nl> + sys_precise_clock ( & c ) ; <nl> + if ( ( c - a ) / 1000 > milliseconds ) return r ; <nl> + r + = busy_loop ( cycles ) ; <nl> + if ( first ) { <nl> + first = 0 ; <nl> + } else { <nl> + if ( c - b < 1000 ) cycles * = 2 ; <nl> + if ( c - b > 10000 ) cycles / = 2 ; <nl> + } <nl> + b = c ; <nl> + } <nl> + } <nl> + <nl> + int cpu_clock_measure ( int millis , int quad_check ) <nl> + { <nl> + struct cpu_mark_t begin [ 4 ] , end [ 4 ] , temp , temp2 ; <nl> + int results [ 4 ] , cycles , n , k , i , j , bi , bj , mdiff , diff , _zero = 0 ; <nl> + uint64_t tl ; <nl> + <nl> + if ( millis < 1 ) return - 1 ; <nl> + tl = millis * ( uint64_t ) 1000 ; <nl> + if ( quad_check ) <nl> + tl / = 4 ; <nl> + n = quad_check ? 4 : 1 ; <nl> + cycles = 1 ; <nl> + for ( k = 0 ; k < n ; k + + ) { <nl> + cpu_tsc_mark ( & begin [ k ] ) ; <nl> + end [ k ] = begin [ k ] ; <nl> + do { <nl> + / * Run busy loop , and fool the compiler that we USE the garbishy <nl> + value it calculates * / <nl> + _zero | = ( 1 & busy_loop ( cycles ) ) ; <nl> + cpu_tsc_mark ( & temp ) ; <nl> + mark_t_subtract ( & temp , & end [ k ] , & temp2 ) ; <nl> + / * If busy loop is too short , increase it * / <nl> + if ( temp2 . sys_clock < tl / 8 ) <nl> + cycles * = 2 ; <nl> + end [ k ] = temp ; <nl> + } while ( end [ k ] . sys_clock - begin [ k ] . sys_clock < tl ) ; <nl> + mark_t_subtract ( & end [ k ] , & begin [ k ] , & temp ) ; <nl> + results [ k ] = cpu_clock_by_mark ( & temp ) ; <nl> + } <nl> + if ( n = = 1 ) return results [ 0 ] ; <nl> + mdiff = 0x7fffffff ; <nl> + bi = bj = - 1 ; <nl> + for ( i = 0 ; i < 4 ; i + + ) { <nl> + for ( j = i + 1 ; j < 4 ; j + + ) { <nl> + diff = results [ i ] - results [ j ] ; <nl> + if ( diff < 0 ) diff = - diff ; <nl> + if ( diff < mdiff ) { <nl> + mdiff = diff ; <nl> + bi = i ; <nl> + bj = j ; <nl> + } <nl> + } <nl> + } <nl> + if ( results [ bi ] = = - 1 ) return - 1 ; <nl> + return ( results [ bi ] + results [ bj ] + _zero ) / 2 ; <nl> + } <nl> + <nl> + int cpu_clock_by_ic ( int millis , int runs ) <nl> + { <nl> + int max_value = 0 , cur_value , i , ri , cycles_inner , cycles_outer , c ; <nl> + struct cpu_id_t * id ; <nl> + uint64_t t0 , t1 , tl , hz ; <nl> + int multiplier_numerator = 1 , multiplier_denom = 1 ; <nl> + if ( millis < = 0 | | runs < = 0 ) return - 2 ; <nl> + id = get_cached_cpuid ( ) ; <nl> + / / if there aren ' t SSE instructions - we can ' t run the test at all <nl> + if ( ! id | | ! id - > flags [ CPU_FEATURE_SSE ] ) return - 1 ; <nl> + / / <nl> + if ( id - > sse_size < 128 ) { <nl> + debugf ( 1 , " SSE execution path is 64 - bit \ n " ) ; <nl> + / / on a CPU with half SSE unit length , SSE instructions execute at 0 . 5 IPC ; <nl> + / / the resulting value must be multiplied by 2 : <nl> + multiplier_numerator = 2 ; <nl> + } else { <nl> + debugf ( 1 , " SSE execution path is 128 - bit \ n " ) ; <nl> + } <nl> + / / <nl> + / / on a Bulldozer or later CPU , SSE instructions execute at 1 . 4 IPC , handle that as well : <nl> + if ( id - > vendor = = VENDOR_AMD & & id - > ext_family > = 21 ) { <nl> + debugf ( 1 , " cpu_clock_by_ic : Bulldozer ( or later ) detected , dividing result by 1 . 4 \ n " ) ; <nl> + multiplier_numerator = 5 ; <nl> + multiplier_denom = 7 ; / / multiply by 5 / 7 , to divide by 1 . 4 <nl> + } <nl> + / / <nl> + tl = millis * 125 ; / / ( * 1000 / 8 ) <nl> + cycles_inner = 128 ; <nl> + cycles_outer = 1 ; <nl> + do { <nl> + if ( cycles_inner < 1000000000 ) cycles_inner * = 2 ; <nl> + else cycles_outer * = 2 ; <nl> + sys_precise_clock ( & t0 ) ; <nl> + for ( i = 0 ; i < cycles_outer ; i + + ) <nl> + busy_sse_loop ( cycles_inner ) ; <nl> + sys_precise_clock ( & t1 ) ; <nl> + } while ( t1 - t0 < tl ) ; <nl> + debugf ( 2 , " inner : % d , outer : % d \ n " , cycles_inner , cycles_outer ) ; <nl> + for ( ri = 0 ; ri < runs ; ri + + ) { <nl> + sys_precise_clock ( & t0 ) ; <nl> + c = 0 ; <nl> + do { <nl> + c + + ; <nl> + for ( i = 0 ; i < cycles_outer ; i + + ) <nl> + busy_sse_loop ( cycles_inner ) ; <nl> + sys_precise_clock ( & t1 ) ; <nl> + } while ( t1 - t0 < tl * ( uint64_t ) 8 ) ; <nl> + / / cpu_Hz = cycles_inner * cycles_outer * 256 / ( t1 - t0 ) * 1000000 <nl> + debugf ( 2 , " c = % d , td = % d \ n " , c , ( int ) ( t1 - t0 ) ) ; <nl> + hz = ( ( uint64_t ) cycles_inner * ( uint64_t ) 256 + 12 ) * <nl> + ( uint64_t ) cycles_outer * ( uint64_t ) multiplier_numerator * ( uint64_t ) c * ( uint64_t ) 1000000 <nl> + / ( ( t1 - t0 ) * ( uint64_t ) multiplier_denom ) ; <nl> + cur_value = ( int ) ( hz / 1000000 ) ; <nl> + if ( cur_value > max_value ) max_value = cur_value ; <nl> + } <nl> + return max_value ; <nl> + } <nl> + <nl> + int cpu_clock ( void ) <nl> + { <nl> + int result ; <nl> + result = cpu_clock_by_os ( ) ; <nl> + if ( result < = 0 ) <nl> + result = cpu_clock_measure ( 200 , 1 ) ; <nl> + return result ; <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . b4aaf99a570 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / rdtsc . h <nl> <nl> + / * <nl> + * Copyright 2010 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # ifndef __RDTSC_H__ <nl> + # define __RDTSC_H__ <nl> + <nl> + void sys_precise_clock ( uint64_t * result ) ; <nl> + int busy_loop_delay ( int milliseconds ) ; <nl> + <nl> + <nl> + # endif / * __RDTSC_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . c5390b9fd24 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / recog_amd . c <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + <nl> + # include < stdio . h > <nl> + # include < string . h > <nl> + # include < ctype . h > <nl> + # include " libcpuid . h " <nl> + # include " recog_amd . h " <nl> + # include " libcpuid_util . h " <nl> + <nl> + enum _amd_code_t { <nl> + NA , <nl> + NO_CODE , <nl> + OPTERON_GENERIC , <nl> + OPTERON_800 , <nl> + ATHLON_XP , <nl> + ATHLON_XP_M , <nl> + ATHLON_XP_M_LV , <nl> + ATHLON , <nl> + ATHLON_MP , <nl> + MOBILE_ATHLON64 , <nl> + ATHLON_FX , <nl> + DURON , <nl> + DURON_MP , <nl> + MOBILE_DURON , <nl> + MOBILE_SEMPRON , <nl> + OPTERON_SINGLE , <nl> + OPTERON_DUALCORE , <nl> + OPTERON_800_DUALCORE , <nl> + MOBILE_TURION , <nl> + ATHLON_64 , <nl> + ATHLON_64_FX , <nl> + TURION_64 , <nl> + TURION_X2 , <nl> + SEMPRON , <nl> + M_SEMPRON , <nl> + SEMPRON_DUALCORE , <nl> + PHENOM , <nl> + PHENOM2 , <nl> + ATHLON_64_X2 , <nl> + ATHLON_64_X3 , <nl> + ATHLON_64_X4 , <nl> + FUSION_C , <nl> + FUSION_E , <nl> + FUSION_EA , <nl> + FUSION_Z , <nl> + } ; <nl> + typedef enum _amd_code_t amd_code_t ; <nl> + <nl> + const struct match_entry_t cpudb_amd [ ] = { <nl> + { - 1 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown AMD CPU " } , <nl> + <nl> + / * 486 and the likes * / <nl> + { 4 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown AMD 486 " } , <nl> + { 4 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " AMD 486DX2 " } , <nl> + { 4 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " AMD 486DX2WB " } , <nl> + { 4 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " AMD 486DX4 " } , <nl> + { 4 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " AMD 486DX4WB " } , <nl> + <nl> + / * Pentia clones * / <nl> + { 5 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown AMD 586 " } , <nl> + { 5 , 0 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K5 " } , <nl> + { 5 , 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K5 " } , <nl> + { 5 , 2 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K5 " } , <nl> + { 5 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K5 " } , <nl> + <nl> + / * The K6 * / <nl> + { 5 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K6 " } , <nl> + { 5 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K6 " } , <nl> + <nl> + { 5 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K6 - 2 " } , <nl> + { 5 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K6 - III " } , <nl> + { 5 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown K6 " } , <nl> + { 5 , 11 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown K6 " } , <nl> + { 5 , 12 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown K6 " } , <nl> + { 5 , 13 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " K6 - 2 + " } , <nl> + <nl> + / * Athlon et al . * / <nl> + { 6 , 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Athlon ( Slot - A ) " } , <nl> + { 6 , 2 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Athlon ( Slot - A ) " } , <nl> + { 6 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Duron ( Spitfire ) " } , <nl> + { 6 , 4 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Athlon ( ThunderBird ) " } , <nl> + <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Athlon " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON , 0 , " Athlon ( Palomino ) " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_MP , 0 , " Athlon MP ( Palomino ) " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , DURON , 0 , " Duron ( Palomino ) " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_XP , 0 , " Athlon XP " } , <nl> + <nl> + { 6 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Athlon XP " } , <nl> + { 6 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , DURON , 0 , " Duron ( Morgan ) " } , <nl> + <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Athlon XP " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON , 0 , " Athlon XP ( Thoroughbred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_XP , 0 , " Athlon XP ( Thoroughbred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , DURON , 0 , " Duron ( Applebred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , SEMPRON , 0 , " Sempron ( Thoroughbred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , 128 , - 1 , SEMPRON , 0 , " Sempron ( Thoroughbred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron ( Thoroughbred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_MP , 0 , " Athlon MP ( Thoroughbred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_XP_M , 0 , " Mobile Athlon ( T - Bred ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_XP_M_LV , 0 , " Mobile Athlon ( T - Bred ) " } , <nl> + <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Athlon XP ( Barton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , 512 , - 1 , ATHLON_XP , 0 , " Athlon XP ( Barton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , 512 , - 1 , SEMPRON , 0 , " Sempron ( Barton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron ( Thorton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , 256 , - 1 , ATHLON_XP , 0 , " Athlon XP ( Thorton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_MP , 0 , " Athlon MP ( Barton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_XP_M , 0 , " Mobile Athlon ( Barton ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , ATHLON_XP_M_LV , 0 , " Mobile Athlon ( Barton ) " } , <nl> + <nl> + / * K8 Architecture * / <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown K8 " } , <nl> + { 15 , - 1 , - 1 , 16 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown K9 " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown A64 " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , OPTERON_SINGLE , 0 , " Opteron " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 2 , - 1 , - 1 , OPTERON_DUALCORE , 0 , " Opteron ( Dual Core ) " } , <nl> + { 15 , 3 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , OPTERON_SINGLE , 0 , " Opteron " } , <nl> + { 15 , 3 , - 1 , 15 , - 1 , 2 , - 1 , - 1 , OPTERON_DUALCORE , 0 , " Opteron ( Dual Core ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 1024 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , ATHLON_FX , 0 , " Athlon FX " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , ATHLON_64_FX , 0 , " Athlon 64 FX " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 2 , 1024 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 512 , - 1 , TURION_64 , 0 , " Turion 64 ( 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 1024 , - 1 , TURION_64 , 0 , " Turion 64 ( 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 2 , 512 , - 1 , TURION_X2 , 0 , " Turion 64 X2 ( 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 2 , 1024 , - 1 , TURION_X2 , 0 , " Turion 64 X2 ( 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 128 , - 1 , SEMPRON , 0 , " A64 Sempron ( 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 256 , - 1 , SEMPRON , 0 , " A64 Sempron ( 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , 512 , - 1 , SEMPRON , 0 , " A64 Sempron ( 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4f , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Orleans / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x5f , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Orleans / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2f , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Venice / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2c , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Venice / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x1f , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Winchester / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x0c , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Newcastle / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x27 , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( San Diego / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x37 , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( San Diego / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x04 , 1 , 512 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( ClawHammer / 512K ) " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , 0x5f , 1 , 1024 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( Orleans / 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x27 , 1 , 1024 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( San Diego / 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x04 , 1 , 1024 , - 1 , ATHLON_64 , 0 , " Athlon 64 ( ClawHammer / 1024K ) " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , 0x4b , 2 , 256 , - 1 , SEMPRON_DUALCORE , 0 , " Athlon 64 X2 ( Windsor / 256K ) " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , 0x23 , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Toledo / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4b , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Windsor / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x43 , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Windsor / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x6b , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Brisbane / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2b , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Manchester / 512K ) " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , 0x23 , 2 , 1024 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Toledo / 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x43 , 2 , 1024 , - 1 , ATHLON_64_X2 , 0 , " Athlon 64 X2 ( Windsor / 1024K ) " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , 0x08 , 1 , 128 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Dublin / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x08 , 1 , 256 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Dublin / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x0c , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Paris ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x1c , 1 , 128 , - 1 , SEMPRON , 0 , " Sempron 64 ( Palermo / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x1c , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Palermo / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x1c , 1 , 128 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Sonora / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x1c , 1 , 256 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Sonora / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2c , 1 , 128 , - 1 , SEMPRON , 0 , " Sempron 64 ( Palermo / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2c , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Palermo / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2c , 1 , 128 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Albany / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2c , 1 , 256 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Albany / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2f , 1 , 128 , - 1 , SEMPRON , 0 , " Sempron 64 ( Palermo / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x2f , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Palermo / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4f , 1 , 128 , - 1 , SEMPRON , 0 , " Sempron 64 ( Manila / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4f , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Manila / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x5f , 1 , 128 , - 1 , SEMPRON , 0 , " Sempron 64 ( Manila / 128K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x5f , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Manila / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x6b , 2 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 Dual ( Sherman / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x6b , 2 , 512 , - 1 , SEMPRON , 0 , " Sempron 64 Dual ( Sherman / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x7f , 1 , 256 , - 1 , SEMPRON , 0 , " Sempron 64 ( Sparta / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x7f , 1 , 512 , - 1 , SEMPRON , 0 , " Sempron 64 ( Sparta / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4c , 1 , 256 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Keene / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4c , 1 , 512 , - 1 , M_SEMPRON , 0 , " Mobile Sempron 64 ( Keene / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 2 , - 1 , - 1 , SEMPRON_DUALCORE , 0 , " Sempron Dual Core " } , <nl> + <nl> + { 15 , - 1 , - 1 , 15 , 0x24 , 1 , 512 , - 1 , TURION_64 , 0 , " Turion 64 ( Lancaster / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x24 , 1 , 1024 , - 1 , TURION_64 , 0 , " Turion 64 ( Lancaster / 1024K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x48 , 2 , 256 , - 1 , TURION_X2 , 0 , " Turion X2 ( Taylor ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x48 , 2 , 512 , - 1 , TURION_X2 , 0 , " Turion X2 ( Trinidad ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x4c , 1 , 512 , - 1 , TURION_64 , 0 , " Turion 64 ( Richmond ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x68 , 2 , 256 , - 1 , TURION_X2 , 0 , " Turion X2 ( Tyler / 256K ) " } , <nl> + { 15 , - 1 , - 1 , 15 , 0x68 , 2 , 512 , - 1 , TURION_X2 , 0 , " Turion X2 ( Tyler / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 17 , 3 , 2 , 512 , - 1 , TURION_X2 , 0 , " Turion X2 ( Griffin / 512K ) " } , <nl> + { 15 , - 1 , - 1 , 17 , 3 , 2 , 1024 , - 1 , TURION_X2 , 0 , " Turion X2 ( Griffin / 1024K ) " } , <nl> + <nl> + / * K9 Architecture * / <nl> + { 15 , - 1 , - 1 , 16 , - 1 , 1 , - 1 , - 1 , PHENOM , 0 , " Unknown AMD Phenom " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 1 , - 1 , - 1 , PHENOM , 0 , " Phenom " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 3 , - 1 , - 1 , PHENOM , 0 , " Phenom X3 ( Toliman ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 4 , - 1 , - 1 , PHENOM , 0 , " Phenom X4 ( Agena ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 3 , 512 , - 1 , PHENOM , 0 , " Phenom X3 ( Toliman / 256K ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 3 , 512 , - 1 , PHENOM , 0 , " Phenom X3 ( Toliman / 512K ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 4 , 128 , - 1 , PHENOM , 0 , " Phenom X4 ( Agena / 128K ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 4 , 256 , - 1 , PHENOM , 0 , " Phenom X4 ( Agena / 256K ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 4 , 512 , - 1 , PHENOM , 0 , " Phenom X4 ( Agena / 512K ) " } , <nl> + { 15 , 2 , - 1 , 16 , - 1 , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon X2 ( Kuma ) " } , <nl> + / * Phenom II derivates : * / <nl> + { 15 , 4 , - 1 , 16 , - 1 , 4 , - 1 , - 1 , NO_CODE , 0 , " Phenom ( Deneb - based ) " } , <nl> + { 15 , 4 , - 1 , 16 , - 1 , 1 , 1024 , - 1 , SEMPRON , 0 , " Sempron ( Sargas ) " } , <nl> + { 15 , 4 , - 1 , 16 , - 1 , 2 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X2 ( Callisto ) " } , <nl> + { 15 , 4 , - 1 , 16 , - 1 , 3 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X3 ( Heka ) " } , <nl> + { 15 , 4 , - 1 , 16 , - 1 , 4 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X4 " } , <nl> + { 15 , 4 , - 1 , 16 , 4 , 4 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X4 ( Deneb ) " } , <nl> + { 15 , 5 , - 1 , 16 , 5 , 4 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X4 ( Deneb ) " } , <nl> + { 15 , 4 , - 1 , 16 , 10 , 4 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X4 ( Zosma ) " } , <nl> + { 15 , 4 , - 1 , 16 , 10 , 6 , 512 , - 1 , PHENOM2 , 0 , " Phenom II X6 ( Thuban ) " } , <nl> + <nl> + { 15 , 4 , - 1 , 16 , - 1 , 2 , 1024 , - 1 , ATHLON_64_X2 , 0 , " Athlon II X2 ( Regor ) " } , <nl> + { 15 , 4 , - 1 , 16 , - 1 , 2 , 512 , - 1 , ATHLON_64_X2 , 0 , " Athlon II X2 ( Regor ) " } , <nl> + { 15 , 5 , - 1 , 16 , 5 , 3 , 512 , - 1 , ATHLON_64_X3 , 0 , " Athlon II X3 ( Rana ) " } , <nl> + { 15 , 5 , - 1 , 16 , 5 , 4 , 512 , - 1 , ATHLON_64_X4 , 0 , " Athlon II X4 ( Propus ) " } , <nl> + / * 2011 CPUs with AMD fusion : * / <nl> + { 15 , - 1 , - 1 , 20 , 1 , 1 , 512 , - 1 , FUSION_C , 0 , " Brazos Ontario " } , <nl> + { 15 , - 1 , - 1 , 20 , 1 , 2 , 512 , - 1 , FUSION_C , 0 , " Brazos Ontario ( Dual - core ) " } , <nl> + { 15 , - 1 , - 1 , 20 , 1 , 1 , 512 , - 1 , FUSION_E , 0 , " Brazos Zacate " } , <nl> + { 15 , - 1 , - 1 , 20 , 1 , 2 , 512 , - 1 , FUSION_E , 0 , " Brazos Zacate ( Dual - core ) " } , <nl> + { 15 , - 1 , - 1 , 20 , 1 , 1 , 512 , - 1 , FUSION_Z , 0 , " Brazos Desna " } , <nl> + { 15 , - 1 , - 1 , 18 , 1 , 2 , 512 , - 1 , FUSION_EA , 0 , " Llano X2 " } , <nl> + { 15 , - 1 , - 1 , 18 , 1 , 2 , 1024 , - 1 , FUSION_EA , 0 , " Llano X2 " } , <nl> + { 15 , - 1 , - 1 , 18 , 1 , 3 , 1024 , - 1 , FUSION_EA , 0 , " Llano X3 " } , <nl> + { 15 , - 1 , - 1 , 18 , 1 , 4 , 1024 , - 1 , FUSION_EA , 0 , " Llano X4 " } , <nl> + <nl> + / * Newer Opterons : * / <nl> + { 15 , 9 , - 1 , 16 , 9 , 8 , - 1 , - 1 , OPTERON_GENERIC , 0 , " Magny - Cours Opteron " } , <nl> + <nl> + / * Bulldozer CPUs : * / <nl> + { 15 , - 1 , - 1 , 21 , 1 , 4 , 2048 , - 1 , NO_CODE , 0 , " Bulldozer X2 " } , <nl> + { 15 , - 1 , - 1 , 21 , 1 , 6 , 2048 , - 1 , NO_CODE , 0 , " Bulldozer X3 " } , <nl> + { 15 , - 1 , - 1 , 21 , 1 , 8 , 2048 , - 1 , NO_CODE , 0 , " Bulldozer X4 " } , <nl> + { 15 , - 1 , - 1 , 21 , 2 , 4 , 2048 , - 1 , NO_CODE , 0 , " Vishera X2 " } , <nl> + { 15 , - 1 , - 1 , 21 , 2 , 6 , 2048 , - 1 , NO_CODE , 0 , " Vishera X3 " } , <nl> + { 15 , - 1 , - 1 , 21 , 2 , 8 , 2048 , - 1 , NO_CODE , 0 , " Vishera X4 " } , <nl> + } ; <nl> + <nl> + <nl> + static void load_amd_features ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + const struct feature_map_t matchtable_edx81 [ ] = { <nl> + { 20 , CPU_FEATURE_NX } , <nl> + { 22 , CPU_FEATURE_MMXEXT } , <nl> + { 25 , CPU_FEATURE_FXSR_OPT } , <nl> + { 30 , CPU_FEATURE_3DNOWEXT } , <nl> + { 31 , CPU_FEATURE_3DNOW } , <nl> + } ; <nl> + const struct feature_map_t matchtable_ecx81 [ ] = { <nl> + { 1 , CPU_FEATURE_CMP_LEGACY } , <nl> + { 2 , CPU_FEATURE_SVM } , <nl> + { 5 , CPU_FEATURE_ABM } , <nl> + { 6 , CPU_FEATURE_SSE4A } , <nl> + { 7 , CPU_FEATURE_MISALIGNSSE } , <nl> + { 8 , CPU_FEATURE_3DNOWPREFETCH } , <nl> + { 9 , CPU_FEATURE_OSVW } , <nl> + { 10 , CPU_FEATURE_IBS } , <nl> + { 11 , CPU_FEATURE_XOP } , <nl> + { 12 , CPU_FEATURE_SKINIT } , <nl> + { 13 , CPU_FEATURE_WDT } , <nl> + { 16 , CPU_FEATURE_FMA4 } , <nl> + } ; <nl> + const struct feature_map_t matchtable_edx87 [ ] = { <nl> + { 0 , CPU_FEATURE_TS } , <nl> + { 1 , CPU_FEATURE_FID } , <nl> + { 2 , CPU_FEATURE_VID } , <nl> + { 3 , CPU_FEATURE_TTP } , <nl> + { 4 , CPU_FEATURE_TM_AMD } , <nl> + { 5 , CPU_FEATURE_STC } , <nl> + { 6 , CPU_FEATURE_100MHZSTEPS } , <nl> + { 7 , CPU_FEATURE_HWPSTATE } , <nl> + / * id 8 is handled in common * / <nl> + { 9 , CPU_FEATURE_CPB } , <nl> + { 10 , CPU_FEATURE_APERFMPERF } , <nl> + { 11 , CPU_FEATURE_PFI } , <nl> + { 12 , CPU_FEATURE_PA } , <nl> + } ; <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 0x80000001 ) { <nl> + match_features ( matchtable_edx81 , COUNT_OF ( matchtable_edx81 ) , raw - > ext_cpuid [ 1 ] [ 3 ] , data ) ; <nl> + match_features ( matchtable_ecx81 , COUNT_OF ( matchtable_ecx81 ) , raw - > ext_cpuid [ 1 ] [ 2 ] , data ) ; <nl> + } <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 0x80000001 ) <nl> + match_features ( matchtable_edx87 , COUNT_OF ( matchtable_edx87 ) , raw - > ext_cpuid [ 7 ] [ 3 ] , data ) ; <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 0x8000001a ) { <nl> + / * We have the extended info about SSE unit size * / <nl> + data - > detection_hints [ CPU_HINT_SSE_SIZE_AUTH ] = 1 ; <nl> + data - > sse_size = ( raw - > ext_cpuid [ 0x1a ] [ 0 ] & 1 ) ? 128 : 64 ; <nl> + } <nl> + } <nl> + <nl> + static void decode_amd_cache_info ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + int l3_result ; <nl> + const int assoc_table [ 16 ] = { <nl> + 0 , 1 , 2 , 0 , 4 , 0 , 8 , 0 , 16 , 0 , 32 , 48 , 64 , 92 , 128 , 255 <nl> + } ; <nl> + unsigned n = raw - > ext_cpuid [ 0 ] [ 0 ] ; <nl> + <nl> + if ( n > = 0x80000005 ) { <nl> + data - > l1_data_cache = ( raw - > ext_cpuid [ 5 ] [ 2 ] > > 24 ) & 0xff ; <nl> + data - > l1_assoc = ( raw - > ext_cpuid [ 5 ] [ 2 ] > > 16 ) & 0xff ; <nl> + data - > l1_cacheline = ( raw - > ext_cpuid [ 5 ] [ 2 ] ) & 0xff ; <nl> + data - > l1_instruction_cache = ( raw - > ext_cpuid [ 5 ] [ 3 ] > > 24 ) & 0xff ; <nl> + } <nl> + if ( n > = 0x80000006 ) { <nl> + data - > l2_cache = ( raw - > ext_cpuid [ 6 ] [ 2 ] > > 16 ) & 0xffff ; <nl> + data - > l2_assoc = assoc_table [ ( raw - > ext_cpuid [ 6 ] [ 2 ] > > 12 ) & 0xf ] ; <nl> + data - > l2_cacheline = ( raw - > ext_cpuid [ 6 ] [ 2 ] ) & 0xff ; <nl> + <nl> + l3_result = ( raw - > ext_cpuid [ 6 ] [ 3 ] > > 18 ) ; <nl> + if ( l3_result > 0 ) { <nl> + l3_result = 512 * l3_result ; / * AMD spec says it ' s a range , <nl> + but we take the lower bound * / <nl> + data - > l3_cache = l3_result ; <nl> + data - > l3_assoc = assoc_table [ ( raw - > ext_cpuid [ 6 ] [ 3 ] > > 12 ) & 0xf ] ; <nl> + data - > l3_cacheline = ( raw - > ext_cpuid [ 6 ] [ 3 ] ) & 0xff ; <nl> + } else { <nl> + data - > l3_cache = 0 ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + static void decode_amd_number_of_cores ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + int logical_cpus = - 1 , num_cores = - 1 ; <nl> + <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 1 ) { <nl> + logical_cpus = ( raw - > basic_cpuid [ 1 ] [ 1 ] > > 16 ) & 0xff ; <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 8 ) { <nl> + num_cores = 1 + ( raw - > ext_cpuid [ 8 ] [ 2 ] & 0xff ) ; <nl> + } <nl> + } <nl> + if ( data - > flags [ CPU_FEATURE_HT ] ) { <nl> + if ( num_cores > 1 ) { <nl> + data - > num_cores = num_cores ; <nl> + data - > num_logical_cpus = logical_cpus ; <nl> + } else { <nl> + data - > num_cores = 1 ; <nl> + data - > num_logical_cpus = ( logical_cpus > = 2 ? logical_cpus : 2 ) ; <nl> + } <nl> + } else { <nl> + data - > num_cores = data - > num_logical_cpus = 1 ; <nl> + } <nl> + } <nl> + <nl> + static int amd_has_turion_modelname ( const char * bs ) <nl> + { <nl> + / * We search for something like TL - 60 . Ahh , I miss regexes . . . * / <nl> + int i , l , k ; <nl> + char code [ 3 ] = { 0 } ; <nl> + const char * codes [ ] = { " ML " , " MT " , " MK " , " TK " , " TL " , " RM " , " ZM " , " " } ; <nl> + l = ( int ) strlen ( bs ) ; <nl> + for ( i = 3 ; i < l - 2 ; i + + ) { <nl> + if ( bs [ i ] = = ' - ' & & <nl> + isupper ( bs [ i - 1 ] ) & & isupper ( bs [ i - 2 ] ) & & ! isupper ( bs [ i - 3 ] ) & & <nl> + isdigit ( bs [ i + 1 ] ) & & isdigit ( bs [ i + 2 ] ) & & ! isdigit ( bs [ i + 3 ] ) ) <nl> + { <nl> + code [ 0 ] = bs [ i - 2 ] ; <nl> + code [ 1 ] = bs [ i - 1 ] ; <nl> + for ( k = 0 ; codes [ k ] [ 0 ] ; k + + ) <nl> + if ( ! strcmp ( codes [ k ] , code ) ) return 1 ; <nl> + } <nl> + } <nl> + return 0 ; <nl> + } <nl> + <nl> + static amd_code_t decode_amd_codename_part1 ( const char * bs ) <nl> + { <nl> + int is_dual = 0 , is_quad = 0 , is_tri = 0 ; <nl> + if ( strstr ( bs , " Dual Core " ) | | <nl> + strstr ( bs , " Dual - Core " ) | | <nl> + strstr ( bs , " X2 " ) ) <nl> + is_dual = 1 ; <nl> + if ( strstr ( bs , " X4 " ) ) is_quad = 1 ; <nl> + if ( strstr ( bs , " X3 " ) ) is_tri = 1 ; <nl> + if ( strstr ( bs , " Opteron " ) ) { <nl> + return is_dual ? OPTERON_DUALCORE : OPTERON_SINGLE ; <nl> + } <nl> + if ( strstr ( bs , " Phenom " ) ) { <nl> + if ( strstr ( bs , " II " ) ) return PHENOM2 ; <nl> + else return PHENOM ; <nl> + } <nl> + if ( amd_has_turion_modelname ( bs ) ) { <nl> + return is_dual ? TURION_X2 : TURION_64 ; <nl> + } <nl> + if ( strstr ( bs , " Athlon ( tm ) 64 FX " ) ) return ATHLON_64_FX ; <nl> + if ( strstr ( bs , " Athlon ( tm ) FX " ) ) return ATHLON_FX ; <nl> + if ( strstr ( bs , " Athlon ( tm ) 64 " ) | | strstr ( bs , " Athlon ( tm ) II X " ) | | match_pattern ( bs , " Athlon ( tm ) X # " ) ) { <nl> + if ( is_quad ) return ATHLON_64_X4 ; <nl> + if ( is_dual ) return ATHLON_64_X2 ; <nl> + if ( is_tri ) return ATHLON_64_X3 ; <nl> + return ATHLON_64 ; <nl> + } <nl> + if ( strstr ( bs , " Turion " ) ) { <nl> + return is_dual ? TURION_X2 : TURION_64 ; <nl> + } <nl> + <nl> + if ( strstr ( bs , " mobile " ) | | strstr ( bs , " Mobile " ) ) { <nl> + if ( strstr ( bs , " Athlon ( tm ) XP - M ( LV ) " ) ) return ATHLON_XP_M_LV ; <nl> + if ( strstr ( bs , " Athlon ( tm ) XP " ) ) return ATHLON_XP_M ; <nl> + if ( strstr ( bs , " Sempron ( tm ) " ) ) return M_SEMPRON ; <nl> + if ( strstr ( bs , " Athlon " ) ) return MOBILE_ATHLON64 ; <nl> + if ( strstr ( bs , " Duron " ) ) return MOBILE_DURON ; <nl> + <nl> + } else { <nl> + if ( strstr ( bs , " Athlon ( tm ) XP " ) ) return ATHLON_XP ; <nl> + if ( strstr ( bs , " Athlon ( tm ) MP " ) ) return ATHLON_MP ; <nl> + if ( strstr ( bs , " Sempron ( tm ) " ) ) return SEMPRON ; <nl> + if ( strstr ( bs , " Duron " ) ) return DURON ; <nl> + if ( strstr ( bs , " Athlon " ) ) return ATHLON ; <nl> + } <nl> + if ( match_pattern ( bs , " C - # # " ) ) return FUSION_C ; <nl> + if ( match_pattern ( bs , " E - # # # " ) ) return FUSION_E ; <nl> + if ( match_pattern ( bs , " Z - # # " ) ) return FUSION_Z ; <nl> + if ( match_pattern ( bs , " E # - # # # # " ) | | match_pattern ( bs , " A # - # # # # " ) ) return FUSION_EA ; <nl> + <nl> + return NO_CODE ; <nl> + } <nl> + <nl> + static void decode_amd_codename ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + amd_code_t code = decode_amd_codename_part1 ( data - > brand_str ) ; <nl> + <nl> + if ( code = = ATHLON_64_X2 & & data - > l2_cache < 512 ) <nl> + code = SEMPRON_DUALCORE ; <nl> + match_cpu_codename ( cpudb_amd , COUNT_OF ( cpudb_amd ) , data , code , 0 ) ; <nl> + } <nl> + <nl> + int cpuid_identify_amd ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + load_amd_features ( raw , data ) ; <nl> + decode_amd_cache_info ( raw , data ) ; <nl> + decode_amd_number_of_cores ( raw , data ) ; <nl> + decode_amd_codename ( raw , data ) ; <nl> + return 0 ; <nl> + } <nl> + <nl> + void cpuid_get_list_amd ( struct cpu_list_t * list ) <nl> + { <nl> + generic_get_cpu_list ( cpudb_amd , COUNT_OF ( cpudb_amd ) , list ) ; <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . e0f3b61f727 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / recog_amd . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # ifndef __RECOG_AMD_H__ <nl> + # define __RECOG_AMD_H__ <nl> + <nl> + int cpuid_identify_amd ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) ; <nl> + void cpuid_get_list_amd ( struct cpu_list_t * list ) ; <nl> + <nl> + # endif / * __RECOG_AMD_H__ * / <nl> new file mode 100644 <nl> index 00000000000 . . 625b2777f51 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / recog_intel . c <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # include < string . h > <nl> + # include < ctype . h > <nl> + # include " libcpuid . h " <nl> + # include " recog_intel . h " <nl> + # include " libcpuid_util . h " <nl> + <nl> + <nl> + enum _intel_code_t { <nl> + NA , <nl> + NO_CODE , <nl> + PENTIUM = 10 , <nl> + MOBILE_PENTIUM , <nl> + <nl> + XEON = 20 , <nl> + XEON_IRWIN , <nl> + XEONMP , <nl> + XEON_POTOMAC , <nl> + XEON_I7 , <nl> + XEON_GAINESTOWN , <nl> + XEON_WESTMERE , <nl> + <nl> + MOBILE_PENTIUM_M = 30 , <nl> + CELERON , <nl> + MOBILE_CELERON , <nl> + NOT_CELERON , <nl> + <nl> + <nl> + CORE_SOLO = 40 , <nl> + MOBILE_CORE_SOLO , <nl> + CORE_DUO , <nl> + MOBILE_CORE_DUO , <nl> + <nl> + WOLFDALE = 50 , <nl> + MEROM , <nl> + PENRYN , <nl> + QUAD_CORE , <nl> + DUAL_CORE_HT , <nl> + QUAD_CORE_HT , <nl> + MORE_THAN_QUADCORE , <nl> + PENTIUM_D , <nl> + <nl> + ATOM = 60 , <nl> + ATOM_SILVERTHORNE , <nl> + ATOM_DIAMONDVILLE , <nl> + ATOM_PINEVIEW , <nl> + ATOM_CEDARVIEW , <nl> + <nl> + CORE_I3 = 70 , <nl> + CORE_I5 , <nl> + CORE_I7 , <nl> + CORE_IVY3 , / * 22nm Core - iX * / <nl> + CORE_IVY5 , <nl> + CORE_IVY7 , <nl> + CORE_HASWELL3 , / * 22nm Core - iX , Haswell * / <nl> + CORE_HASWELL5 , <nl> + CORE_HASWELL7 , <nl> + } ; <nl> + typedef enum _intel_code_t intel_code_t ; <nl> + <nl> + enum _intel_model_t { <nl> + UNKNOWN = - 1 , <nl> + _3000 = 100 , <nl> + _3100 , <nl> + _3200 , <nl> + X3200 , <nl> + _3300 , <nl> + X3300 , <nl> + _5100 , <nl> + _5200 , <nl> + _5300 , <nl> + _5400 , <nl> + _2xxx , / * Core i [ 357 ] 2xxx * / <nl> + _3xxx , / * Core i [ 357 ] 3xxx * / <nl> + } ; <nl> + typedef enum _intel_model_t intel_model_t ; <nl> + <nl> + const struct match_entry_t cpudb_intel [ ] = { <nl> + { - 1 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Intel CPU " } , <nl> + <nl> + / * i486 * / <nl> + { 4 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown i486 " } , <nl> + { 4 , 0 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 DX - 25 / 33 " } , <nl> + { 4 , 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 DX - 50 " } , <nl> + { 4 , 2 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 SX " } , <nl> + { 4 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 DX2 " } , <nl> + { 4 , 4 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 SL " } , <nl> + { 4 , 5 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 SX2 " } , <nl> + { 4 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 DX2 WriteBack " } , <nl> + { 4 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 DX4 " } , <nl> + { 4 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " i486 DX4 WriteBack " } , <nl> + <nl> + / * All Pentia : <nl> + Pentium 1 * / <nl> + { 5 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Pentium " } , <nl> + { 5 , 0 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium A - Step " } , <nl> + { 5 , 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 1 ( 0 . 8u ) " } , <nl> + { 5 , 2 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 1 ( 0 . 35u ) " } , <nl> + { 5 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium OverDrive " } , <nl> + { 5 , 4 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 1 ( 0 . 35u ) " } , <nl> + { 5 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 1 ( 0 . 35u ) " } , <nl> + { 5 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium MMX ( 0 . 25u ) " } , <nl> + <nl> + / * Pentium 2 / 3 / M / Conroe / whatsnext - all P6 based . * / <nl> + { 6 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown P6 " } , <nl> + { 6 , 0 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium Pro " } , <nl> + { 6 , 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium Pro " } , <nl> + { 6 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium II ( Klamath ) " } , <nl> + { 6 , 5 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium II ( Deschutes ) " } , <nl> + { 6 , 5 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile Pentium II ( Tonga ) " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium II ( Dixon ) " } , <nl> + <nl> + { 6 , 3 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - II Xeon " } , <nl> + { 6 , 5 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - II Xeon " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - II Xeon " } , <nl> + <nl> + { 6 , 5 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - II Celeron ( no L2 ) " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - II Celeron ( 128K ) " } , <nl> + <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> + <nl> + { 6 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium III ( Katmai ) " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium III ( Coppermine ) " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium III ( Coppermine ) " } , <nl> + { 6 , 11 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium III ( Tualatin ) " } , <nl> + <nl> + { 6 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - III Xeon " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - III Xeon " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - III Xeon " } , <nl> + { 6 , 11 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " P - III Xeon " } , <nl> + <nl> + { 6 , 7 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - III Celeron " } , <nl> + { 6 , 8 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - III Celeron " } , <nl> + { 6 , 10 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - III Celeron " } , <nl> + { 6 , 11 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - III Celeron " } , <nl> + <nl> + / * Netburst based ( Pentium 4 and later ) <nl> + classic P4s * / <nl> + { 15 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Pentium 4 " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " Unknown P - 4 Celeron " } , <nl> + { 15 , - 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Unknown Xeon " } , <nl> + <nl> + { 15 , 0 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 4 ( Willamette ) " } , <nl> + { 15 , 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 4 ( Willamette ) " } , <nl> + { 15 , 2 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 4 ( Northwood ) " } , <nl> + { 15 , 3 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 4 ( Prescott ) " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 4 ( Prescott ) " } , <nl> + { 15 , 6 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium 4 ( Cedar Mill ) " } , <nl> + { 15 , 0 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile P - 4 ( Willamette ) " } , <nl> + { 15 , 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile P - 4 ( Willamette ) " } , <nl> + { 15 , 2 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile P - 4 ( Northwood ) " } , <nl> + { 15 , 3 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile P - 4 ( Prescott ) " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile P - 4 ( Prescott ) " } , <nl> + { 15 , 6 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM , 0 , " Mobile P - 4 ( Cedar Mill ) " } , <nl> + <nl> + / * server CPUs * / <nl> + { 15 , 0 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Foster ) " } , <nl> + { 15 , 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Foster ) " } , <nl> + { 15 , 2 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Prestonia ) " } , <nl> + { 15 , 2 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEONMP , 0 , " Xeon ( Gallatin ) " } , <nl> + { 15 , 3 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Nocona ) " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Nocona ) " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON_IRWIN , 0 , " Xeon ( Irwindale ) " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEONMP , 0 , " Xeon ( Cranford ) " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON_POTOMAC , 0 , " Xeon ( Potomac ) " } , <nl> + { 15 , 6 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Dempsey ) " } , <nl> + <nl> + / * Pentium Ds * / <nl> + { 15 , 4 , 4 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium D " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , PENTIUM_D , 0 , " Pentium D " } , <nl> + { 15 , 4 , 7 , 15 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Pentium D " } , <nl> + { 15 , 6 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , PENTIUM_D , 0 , " Pentium D " } , <nl> + <nl> + / * Celeron and Celeron Ds * / <nl> + { 15 , 1 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - 4 Celeron ( 128K ) " } , <nl> + { 15 , 2 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " P - 4 Celeron ( 128K ) " } , <nl> + { 15 , 3 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " Celeron D " } , <nl> + { 15 , 4 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " Celeron D " } , <nl> + { 15 , 6 , - 1 , 15 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " Celeron D " } , <nl> + <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> + / * Intel Core microarchitecture - P6 - based * / <nl> + <nl> + { 6 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Pentium M " } , <nl> + { 6 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM_M , 0 , " Unknown Pentium M " } , <nl> + { 6 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , PENTIUM , 0 , " Pentium M ( Banias ) " } , <nl> + { 6 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM_M , 0 , " Pentium M ( Banias ) " } , <nl> + { 6 , 9 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " Celeron M " } , <nl> + { 6 , 13 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , PENTIUM , 0 , " Pentium M ( Dothan ) " } , <nl> + { 6 , 13 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , MOBILE_PENTIUM_M , 0 , " Pentium M ( Dothan ) " } , <nl> + { 6 , 13 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CELERON , 0 , " Celeron M " } , <nl> + <nl> + { 6 , 12 , - 1 , - 1 , - 1 , - 1 , - 1 , - 1 , ATOM , 0 , " Unknown Atom " } , <nl> + { 6 , 12 , - 1 , - 1 , - 1 , - 1 , - 1 , - 1 , ATOM_DIAMONDVILLE , 0 , " Atom ( Diamondville ) " } , <nl> + { 6 , 12 , - 1 , - 1 , - 1 , - 1 , - 1 , - 1 , ATOM_SILVERTHORNE , 0 , " Atom ( Silverthorne ) " } , <nl> + { 6 , 12 , - 1 , - 1 , - 1 , - 1 , - 1 , - 1 , ATOM_CEDARVIEW , 0 , " Atom ( Cedarview ) " } , <nl> + { 6 , 6 , - 1 , - 1 , - 1 , - 1 , - 1 , - 1 , ATOM_CEDARVIEW , 0 , " Atom ( Cedarview ) " } , <nl> + { 6 , 12 , - 1 , - 1 , - 1 , - 1 , - 1 , - 1 , ATOM_PINEVIEW , 0 , " Atom ( Pineview ) " } , <nl> + <nl> + / * mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - - * / <nl> + <nl> + { 6 , 14 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Yonah " } , <nl> + { 6 , 14 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CORE_SOLO , 0 , " Yonah ( Core Solo ) " } , <nl> + { 6 , 14 , - 1 , - 1 , - 1 , 2 , - 1 , - 1 , CORE_DUO , 0 , " Yonah ( Core Duo ) " } , <nl> + { 6 , 14 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , MOBILE_CORE_SOLO , 0 , " Yonah ( Core Solo ) " } , <nl> + { 6 , 14 , - 1 , - 1 , - 1 , 2 , - 1 , - 1 , MOBILE_CORE_DUO , 0 , " Yonah ( Core Duo ) " } , <nl> + { 6 , 14 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , CORE_SOLO , 0 , " Yonah ( Core Solo ) " } , <nl> + <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Core 2 " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , 4096 , - 1 , CORE_DUO , 0 , " Conroe ( Core 2 Duo ) " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , 1024 , - 1 , CORE_DUO , 0 , " Conroe ( Core 2 Duo ) 1024K " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , 512 , - 1 , CORE_DUO , 0 , " Conroe ( Core 2 Duo ) 512K " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 4 , - 1 , - 1 , QUAD_CORE , 0 , " Kentsfield ( Core 2 Quad ) " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 4 , 4096 , - 1 , QUAD_CORE , 0 , " Kentsfield ( Core 2 Quad ) " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 400 , - 1 , - 1 , MORE_THAN_QUADCORE , 0 , " More than quad - core " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , 2048 , - 1 , CORE_DUO , 0 , " Allendale ( Core 2 Duo ) " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , - 1 , - 1 , MOBILE_CORE_DUO , 0 , " Merom ( Core 2 Duo ) " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , 2048 , - 1 , MEROM , 0 , " Merom ( Core 2 Duo ) 2048K " } , <nl> + { 6 , 15 , - 1 , - 1 , - 1 , 2 , 4096 , - 1 , MEROM , 0 , " Merom ( Core 2 Duo ) 4096K " } , <nl> + <nl> + { 6 , 15 , - 1 , - 1 , 15 , 1 , - 1 , - 1 , CELERON , 0 , " Conroe - L ( Celeron ) " } , <nl> + { 6 , 6 , - 1 , - 1 , 22 , 1 , - 1 , - 1 , CELERON , 0 , " Conroe - L ( Celeron ) " } , <nl> + { 6 , 15 , - 1 , - 1 , 15 , 2 , - 1 , - 1 , CELERON , 0 , " Conroe - L ( Allendale ) " } , <nl> + { 6 , 6 , - 1 , - 1 , 22 , 2 , - 1 , - 1 , CELERON , 0 , " Conroe - L ( Allendale ) " } , <nl> + <nl> + <nl> + { 6 , 6 , - 1 , - 1 , 22 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Core ? " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Core ? " } , <nl> + { 6 , 6 , - 1 , - 1 , 22 , 400 , - 1 , - 1 , MORE_THAN_QUADCORE , 0 , " More than quad - core " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 400 , - 1 , - 1 , MORE_THAN_QUADCORE , 0 , " More than quad - core " } , <nl> + <nl> + { 6 , 7 , - 1 , - 1 , 23 , 1 , - 1 , - 1 , CORE_SOLO , 0 , " Unknown Core 45nm " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 1 , - 1 , - 1 , CORE_DUO , 0 , " Unknown Core 45nm " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 1024 , - 1 , WOLFDALE , 0 , " Celeron Wolfdale 1M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 2048 , - 1 , WOLFDALE , 0 , " Wolfdale ( Core 2 Duo ) 2M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 3072 , - 1 , WOLFDALE , 0 , " Wolfdale ( Core 2 Duo ) 3M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 6144 , - 1 , WOLFDALE , 0 , " Wolfdale ( Core 2 Duo ) 6M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 1 , - 1 , - 1 , MOBILE_CORE_DUO , 0 , " Penryn ( Core 2 Duo ) " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 3072 , - 1 , PENRYN , 0 , " Penryn ( Core 2 Duo ) 3M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 6144 , - 1 , PENRYN , 0 , " Penryn ( Core 2 Duo ) 6M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 4 , 2048 , - 1 , QUAD_CORE , 0 , " Yorkfield ( Core 2 Quad ) 2M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 4 , 3072 , - 1 , QUAD_CORE , 0 , " Yorkfield ( Core 2 Quad ) 3M " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 4 , 6144 , - 1 , QUAD_CORE , 0 , " Yorkfield ( Core 2 Quad ) 6M " } , <nl> + <nl> + { 6 , 5 , - 1 , - 1 , 37 , 2 , - 1 , - 1 , NO_CODE , 0 , " Unknown Core i3 / i5 CPU " } , <nl> + { 6 , 5 , - 1 , - 1 , 37 , 2 , - 1 , 4096 , CORE_I7 , 0 , " Arrandale ( Core i7 ) " } , <nl> + { 6 , 5 , - 1 , - 1 , 37 , 2 , - 1 , 3072 , CORE_I5 , 0 , " Arrandale ( Core i5 ) " } , <nl> + { 6 , 5 , - 1 , - 1 , 37 , 2 , - 1 , 4096 , CORE_I5 , 0 , " Clarkdale ( Core i5 ) " } , <nl> + { 6 , 5 , - 1 , - 1 , 37 , 4 , - 1 , 8192 , CORE_I5 , 0 , " Lynnfield ( Core i5 ) " } , <nl> + { 6 , 5 , - 1 , - 1 , 37 , 2 , - 1 , 3072 , CORE_I3 , 0 , " Arrandale ( Core i3 ) " } , <nl> + { 6 , 5 , - 1 , - 1 , 37 , 2 , - 1 , 4096 , CORE_I3 , 0 , " Clarkdale ( Core i3 ) " } , <nl> + <nl> + { 6 , 10 , - 1 , - 1 , 42 , - 1 , - 1 , - 1 , NO_CODE , 0 , " Unknown Sandy Bridge " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , - 1 , - 1 , - 1 , CORE_I7 , 0 , " Sandy Bridge i7 " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , 4 , - 1 , - 1 , CORE_I7 , 0 , " Sandy Bridge ( Core i7 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , 4 , - 1 , - 1 , CORE_I5 , 0 , " Sandy Bridge ( Core i5 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , 2 , - 1 , - 1 , CORE_I3 , 0 , " Sandy Bridge ( Core i3 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , 1 , - 1 , - 1 , CELERON , 0 , " Celeron ( Sandy Bridge ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , 2 , - 1 , - 1 , CELERON , 0 , " Celeron ( Sandy Bridge ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 42 , 2 , - 1 , - 1 , PENTIUM , 0 , " Pentium ( Sandy Bridge ) " } , <nl> + <nl> + { 6 , 10 , - 1 , - 1 , 26 , 1 , - 1 , - 1 , CORE_I7 , 0 , " Intel Core i7 " } , <nl> + { 6 , 10 , - 1 , - 1 , 26 , 4 , - 1 , - 1 , CORE_I7 , 0 , " Bloomfield ( Core i7 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 30 , 4 , - 1 , - 1 , CORE_I7 , 0 , " Lynnfield ( Core i7 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 26 , 4 , - 1 , - 1 , XEON_I7 , 0 , " Xeon ( Bloomfield ) " } , <nl> + <nl> + { 6 , 10 , - 1 , - 1 , 26 , 4 , - 1 , - 1 , XEON_GAINESTOWN , 0 , " Xeon ( Gainestown ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 26 , 4 , - 1 , 4096 , XEON_GAINESTOWN , 0 , " Xeon ( Gainestown ) 4M " } , <nl> + { 6 , 10 , - 1 , - 1 , 26 , 4 , - 1 , 8192 , XEON_GAINESTOWN , 0 , " Xeon ( Gainestown ) 8M " } , <nl> + <nl> + { 6 , 12 , - 1 , - 1 , 44 , - 1 , - 1 , - 1 , XEON_WESTMERE , 0 , " Xeon ( Westmere - based ) " } , <nl> + { 6 , 12 , - 1 , - 1 , 44 , 4 , - 1 , 12288 , CORE_I7 , 0 , " Gulftown ( Core i7 ) " } , <nl> + { 6 , 12 , - 1 , - 1 , 44 , - 1 , - 1 , 12288 , XEON_WESTMERE , 0 , " Xeon ( Gulftown ) " } , <nl> + <nl> + { 6 , 13 , - 1 , - 1 , 45 , - 1 , - 1 , - 1 , XEON , 0 , " Xeon ( Sandy Bridge ) " } , <nl> + <nl> + { 6 , 13 , - 1 , - 1 , 45 , - 1 , - 1 , - 1 , CORE_I7 , 0 , " Sandy Bridge - E ( Core i7 ) " } , <nl> + { 6 , 13 , - 1 , - 1 , 45 , - 1 , - 1 , - 1 , CORE_I5 , 0 , " Sandy Bridge - E ( Core i5 ) " } , <nl> + { 6 , 13 , - 1 , - 1 , 45 , - 1 , - 1 , - 1 , CORE_I3 , 0 , " Sandy Bridge - E ( Core i3 ) " } , <nl> + <nl> + { 6 , 10 , - 1 , - 1 , 58 , 4 , - 1 , - 1 , CORE_IVY7 , 0 , " Ivy Bridge ( Core i7 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 58 , 4 , - 1 , - 1 , CORE_IVY5 , 0 , " Ivy Bridge ( Core i5 ) " } , <nl> + { 6 , 10 , - 1 , - 1 , 58 , 2 , - 1 , - 1 , CORE_IVY3 , 0 , " Ivy Bridge ( Core i3 ) " } , <nl> + <nl> + { 6 , 12 , - 1 , - 1 , 60 , 4 , - 1 , - 1 , CORE_HASWELL7 , 0 , " Haswell ( Core i7 ) " } , <nl> + { 6 , 12 , - 1 , - 1 , 60 , 4 , - 1 , - 1 , CORE_HASWELL5 , 0 , " Haswell ( Core i5 ) " } , <nl> + { 6 , 12 , - 1 , - 1 , 60 , 2 , - 1 , - 1 , CORE_HASWELL3 , 0 , " Haswell ( Core i3 ) " } , <nl> + <nl> + <nl> + / * Core microarchitecture - based Xeons : * / <nl> + { 6 , 14 , - 1 , - 1 , 14 , 1 , - 1 , - 1 , XEON , 0 , " Xeon LV " } , <nl> + { 6 , 15 , - 1 , - 1 , 15 , 2 , 4096 , - 1 , XEON , _5100 , " Xeon ( Woodcrest ) " } , <nl> + { 6 , 15 , - 1 , - 1 , 15 , 2 , 2048 , - 1 , XEON , _3000 , " Xeon ( Conroe / 2M ) " } , <nl> + { 6 , 15 , - 1 , - 1 , 15 , 2 , 4096 , - 1 , XEON , _3000 , " Xeon ( Conroe / 4M ) " } , <nl> + { 6 , 15 , - 1 , - 1 , 15 , 4 , 4096 , - 1 , XEON , X3200 , " Xeon ( Kentsfield ) " } , <nl> + { 6 , 15 , - 1 , - 1 , 15 , 4 , 4096 , - 1 , XEON , _5300 , " Xeon ( Clovertown ) " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 6144 , - 1 , XEON , _3100 , " Xeon ( Wolfdale ) " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 2 , 6144 , - 1 , XEON , _5200 , " Xeon ( Wolfdale DP ) " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 4 , 6144 , - 1 , XEON , _5400 , " Xeon ( Harpertown ) " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 4 , 3072 , - 1 , XEON , X3300 , " Xeon ( Yorkfield / 3M ) " } , <nl> + { 6 , 7 , - 1 , - 1 , 23 , 4 , 6144 , - 1 , XEON , X3300 , " Xeon ( Yorkfield / 6M ) " } , <nl> + <nl> + / * Itaniums * / <nl> + { 7 , - 1 , - 1 , - 1 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Itanium " } , <nl> + { 15 , - 1 , - 1 , 16 , - 1 , 1 , - 1 , - 1 , NO_CODE , 0 , " Itanium 2 " } , <nl> + <nl> + } ; <nl> + <nl> + <nl> + static void load_intel_features ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + const struct feature_map_t matchtable_edx1 [ ] = { <nl> + { 18 , CPU_FEATURE_PN } , <nl> + { 21 , CPU_FEATURE_DTS } , <nl> + { 22 , CPU_FEATURE_ACPI } , <nl> + { 27 , CPU_FEATURE_SS } , <nl> + { 29 , CPU_FEATURE_TM } , <nl> + { 30 , CPU_FEATURE_IA64 } , <nl> + { 31 , CPU_FEATURE_PBE } , <nl> + } ; <nl> + const struct feature_map_t matchtable_ecx1 [ ] = { <nl> + { 1 , CPU_FEATURE_PCLMUL } , <nl> + { 2 , CPU_FEATURE_DTS64 } , <nl> + { 4 , CPU_FEATURE_DS_CPL } , <nl> + { 5 , CPU_FEATURE_VMX } , <nl> + { 6 , CPU_FEATURE_SMX } , <nl> + { 7 , CPU_FEATURE_EST } , <nl> + { 8 , CPU_FEATURE_TM2 } , <nl> + { 10 , CPU_FEATURE_CID } , <nl> + { 14 , CPU_FEATURE_XTPR } , <nl> + { 15 , CPU_FEATURE_PDCM } , <nl> + { 18 , CPU_FEATURE_DCA } , <nl> + { 20 , CPU_FEATURE_SSE4_2 } , <nl> + { 22 , CPU_FEATURE_MOVBE } , <nl> + { 25 , CPU_FEATURE_AES } , <nl> + { 26 , CPU_FEATURE_XSAVE } , <nl> + { 27 , CPU_FEATURE_OSXSAVE } , <nl> + { 28 , CPU_FEATURE_AVX } , <nl> + { 30 , CPU_FEATURE_RDRAND } , <nl> + } ; <nl> + const struct feature_map_t matchtable_ebx7 [ ] = { <nl> + { 5 , CPU_FEATURE_AVX2 } , <nl> + } ; <nl> + const struct feature_map_t matchtable_edx81 [ ] = { <nl> + { 20 , CPU_FEATURE_XD } , <nl> + } ; <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 1 ) { <nl> + match_features ( matchtable_edx1 , COUNT_OF ( matchtable_edx1 ) , raw - > basic_cpuid [ 1 ] [ 3 ] , data ) ; <nl> + match_features ( matchtable_ecx1 , COUNT_OF ( matchtable_ecx1 ) , raw - > basic_cpuid [ 1 ] [ 2 ] , data ) ; <nl> + } <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 7 ) { <nl> + match_features ( matchtable_ebx7 , COUNT_OF ( matchtable_ebx7 ) , raw - > basic_cpuid [ 7 ] [ 1 ] , data ) ; <nl> + } <nl> + if ( raw - > ext_cpuid [ 0 ] [ 0 ] > = 1 ) { <nl> + match_features ( matchtable_edx81 , COUNT_OF ( matchtable_edx81 ) , raw - > ext_cpuid [ 1 ] [ 3 ] , data ) ; <nl> + } <nl> + } <nl> + <nl> + enum _cache_type_t { <nl> + L1I , <nl> + L1D , <nl> + L2 , <nl> + L3 <nl> + } ; <nl> + typedef enum _cache_type_t cache_type_t ; <nl> + <nl> + static void check_case ( uint8_t on , cache_type_t cache , int size , int assoc , int linesize , struct cpu_id_t * data ) <nl> + { <nl> + if ( ! on ) return ; <nl> + switch ( cache ) { <nl> + case L1I : <nl> + data - > l1_instruction_cache = size ; <nl> + break ; <nl> + case L1D : <nl> + data - > l1_data_cache = size ; <nl> + data - > l1_assoc = assoc ; <nl> + data - > l1_cacheline = linesize ; <nl> + break ; <nl> + case L2 : <nl> + data - > l2_cache = size ; <nl> + data - > l2_assoc = assoc ; <nl> + data - > l2_cacheline = linesize ; <nl> + break ; <nl> + case L3 : <nl> + data - > l3_cache = size ; <nl> + data - > l3_assoc = assoc ; <nl> + data - > l3_cacheline = linesize ; <nl> + default : <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + static void decode_intel_oldstyle_cache_info ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + uint8_t f [ 256 ] = { 0 } ; <nl> + int reg , off ; <nl> + uint32_t x ; <nl> + for ( reg = 0 ; reg < 4 ; reg + + ) { <nl> + x = raw - > basic_cpuid [ 2 ] [ reg ] ; <nl> + if ( x & 0x80000000 ) continue ; <nl> + for ( off = 0 ; off < 4 ; off + + ) { <nl> + f [ x & 0xff ] = 1 ; <nl> + x > > = 8 ; <nl> + } <nl> + } <nl> + <nl> + check_case ( f [ 0x06 ] , L1I , 8 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x08 ] , L1I , 16 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x0A ] , L1D , 8 , 2 , 32 , data ) ; <nl> + check_case ( f [ 0x0C ] , L1D , 16 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x22 ] , L3 , 512 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x23 ] , L3 , 1024 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x25 ] , L3 , 2048 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x29 ] , L3 , 4096 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x2C ] , L1D , 32 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x30 ] , L1I , 32 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x39 ] , L2 , 128 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x3A ] , L2 , 192 , 6 , 64 , data ) ; <nl> + check_case ( f [ 0x3B ] , L2 , 128 , 2 , 64 , data ) ; <nl> + check_case ( f [ 0x3C ] , L2 , 256 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x3D ] , L2 , 384 , 6 , 64 , data ) ; <nl> + check_case ( f [ 0x3E ] , L2 , 512 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x41 ] , L2 , 128 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x42 ] , L2 , 256 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x43 ] , L2 , 512 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x44 ] , L2 , 1024 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x45 ] , L2 , 2048 , 4 , 32 , data ) ; <nl> + check_case ( f [ 0x46 ] , L3 , 4096 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x47 ] , L3 , 8192 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x4A ] , L3 , 6144 , 12 , 64 , data ) ; <nl> + check_case ( f [ 0x4B ] , L3 , 8192 , 16 , 64 , data ) ; <nl> + check_case ( f [ 0x4C ] , L3 , 12288 , 12 , 64 , data ) ; <nl> + check_case ( f [ 0x4D ] , L3 , 16384 , 16 , 64 , data ) ; <nl> + check_case ( f [ 0x4E ] , L2 , 6144 , 24 , 64 , data ) ; <nl> + check_case ( f [ 0x60 ] , L1D , 16 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x66 ] , L1D , 8 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x67 ] , L1D , 16 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x68 ] , L1D , 32 , 4 , 64 , data ) ; <nl> + / * The following four entries are trace cache . Intel does not <nl> + * specify a cache - line size , so we use - 1 instead <nl> + * / <nl> + check_case ( f [ 0x70 ] , L1I , 12 , 8 , - 1 , data ) ; <nl> + check_case ( f [ 0x71 ] , L1I , 16 , 8 , - 1 , data ) ; <nl> + check_case ( f [ 0x72 ] , L1I , 32 , 8 , - 1 , data ) ; <nl> + check_case ( f [ 0x73 ] , L1I , 64 , 8 , - 1 , data ) ; <nl> + <nl> + check_case ( f [ 0x78 ] , L2 , 1024 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x79 ] , L2 , 128 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x7A ] , L2 , 256 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x7B ] , L2 , 512 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x7C ] , L2 , 1024 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x7D ] , L2 , 2048 , 8 , 64 , data ) ; <nl> + check_case ( f [ 0x7F ] , L2 , 512 , 2 , 64 , data ) ; <nl> + check_case ( f [ 0x82 ] , L2 , 256 , 8 , 32 , data ) ; <nl> + check_case ( f [ 0x83 ] , L2 , 512 , 8 , 32 , data ) ; <nl> + check_case ( f [ 0x84 ] , L2 , 1024 , 8 , 32 , data ) ; <nl> + check_case ( f [ 0x85 ] , L2 , 2048 , 8 , 32 , data ) ; <nl> + check_case ( f [ 0x86 ] , L2 , 512 , 4 , 64 , data ) ; <nl> + check_case ( f [ 0x87 ] , L2 , 1024 , 8 , 64 , data ) ; <nl> + <nl> + if ( f [ 0x49 ] ) { <nl> + / * This flag is overloaded with two meanings . On Xeon MP <nl> + * ( family 0xf , model 0x6 ) this means L3 cache . On all other <nl> + * CPUs ( notably Conroe et al ) , this is L2 cache . In both cases <nl> + * it means 4MB , 16 - way associative , 64 - byte line size . <nl> + * / <nl> + if ( data - > family = = 0xf & & data - > model = = 0x6 ) { <nl> + data - > l3_cache = 4096 ; <nl> + data - > l3_assoc = 16 ; <nl> + data - > l3_cacheline = 64 ; <nl> + } else { <nl> + data - > l2_cache = 4096 ; <nl> + data - > l2_assoc = 16 ; <nl> + data - > l2_cacheline = 64 ; <nl> + } <nl> + } <nl> + if ( f [ 0x40 ] ) { <nl> + / * Again , a special flag . It means : <nl> + * 1 ) If no L2 is specified , then CPU is w / o L2 ( 0 KB ) <nl> + * 2 ) If L2 is specified by other flags , then , CPU is w / o L3 . <nl> + * / <nl> + if ( data - > l2_cache = = - 1 ) { <nl> + data - > l2_cache = 0 ; <nl> + } else { <nl> + data - > l3_cache = 0 ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + static void decode_intel_deterministic_cache_info ( struct cpu_raw_data_t * raw , <nl> + struct cpu_id_t * data ) <nl> + { <nl> + int ecx ; <nl> + int ways , partitions , linesize , sets , size , level , typenumber ; <nl> + cache_type_t type ; <nl> + for ( ecx = 0 ; ecx < MAX_INTELFN4_LEVEL ; ecx + + ) { <nl> + typenumber = raw - > intel_fn4 [ ecx ] [ 0 ] & 0x1f ; <nl> + if ( typenumber = = 0 ) break ; <nl> + level = ( raw - > intel_fn4 [ ecx ] [ 0 ] > > 5 ) & 0x7 ; <nl> + if ( level = = 1 & & typenumber = = 1 ) <nl> + type = L1D ; <nl> + else if ( level = = 1 & & typenumber = = 2 ) <nl> + type = L1I ; <nl> + else if ( level = = 2 & & typenumber = = 3 ) <nl> + type = L2 ; <nl> + else if ( level = = 3 & & typenumber = = 3 ) <nl> + type = L3 ; <nl> + else { <nl> + warnf ( " deterministic_cache : unknown level / typenumber combo ( % d / % d ) , cannot \ n " , level , typenumber ) ; <nl> + warnf ( " deterministic_cache : recognize cache type \ n " ) ; <nl> + continue ; <nl> + } <nl> + ways = ( ( raw - > intel_fn4 [ ecx ] [ 1 ] > > 22 ) & 0x3ff ) + 1 ; <nl> + partitions = ( ( raw - > intel_fn4 [ ecx ] [ 1 ] > > 12 ) & 0x3ff ) + 1 ; <nl> + linesize = ( raw - > intel_fn4 [ ecx ] [ 1 ] & 0xfff ) + 1 ; <nl> + sets = raw - > intel_fn4 [ ecx ] [ 2 ] + 1 ; <nl> + size = ways * partitions * linesize * sets / 1024 ; <nl> + check_case ( 1 , type , size , ways , linesize , data ) ; <nl> + } <nl> + } <nl> + <nl> + static int decode_intel_extended_topology ( struct cpu_raw_data_t * raw , <nl> + struct cpu_id_t * data ) <nl> + { <nl> + int i , level_type , num_smt = - 1 , num_core = - 1 ; <nl> + for ( i = 0 ; i < MAX_INTELFN11_LEVEL ; i + + ) { <nl> + level_type = ( raw - > intel_fn11 [ i ] [ 2 ] & 0xff00 ) > > 8 ; <nl> + switch ( level_type ) { <nl> + case 0x01 : <nl> + num_smt = raw - > intel_fn11 [ i ] [ 1 ] & 0xffff ; <nl> + break ; <nl> + case 0x02 : <nl> + num_core = raw - > intel_fn11 [ i ] [ 1 ] & 0xffff ; <nl> + break ; <nl> + default : <nl> + break ; <nl> + } <nl> + } <nl> + if ( num_smt = = - 1 | | num_core = = - 1 ) return 0 ; <nl> + data - > num_cores = num_core / num_smt ; <nl> + data - > num_logical_cpus = num_core ; <nl> + return 1 ; <nl> + } <nl> + <nl> + static void decode_intel_number_of_cores ( struct cpu_raw_data_t * raw , <nl> + struct cpu_id_t * data ) <nl> + { <nl> + int logical_cpus = - 1 , num_cores = - 1 ; <nl> + <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 11 ) { <nl> + if ( decode_intel_extended_topology ( raw , data ) ) return ; <nl> + } <nl> + <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 1 ) { <nl> + logical_cpus = ( raw - > basic_cpuid [ 1 ] [ 1 ] > > 16 ) & 0xff ; <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 4 ) { <nl> + num_cores = 1 + ( ( raw - > basic_cpuid [ 4 ] [ 0 ] > > 26 ) & 0x3f ) ; <nl> + } <nl> + } <nl> + if ( data - > flags [ CPU_FEATURE_HT ] ) { <nl> + if ( num_cores > 1 ) { <nl> + data - > num_cores = num_cores ; <nl> + data - > num_logical_cpus = logical_cpus ; <nl> + } else { <nl> + data - > num_cores = 1 ; <nl> + data - > num_logical_cpus = ( logical_cpus > = 2 ? logical_cpus : 2 ) ; <nl> + } <nl> + } else { <nl> + data - > num_cores = data - > num_logical_cpus = 1 ; <nl> + } <nl> + } <nl> + <nl> + static intel_code_t get_brand_code ( struct cpu_id_t * data ) <nl> + { <nl> + intel_code_t code = NO_CODE ; <nl> + int i , need_matchtable = 1 , core_ix_base = 0 ; <nl> + const char * bs = data - > brand_str ; <nl> + const char * s ; <nl> + const struct { intel_code_t c ; const char * search ; } matchtable [ ] = { <nl> + { XEONMP , " Xeon MP " } , <nl> + { XEONMP , " Xeon ( TM ) MP " } , <nl> + { XEON , " Xeon " } , <nl> + { CELERON , " Celeron " } , <nl> + { MOBILE_PENTIUM_M , " Pentium ( R ) M " } , <nl> + { CORE_SOLO , " Pentium ( R ) Dual CPU " } , <nl> + { PENTIUM_D , " Pentium ( R ) D " } , <nl> + { PENTIUM , " Pentium " } , <nl> + { CORE_SOLO , " Genuine Intel ( R ) CPU " } , <nl> + { CORE_SOLO , " Intel ( R ) Core ( TM ) " } , <nl> + { ATOM_DIAMONDVILLE , " Atom ( TM ) CPU [ N ] [ 23 ] # # " } , <nl> + { ATOM_SILVERTHORNE , " Atom ( TM ) CPU Z " } , <nl> + { ATOM_PINEVIEW , " Atom ( TM ) CPU D " } , <nl> + { ATOM_CEDARVIEW , " Atom ( TM ) CPU N # # # # " } , <nl> + { ATOM , " Atom ( TM ) CPU " } , <nl> + } ; <nl> + <nl> + if ( strstr ( bs , " Mobile " ) ) { <nl> + need_matchtable = 0 ; <nl> + if ( strstr ( bs , " Celeron " ) ) <nl> + code = MOBILE_CELERON ; <nl> + else if ( strstr ( bs , " Pentium " ) ) <nl> + code = MOBILE_PENTIUM ; <nl> + } <nl> + if ( ( i = match_pattern ( bs , " Core ( TM ) i [ 357 ] " ) ) ! = 0 ) { <nl> + / * Core i3 , Core i5 or Core i7 * / <nl> + need_matchtable = 0 ; <nl> + <nl> + core_ix_base = CORE_I3 ; <nl> + <nl> + / * if it has RdRand , then it is at least Ivy Bridge * / <nl> + if ( data - > flags [ CPU_FEATURE_RDRAND ] ) <nl> + core_ix_base = CORE_IVY3 ; <nl> + / * if it has FMA , then it is at least Haswell * / <nl> + if ( data - > flags [ CPU_FEATURE_FMA3 ] ) <nl> + core_ix_base = CORE_HASWELL3 ; <nl> + <nl> + switch ( bs [ i + 9 ] ) { <nl> + case ' 3 ' : code = core_ix_base + 0 ; break ; <nl> + case ' 5 ' : code = core_ix_base + 1 ; break ; <nl> + case ' 7 ' : code = core_ix_base + 2 ; break ; <nl> + } <nl> + } <nl> + if ( need_matchtable ) { <nl> + for ( i = 0 ; i < COUNT_OF ( matchtable ) ; i + + ) <nl> + if ( match_pattern ( bs , matchtable [ i ] . search ) ) { <nl> + code = matchtable [ i ] . c ; <nl> + break ; <nl> + } <nl> + debugf ( 2 , " intel matchtable result is % d \ n " , code ) ; <nl> + } <nl> + if ( code = = XEON ) { <nl> + if ( match_pattern ( bs , " W35 # # " ) | | match_pattern ( bs , " [ ELXW ] 75 # # " ) ) <nl> + code = XEON_I7 ; <nl> + else if ( match_pattern ( bs , " [ ELXW ] 55 # # " ) ) <nl> + code = XEON_GAINESTOWN ; <nl> + else if ( match_pattern ( bs , " [ ELXW ] 56 # # " ) ) <nl> + code = XEON_WESTMERE ; <nl> + else if ( data - > l3_cache > 0 ) <nl> + code = XEON_IRWIN ; <nl> + } <nl> + if ( code = = XEONMP & & data - > l3_cache > 0 ) <nl> + code = XEON_POTOMAC ; <nl> + if ( code = = CORE_SOLO ) { <nl> + s = strstr ( bs , " CPU " ) ; <nl> + if ( s ) { <nl> + s + = 3 ; <nl> + while ( * s = = ' ' ) s + + ; <nl> + if ( * s = = ' T ' ) <nl> + code = ( data - > num_cores = = 1 ) ? MOBILE_CORE_SOLO : MOBILE_CORE_DUO ; <nl> + } <nl> + } <nl> + if ( code = = CORE_SOLO ) { <nl> + switch ( data - > num_cores ) { <nl> + case 1 : break ; <nl> + case 2 : <nl> + { <nl> + code = CORE_DUO ; <nl> + if ( data - > num_logical_cpus > 2 ) <nl> + code = DUAL_CORE_HT ; <nl> + break ; <nl> + } <nl> + case 4 : <nl> + { <nl> + code = QUAD_CORE ; <nl> + if ( data - > num_logical_cpus > 4 ) <nl> + code = QUAD_CORE_HT ; <nl> + break ; <nl> + } <nl> + default : <nl> + code = MORE_THAN_QUADCORE ; break ; <nl> + } <nl> + } <nl> + <nl> + if ( code = = CORE_DUO & & data - > ext_model > = 23 ) { <nl> + code = WOLFDALE ; <nl> + } <nl> + if ( code = = PENTIUM_D & & data - > ext_model > = 23 ) { <nl> + code = WOLFDALE ; <nl> + } <nl> + if ( code = = MOBILE_CORE_DUO & & data - > model ! = 14 ) { <nl> + if ( data - > ext_model < 23 ) { <nl> + code = MEROM ; <nl> + } else { <nl> + code = PENRYN ; <nl> + } <nl> + } <nl> + return code ; <nl> + } <nl> + <nl> + static intel_model_t get_model_code ( struct cpu_id_t * data ) <nl> + { <nl> + int i = 0 ; <nl> + int l = ( int ) strlen ( data - > brand_str ) ; <nl> + const char * bs = data - > brand_str ; <nl> + int mod_flags = 0 , model_no = 0 , ndigs = 0 ; <nl> + / * If the CPU is a Core ix , then just return the model number generation : * / <nl> + if ( ( i = match_pattern ( bs , " Core ( TM ) i [ 357 ] " ) ) ! = 0 ) { <nl> + i + = 11 ; <nl> + if ( i + 4 > = l ) return UNKNOWN ; <nl> + if ( bs [ i ] = = ' 2 ' ) return _2xxx ; <nl> + if ( bs [ i ] = = ' 3 ' ) return _3xxx ; <nl> + return UNKNOWN ; <nl> + } <nl> + <nl> + / * For Core2 - based Xeons : * / <nl> + while ( i < l - 3 ) { <nl> + if ( bs [ i ] = = ' C ' & & bs [ i + 1 ] = = ' P ' & & bs [ i + 2 ] = = ' U ' ) <nl> + break ; <nl> + i + + ; <nl> + } <nl> + if ( i > = l - 3 ) return UNKNOWN ; <nl> + i + = 3 ; <nl> + while ( i < l - 4 & & bs [ i ] = = ' ' ) i + + ; <nl> + if ( i > = l - 4 ) return UNKNOWN ; <nl> + while ( i < l - 4 & & ! isdigit ( bs [ i ] ) ) { <nl> + if ( bs [ i ] > = ' A ' & & bs [ i ] < = ' Z ' ) <nl> + mod_flags | = ( 1 < < ( bs [ i ] - ' A ' ) ) ; <nl> + i + + ; <nl> + } <nl> + if ( i > = l - 4 ) return UNKNOWN ; <nl> + while ( isdigit ( bs [ i ] ) ) { <nl> + ndigs + + ; <nl> + model_no = model_no * 10 + ( int ) ( bs [ i ] - ' 0 ' ) ; <nl> + i + + ; <nl> + } <nl> + if ( ndigs ! = 4 ) return UNKNOWN ; <nl> + # define HAVE ( ch , flags ) ( ( flags & ( 1 < < ( ( int ) ( ch - ' A ' ) ) ) ) ! = 0 ) <nl> + switch ( model_no / 100 ) { <nl> + case 30 : return _3000 ; <nl> + case 31 : return _3100 ; <nl> + case 32 : <nl> + { <nl> + return ( HAVE ( ' X ' , mod_flags ) ) ? X3200 : _3200 ; <nl> + } <nl> + case 33 : <nl> + { <nl> + return ( HAVE ( ' X ' , mod_flags ) ) ? X3300 : _3300 ; <nl> + } <nl> + case 51 : return _5100 ; <nl> + case 52 : return _5200 ; <nl> + case 53 : return _5300 ; <nl> + case 54 : return _5400 ; <nl> + default : <nl> + return UNKNOWN ; <nl> + } <nl> + # undef HAVE <nl> + } <nl> + <nl> + int cpuid_identify_intel ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) <nl> + { <nl> + load_intel_features ( raw , data ) ; <nl> + if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 4 ) { <nl> + / * Deterministic way is preferred , being more generic * / <nl> + decode_intel_deterministic_cache_info ( raw , data ) ; <nl> + } else if ( raw - > basic_cpuid [ 0 ] [ 0 ] > = 2 ) { <nl> + decode_intel_oldstyle_cache_info ( raw , data ) ; <nl> + } <nl> + decode_intel_number_of_cores ( raw , data ) ; <nl> + match_cpu_codename ( cpudb_intel , COUNT_OF ( cpudb_intel ) , data , <nl> + get_brand_code ( data ) , get_model_code ( data ) ) ; <nl> + return 0 ; <nl> + } <nl> + <nl> + void cpuid_get_list_intel ( struct cpu_list_t * list ) <nl> + { <nl> + generic_get_cpu_list ( cpudb_intel , COUNT_OF ( cpudb_intel ) , list ) ; <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 67279373271 <nl> mmm / dev / null <nl> ppp b / libs / libcpuid / include / cpuid / recog_intel . h <nl> <nl> + / * <nl> + * Copyright 2008 Veselin Georgiev , <nl> + * anrieffNOSPAM @ mgail_DOT . com ( convert to gmail ) <nl> + * <nl> + * Redistribution and use in source and binary forms , with or without <nl> + * modification , are permitted provided that the following conditions <nl> + * are met : <nl> + * <nl> + * 1 . Redistributions of source code must retain the above copyright <nl> + * notice , this list of conditions and the following disclaimer . <nl> + * 2 . Redistributions in binary form must reproduce the above copyright <nl> + * notice , this list of conditions and the following disclaimer in the <nl> + * documentation and / or other materials provided with the distribution . <nl> + * <nl> + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS ' ' AND ANY EXPRESS OR <nl> + * IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES <nl> + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . <nl> + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , <nl> + * INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT <nl> + * NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , <nl> + * DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY <nl> + * THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT <nl> + * ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF <nl> + * THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . <nl> + * / <nl> + # ifndef __RECOG_INTEL_H__ <nl> + # define __RECOG_INTEL_H__ <nl> + <nl> + int cpuid_identify_intel ( struct cpu_raw_data_t * raw , struct cpu_id_t * data ) ; <nl> + void cpuid_get_list_intel ( struct cpu_list_t * list ) ; <nl> + <nl> + # endif / * __RECOG_INTEL_H__ * / <nl>
Merge
ClickHouse/ClickHouse
2935f975ea7a93627a599eefb8b3a4ef86db88a7
2015-02-25T20:56:53Z
mmm a / jstests / inb . js <nl> ppp b / jstests / inb . js <nl> <nl> + / / Test $ in regular expressions with overlapping index bounds . SERVER - 4677 <nl> + <nl> t = db . jstests_inb ; <nl> t . drop ( ) ; <nl> <nl> mmm a / jstests / indexz . js <nl> ppp b / jstests / indexz . js <nl> <nl> / / Check that optimal query plans do not contain empty but unindexed ranges . <nl> - / / Check that fast count query plans do not contain empty but unindexed ranges . <nl> <nl> t = db . jstests_indexz ; <nl> t . drop ( ) ; <nl> explain = t . find ( { a : 1 , b : { $ gt : 2 , $ lt : 2 } } ) . explain ( true ) ; <nl> assert . eq ( ' BtreeCursor a_1_b_1 ' , explain . cursor ) ; <nl> assert . eq ( 1 , explain . allPlans . length ) ; <nl> <nl> - <nl>
test comments
mongodb/mongo
94ff17db3325cb99dd8407a75526d17a95166e27
2012-01-19T01:31:12Z
new file mode 100644 <nl> index 0000000000 . . 37fb9093db <nl> mmm / dev / null <nl> ppp b / change / react - native - windows - 2020 - 08 - 20 - 18 - 09 - 50 - disable3D . json <nl> <nl> + { <nl> + " type " : " prerelease " , <nl> + " comment " : " Add API to turn off 3D perspective to enable controls that don ' t work in 3D " , <nl> + " packageName " : " react - native - windows " , <nl> + " email " : " asklar @ winse . microsoft . com " , <nl> + " dependentChangeType " : " patch " , <nl> + " date " : " 2020 - 08 - 21T01 : 09 : 50 . 688Z " <nl> + } <nl> mmm a / vnext / Microsoft . ReactNative / ReactRootView . cpp <nl> ppp b / vnext / Microsoft . ReactNative / ReactRootView . cpp <nl> <nl> # include " pch . h " <nl> # include " ReactRootView . h " <nl> # include " ReactRootView . g . cpp " <nl> + # include < UI . Xaml . Media . Media3D . h > <nl> # include " DynamicWriter . h " <nl> # include " ReactNativeHost . h " <nl> <nl> namespace winrt : : Microsoft : : ReactNative : : implementation { <nl> <nl> ReactRootView : : ReactRootView ( ) noexcept { <nl> m_rootControl = std : : make_shared < react : : uwp : : ReactRootControl > ( * this ) ; <nl> + UpdatePerspective ( ) ; <nl> Loaded ( [ this ] ( auto & & , auto & & ) { react : : uwp : : SetCompositor ( react : : uwp : : GetCompositor ( * this ) ) ; } ) ; <nl> } <nl> <nl> void ReactRootView : : ReloadView ( ) noexcept { <nl> } <nl> } <nl> <nl> + void ReactRootView : : UpdatePerspective ( ) { <nl> + / / Xaml ' s default projection in 3D is orthographic ( all lines are parallel ) <nl> + / / However React Native ' s default projection is a one - point perspective . <nl> + / / Set a default perspective projection on the main control to mimic this . <nl> + auto grid = m_rootControl - > GetXamlView ( ) . as < xaml : : Controls : : Grid > ( ) ; <nl> + <nl> + if ( m_isPerspectiveEnabled ) { <nl> + auto perspectiveTransform3D = xaml : : Media : : Media3D : : PerspectiveTransform3D ( ) ; <nl> + perspectiveTransform3D . Depth ( 850 ) ; <nl> + xaml : : Media : : Media3D : : Transform3D t3d ( perspectiveTransform3D ) ; <nl> + grid . Transform3D ( t3d ) ; <nl> + } else { <nl> + grid . ClearValue ( xaml : : UIElement : : Transform3DProperty ( ) ) ; <nl> + } <nl> + } <nl> } / / namespace winrt : : Microsoft : : ReactNative : : implementation <nl> mmm a / vnext / Microsoft . ReactNative / ReactRootView . h <nl> ppp b / vnext / Microsoft . ReactNative / ReactRootView . h <nl> struct ReactRootView : ReactRootViewT < ReactRootView > { <nl> ReactNative : : JSValueArgWriter InitialProps ( ) noexcept ; <nl> void InitialProps ( ReactNative : : JSValueArgWriter const & value ) noexcept ; <nl> <nl> + / / property IsPerspectiveEnabled <nl> + bool IsPerspectiveEnabled ( ) const noexcept { <nl> + return m_isPerspectiveEnabled ; <nl> + } <nl> + void IsPerspectiveEnabled ( bool value ) noexcept { <nl> + m_isPerspectiveEnabled = value ; <nl> + UpdatePerspective ( ) ; <nl> + } <nl> + <nl> void ReloadView ( ) noexcept ; <nl> <nl> private : <nl> struct ReactRootView : ReactRootViewT < ReactRootView > { <nl> hstring m_componentName ; <nl> ReactNative : : JSValueArgWriter m_initialPropsWriter ; <nl> folly : : dynamic m_initialProps ; <nl> - <nl> + bool m_isPerspectiveEnabled { true } ; <nl> std : : shared_ptr < react : : uwp : : ReactRootControl > m_rootControl ; <nl> + <nl> + void UpdatePerspective ( ) ; <nl> } ; <nl> <nl> } / / namespace winrt : : Microsoft : : ReactNative : : implementation <nl> mmm a / vnext / Microsoft . ReactNative / ReactRootView . idl <nl> ppp b / vnext / Microsoft . ReactNative / ReactRootView . idl <nl> namespace Microsoft . ReactNative { <nl> ReactNativeHost ReactNativeHost { get ; set ; } ; <nl> String ComponentName { get ; set ; } ; <nl> JSValueArgWriter InitialProps { get ; set ; } ; <nl> + Boolean IsPerspectiveEnabled { get ; set ; } ; <nl> <nl> void ReloadView ( ) ; <nl> } <nl> mmm a / vnext / Microsoft . ReactNative / Views / ReactRootControl . cpp <nl> ppp b / vnext / Microsoft . ReactNative / Views / ReactRootControl . cpp <nl> <nl> # include < UI . Xaml . Controls . h > <nl> # include < UI . Xaml . Input . h > <nl> # include < UI . Xaml . Markup . h > <nl> - # include < UI . Xaml . Media . Media3D . h > <nl> <nl> # include " DevMenu . h " <nl> # include " Modules / DevSettingsModule . h " <nl> void ReactRootControl : : PrepareXamlRootView ( XamlView const & rootView ) noexcept { <nl> children . Clear ( ) ; <nl> <nl> auto newRootView = winrt : : Grid { } ; <nl> - / / Xaml ' s default projection in 3D is orthographic ( all lines are parallel ) <nl> - / / However React Native ' s default projection is a one - point perspective . <nl> - / / Set a default perspective projection on the main control to mimic this . <nl> - auto perspectiveTransform3D = xaml : : Media : : Media3D : : PerspectiveTransform3D ( ) ; <nl> - perspectiveTransform3D . Depth ( 850 ) ; <nl> - xaml : : Media : : Media3D : : Transform3D t3d ( perspectiveTransform3D ) ; <nl> - newRootView . Transform3D ( t3d ) ; <nl> children . Append ( newRootView ) ; <nl> m_weakXamlRootView = newRootView . try_as < XamlView > ( ) ; <nl> } else { <nl>
Add API to enable non - 3D controls ( )
microsoft/react-native-windows
4e775b9a59c55996d7598aadaeb82c93c40cbb6f
2020-08-25T18:29:51Z
mmm a / build_detect_platform <nl> ppp b / build_detect_platform <nl> fi <nl> <nl> # Default to fbcode gcc on internal fb machines <nl> if [ - d / mnt / gvfs / third - party - a - z " $ CXX " ] ; then <nl> - source fbcode . gcc471 . sh <nl> + if [ - z " $ USE_CLANG " ] ; then <nl> + source fbcode . gcc471 . sh <nl> + else <nl> + source fbcode . clang31 . sh <nl> + fi <nl> fi <nl> <nl> # Delete existing output , if it exists <nl> fi <nl> COMMON_FLAGS = " $ { CFLAGS } " <nl> CROSS_COMPILE = <nl> PLATFORM_CCFLAGS = <nl> - PLATFORM_CXXFLAGS = <nl> - PLATFORM_LDFLAGS = <nl> + PLATFORM_CXXFLAGS = " $ { CXXFLAGS } " <nl> + PLATFORM_LDFLAGS = " $ PLATFORM_LDFLAGS " <nl> PLATFORM_SHARED_EXT = " so " <nl> PLATFORM_SHARED_LDFLAGS = " $ { EXEC_LDFLAGS_SHARED } - shared - Wl , - soname - Wl , " <nl> PLATFORM_SHARED_CFLAGS = " - fPIC " <nl> case " $ TARGET_OS " in <nl> ; ; <nl> Linux ) <nl> PLATFORM = OS_LINUX <nl> - COMMON_FLAGS = " $ COMMON_FLAGS - I / usr / include - fno - builtin - memcmp - pthread - DOS_LINUX - fPIC " <nl> - PLATFORM_LDFLAGS = " $ PLATFORM_LDFLAGS - pthread " <nl> + COMMON_FLAGS = " $ COMMON_FLAGS - DOS_LINUX - fPIC " <nl> + if [ - z " $ USE_CLANG " ] ; then <nl> + COMMON_FLAGS = " $ COMMON_FLAGS - fno - builtin - memcmp " <nl> + fi <nl> + PLATFORM_LDFLAGS = " $ PLATFORM_LDFLAGS - lpthread " <nl> PORT_FILE = port / port_posix . cc <nl> ; ; <nl> SunOS ) <nl> mmm a / db / skiplist_test . cc <nl> ppp b / db / skiplist_test . cc <nl> namespace leveldb { <nl> <nl> typedef uint64_t Key ; <nl> <nl> - struct Comparator { <nl> + struct TestComparator { <nl> int operator ( ) ( const Key & a , const Key & b ) const { <nl> if ( a < b ) { <nl> return - 1 ; <nl> class SkipTest { } ; <nl> <nl> TEST ( SkipTest , Empty ) { <nl> Arena arena ; <nl> - Comparator cmp ; <nl> - SkipList < Key , Comparator > list ( cmp , & arena ) ; <nl> + TestComparator cmp ; <nl> + SkipList < Key , TestComparator > list ( cmp , & arena ) ; <nl> ASSERT_TRUE ( ! list . Contains ( 10 ) ) ; <nl> <nl> - SkipList < Key , Comparator > : : Iterator iter ( & list ) ; <nl> + SkipList < Key , TestComparator > : : Iterator iter ( & list ) ; <nl> ASSERT_TRUE ( ! iter . Valid ( ) ) ; <nl> iter . SeekToFirst ( ) ; <nl> ASSERT_TRUE ( ! iter . Valid ( ) ) ; <nl> TEST ( SkipTest , InsertAndLookup ) { <nl> Random rnd ( 1000 ) ; <nl> std : : set < Key > keys ; <nl> Arena arena ; <nl> - Comparator cmp ; <nl> - SkipList < Key , Comparator > list ( cmp , & arena ) ; <nl> + TestComparator cmp ; <nl> + SkipList < Key , TestComparator > list ( cmp , & arena ) ; <nl> for ( int i = 0 ; i < N ; i + + ) { <nl> Key key = rnd . Next ( ) % R ; <nl> if ( keys . insert ( key ) . second ) { <nl> TEST ( SkipTest , InsertAndLookup ) { <nl> <nl> / / Simple iterator tests <nl> { <nl> - SkipList < Key , Comparator > : : Iterator iter ( & list ) ; <nl> + SkipList < Key , TestComparator > : : Iterator iter ( & list ) ; <nl> ASSERT_TRUE ( ! iter . Valid ( ) ) ; <nl> <nl> iter . Seek ( 0 ) ; <nl> TEST ( SkipTest , InsertAndLookup ) { <nl> <nl> / / Forward iteration test <nl> for ( int i = 0 ; i < R ; i + + ) { <nl> - SkipList < Key , Comparator > : : Iterator iter ( & list ) ; <nl> + SkipList < Key , TestComparator > : : Iterator iter ( & list ) ; <nl> iter . Seek ( i ) ; <nl> <nl> / / Compare against model iterator <nl> TEST ( SkipTest , InsertAndLookup ) { <nl> <nl> / / Backward iteration test <nl> { <nl> - SkipList < Key , Comparator > : : Iterator iter ( & list ) ; <nl> + SkipList < Key , TestComparator > : : Iterator iter ( & list ) ; <nl> iter . SeekToLast ( ) ; <nl> <nl> / / Compare against model iterator <nl> class ConcurrentTest { <nl> <nl> / / SkipList is not protected by mu_ . We just use a single writer <nl> / / thread to modify it . <nl> - SkipList < Key , Comparator > list_ ; <nl> + SkipList < Key , TestComparator > list_ ; <nl> <nl> public : <nl> - ConcurrentTest ( ) : list_ ( Comparator ( ) , & arena_ ) { } <nl> + ConcurrentTest ( ) : list_ ( TestComparator ( ) , & arena_ ) { } <nl> <nl> / / REQUIRES : External synchronization <nl> void WriteStep ( Random * rnd ) { <nl> class ConcurrentTest { <nl> } <nl> <nl> Key pos = RandomTarget ( rnd ) ; <nl> - SkipList < Key , Comparator > : : Iterator iter ( & list_ ) ; <nl> + SkipList < Key , TestComparator > : : Iterator iter ( & list_ ) ; <nl> iter . Seek ( pos ) ; <nl> while ( true ) { <nl> Key current ; <nl> mmm a / db / version_set . cc <nl> ppp b / db / version_set . cc <nl> static int64_t TotalFileSize ( const std : : vector < FileMetaData * > & files ) { <nl> return sum ; <nl> } <nl> <nl> - namespace { <nl> - std : : string IntSetToString ( const std : : set < uint64_t > & s ) { <nl> - std : : string result = " { " ; <nl> - for ( std : : set < uint64_t > : : const_iterator it = s . begin ( ) ; <nl> - it ! = s . end ( ) ; <nl> - + + it ) { <nl> - result + = ( result . size ( ) > 1 ) ? " , " : " " ; <nl> - result + = NumberToString ( * it ) ; <nl> - } <nl> - result + = " } " ; <nl> - return result ; <nl> - } <nl> - } / / namespace <nl> - <nl> Version : : ~ Version ( ) { <nl> assert ( refs_ = = 0 ) ; <nl> <nl> new file mode 100644 <nl> index 0000000000 . . 276bf12ca0 <nl> mmm / dev / null <nl> ppp b / fbcode . clang31 . sh <nl> <nl> + # ! / bin / sh <nl> + # <nl> + # Set environment variables so that we can compile leveldb using <nl> + # fbcode settings . It uses the latest g + + compiler and also <nl> + # uses jemalloc <nl> + # This is compiled with gcc version 4 . 7 . 1 for zeus proxy <nl> + <nl> + TOOLCHAIN_REV = f365dbeae46a30414a2874a6f45e73e10f1caf7d <nl> + TOOLCHAIN_EXECUTABLES = " / mnt / gvfs / third - party / $ TOOLCHAIN_REV / centos5 . 2 - native " <nl> + TOOLCHAIN_LIB_BASE = " / mnt / gvfs / third - party / $ TOOLCHAIN_REV / gcc - 4 . 7 . 1 - glibc - 2 . 14 . 1 " <nl> + TOOL_JEMALLOC = jemalloc - 3 . 0 . 0 / 2f45f3a <nl> + GLIBC_RUNTIME_PATH = / usr / local / fbcode / gcc - 4 . 7 . 1 - glibc - 2 . 14 . 1 <nl> + <nl> + # location of snappy headers and libraries <nl> + SNAPPY_INCLUDE = " - I $ TOOLCHAIN_LIB_BASE / snappy / snappy - 1 . 0 . 3 / 7518bbe / include " <nl> + SNAPPY_LIBS = " $ TOOLCHAIN_LIB_BASE / snappy / snappy - 1 . 0 . 3 / 7518bbe / lib / libsnappy . a " <nl> + <nl> + # location of boost headers and libraries <nl> + THRIFT_INCLUDE = " - I $ TOOLCHAIN_LIB_BASE / boost / boost - 1 . 48 . 0 / bef9365 / include - std = gnu + + 0x " <nl> + THRIFT_INCLUDE + = " - I . / thrift - I . / thrift / gen - cpp - I . / thrift / lib / cpp " <nl> + THRIFT_LIBS = " - L $ TOOLCHAIN_LIB_BASE / boost / boost - 1 . 48 . 0 / bef9365 / lib " <nl> + <nl> + # location of libevent <nl> + LIBEVENT_INCLUDE = " - I $ TOOLCHAIN_LIB_BASE / libevent / libevent - 1 . 4 . 14b / 91ddd43 / include " <nl> + LIBEVENT_LIBS = " - L $ TOOLCHAIN_LIB_BASE / libevent / libevent - 1 . 4 . 14b / 91ddd43 / lib " <nl> + <nl> + # use Intel SSE support for checksum calculations <nl> + export USE_SSE = " - msse - msse4 . 2 " <nl> + <nl> + CC = " $ TOOLCHAIN_EXECUTABLES / clang / clang - 3 . 1 / 6ca8a59 / bin / clang $ CLANG_INCLUDES " <nl> + CXX = " $ TOOLCHAIN_EXECUTABLES / clang / clang - 3 . 1 / 6ca8a59 / bin / clang + + $ CLANG_INCLUDES $ JINCLUDE $ SNAPPY_INCLUDE $ THRIFT_INCLUDE $ LIBEVENT_INCLUDE " <nl> + AR = $ TOOLCHAIN_EXECUTABLES / binutils / binutils - 2 . 21 . 1 / da39a3e / bin / ar <nl> + RANLIB = $ TOOLCHAIN_EXECUTABLES / binutils / binutils - 2 . 21 . 1 / da39a3e / bin / ranlib <nl> + <nl> + CFLAGS = " - B $ TOOLCHAIN_EXECUTABLES / binutils / binutils - 2 . 21 . 1 / da39a3e / bin - nostdlib - nostdinc - isystem $ TOOLCHAIN_LIB_BASE / libgcc / libgcc - 4 . 7 . 1 / afc21dc / include / c + + / 4 . 7 . 1 - isystem $ TOOLCHAIN_LIB_BASE / libgcc / libgcc - 4 . 7 . 1 / afc21dc / include / c + + / 4 . 7 . 1 / x86_64 - facebook - linux - isystem $ TOOLCHAIN_LIB_BASE / libgcc / libgcc - 4 . 7 . 1 / afc21dc / include / c + + / 4 . 7 . 1 / backward - isystem $ TOOLCHAIN_LIB_BASE / glibc / glibc - 2 . 14 . 1 / 99df8fc / include - isystem $ TOOLCHAIN_LIB_BASE / clang / clang - 3 . 1 / c8f7279 / lib / clang / 3 . 1 / include - isystem $ TOOLCHAIN_LIB_BASE / kernel - headers / kernel - headers - 3 . 2 . 18_70_fbk11_00129_gc8882d0 / da39a3e / include / linux - isystem $ TOOLCHAIN_LIB_BASE / kernel - headers / kernel - headers - 3 . 2 . 18_70_fbk11_00129_gc8882d0 / da39a3e / include - Wall - Wno - sign - compare - Wno - unused - variable - Winvalid - pch - Wno - deprecated - Woverloaded - virtual " <nl> + CXXFLAGS = " $ CFLAGS - nostdinc + + - std = gnu + + 0x " <nl> + <nl> + CFLAGS + = " - I $ TOOLCHAIN_LIB_BASE / jemalloc / $ TOOL_JEMALLOC / include - DHAVE_JEMALLOC " <nl> + <nl> + EXEC_LDFLAGS = " - Wl , - - whole - archive $ TOOLCHAIN_LIB_BASE / jemalloc / $ TOOL_JEMALLOC / lib / libjemalloc . a " <nl> + EXEC_LDFLAGS + = " - Wl , - - no - whole - archive $ TOOLCHAIN_LIB_BASE / libunwind / libunwind - 1 . 0 . 1 / 91ddd43 / lib / libunwind . a " <nl> + EXEC_LDFLAGS + = " $ HDFSLIB $ SNAPPY_LIBS $ THRIFT_LIBS $ LIBEVENT_LIBS " <nl> + EXEC_LDFLAGS + = " - Wl , - - dynamic - linker , $ GLIBC_RUNTIME_PATH / lib / ld - linux - x86 - 64 . so . 2 " <nl> + EXEC_LDFLAGS + = " - B $ TOOLCHAIN_EXECUTABLES / binutils / binutils - 2 . 21 . 1 / da39a3e / bin " <nl> + <nl> + PLATFORM_LDFLAGS = " - L $ TOOLCHAIN_LIB_BASE / libgcc / libgcc - 4 . 7 . 1 / afc21dc / lib - L $ TOOLCHAIN_LIB_BASE / glibc / glibc - 2 . 14 . 1 / 99df8fc / lib " <nl> + <nl> + EXEC_LDFLAGS_SHARED = " $ SNAPPY_LIBS " <nl> + SNAPPY_LDFLAGS = " $ SNAPPY_LIBS " <nl> + <nl> + export CC CXX AR RANLIB CFLAGS EXEC_LDFLAGS EXEC_LDFLAGS_SHARED SNAPPY_LDFLAGS <nl> mmm a / fbcode . gcc471 . sh <nl> ppp b / fbcode . gcc471 . sh <nl> EXEC_LDFLAGS = " - Wl , - - whole - archive $ TOOLCHAIN_LIB_BASE / jemalloc / $ TOOL_JEMALLOC / l <nl> EXEC_LDFLAGS + = " - Wl , - - no - whole - archive $ TOOLCHAIN_LIB_BASE / libunwind / libunwind - 20100812_experimental / 91ddd43 / lib / libunwind . a " <nl> EXEC_LDFLAGS + = " $ HDFSLIB $ SNAPPY_LIBS $ THRIFT_LIBS $ LIBEVENT_LIBS " <nl> <nl> + PLATFORM_LDFLAGS = " - L $ TOOLCHAIN_LIB_BASE / libgcc / libgcc - 4 . 7 . 1 / afc21dc / lib - L $ TOOLCHAIN_LIB_BASE / glibc / glibc - 2 . 14 . 1 / 99df8fc / lib " <nl> + <nl> EXEC_LDFLAGS_SHARED = " $ SNAPPY_LIBS " <nl> SNAPPY_LDFLAGS = " $ SNAPPY_LIBS " <nl> <nl> mmm a / table / table_test . cc <nl> ppp b / table / table_test . cc <nl> static bool ZlibCompressionSupported ( ) { <nl> & out ) ; <nl> } <nl> <nl> + # ifdef BZIP2 <nl> static bool BZip2CompressionSupported ( ) { <nl> std : : string out ; <nl> Slice in = " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " ; <nl> return port : : BZip2_Compress ( Options ( ) . compression_opts , in . data ( ) , in . size ( ) , <nl> & out ) ; <nl> } <nl> + # endif <nl> <nl> enum TestType { <nl> TABLE_TEST , <nl> mmm a / util / env_posix . cc <nl> ppp b / util / env_posix . cc <nl> class PosixWritableFile : public WritableFile { <nl> cursize_ + = left ; <nl> } else { <nl> while ( left ! = 0 ) { <nl> - size_t done = write ( fd_ , src , left ) ; <nl> + ssize_t done = write ( fd_ , src , left ) ; <nl> if ( done < 0 ) { <nl> return IOError ( filename_ , errno ) ; <nl> } <nl> class PosixWritableFile : public WritableFile { <nl> size_t left = cursize_ ; <nl> char * src = buf_ ; <nl> while ( left ! = 0 ) { <nl> - size_t done = write ( fd_ , src , left ) ; <nl> + ssize_t done = write ( fd_ , src , left ) ; <nl> if ( done < 0 ) { <nl> return IOError ( filename_ , errno ) ; <nl> } <nl>
Add optional clang compile mode
facebook/rocksdb
a2dcd79c1e8db7ceae7b17aabd58aea3a857ce55
2013-01-16T02:48:37Z
mmm a / hphp / hack / src / naming / naming_special_names . ml <nl> ppp b / hphp / hack / src / naming / naming_special_names . ml <nl> end <nl> module PPLFunctions = struct <nl> let all_reserved = <nl> [ " sample " ; " \ \ sample " ; " factor " ; " \ \ factor " ; <nl> - " observe " ; " \ \ observe " ; " condition " ; " \ \ condition " <nl> + " observe " ; " \ \ observe " ; " condition " ; " \ \ condition " ; <nl> + " sample_model " ; " \ \ sample_model " ; <nl> ] <nl> <nl> let is_reserved = <nl> mmm a / hphp / hack / src / parser / ppl / ppl_rewriter_syntax . ml <nl> ppp b / hphp / hack / src / parser / ppl / ppl_rewriter_syntax . ml <nl> let suspend_token_syntax = make_token_syntax TokenKind . Suspend <nl> ( * Special method names reserved by the Infer class * ) <nl> let reserved_method_names = <nl> [ " sample " <nl> + ; " sample_model " <nl> ; " factor " <nl> ; " observe " <nl> ; " condition " <nl> mmm a / hphp / hack / test / typecheck / ppl / anon_special_functions_correct . php <nl> ppp b / hphp / hack / test / typecheck / ppl / anon_special_functions_correct . php <nl> function sample ( string $ k ) : void { } <nl> function observe ( string $ k ) : void { } <nl> function condition ( string $ k ) : void { } <nl> function factor ( string $ k ) : void { } <nl> + function sample_model ( string $ k ) : void { } <nl> <nl> class Infer { <nl> public function sample ( int $ k ) : int { <nl> public function observe ( int $ k ) : int { <nl> public function condition ( int $ s ) : int { <nl> return 0 ; <nl> } <nl> + public function sample_model ( int $ k ) : int { <nl> + return 0 ; <nl> + } <nl> } <nl> <nl> < < __PPL > > <nl> new file mode 100644 <nl> index 00000000000 . . 640a4d21ae7 <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / typecheck / ppl / sampleModel_correct . php <nl> <nl> + < ? hh / / strict <nl> + <nl> + / / __PPL attributed classes have special rewriting rules for <nl> + / / sample , factor , observe , and condition <nl> + / / They are typed as if they were calls made to Infer - > sample , etc . <nl> + / / Infer is a special class defined by the PPL team <nl> + / / This file should produce no errors <nl> + <nl> + function sample ( string $ k ) : void { } <nl> + function observe ( string $ k ) : void { } <nl> + function condition ( string $ k ) : void { } <nl> + function factor ( string $ k ) : void { } <nl> + function sample_model ( string $ k ) : void { } <nl> + <nl> + class Infer { <nl> + public function sample ( int $ k ) : int { <nl> + return 0 ; <nl> + } <nl> + public function factor ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> + public function observe ( int $ k ) : int { <nl> + return 0 ; <nl> + } <nl> + public function condition ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> + public function sample_model ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> + } <nl> + <nl> + < < __PPL > > <nl> + class MyClass { <nl> + public function test ( ) : void { <nl> + sample_model ( 1 ) ; <nl> + } <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . 4269126fceb <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / typecheck / ppl / sampleModel_correct . php . exp <nl> @ @ - 0 , 0 + 1 @ @ <nl> + No errors <nl> new file mode 100644 <nl> index 00000000000 . . 04c34aa9c52 <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / typecheck / ppl / sampleModel_incorrect . php <nl> <nl> + < ? hh / / strict <nl> + <nl> + / / __PPL attributed classes have special rewriting rules for <nl> + / / sample , factor , observe , and condition <nl> + / / They are typed as if they were calls made to Infer - > sample , etc . <nl> + / / Infer is a special class defined by the PPL team <nl> + <nl> + function sample ( string $ k ) : void { } <nl> + function observe ( string $ k ) : void { } <nl> + function condition ( string $ k ) : void { } <nl> + function factor ( string $ k ) : void { } <nl> + function sample_model ( string $ k ) : void { } <nl> + <nl> + class Infer { <nl> + public function sample ( int $ k ) : int { <nl> + return 0 ; <nl> + } <nl> + public function factor ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> + public function observe ( int $ k ) : int { <nl> + return 0 ; <nl> + } <nl> + public function condition ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> + public function sample_model ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> + } <nl> + <nl> + < < __PPL > > <nl> + class MyClass { <nl> + public function test ( ) : void { <nl> + sample_model ( " hi " ) ; <nl> + } <nl> + } <nl> new file mode 100644 <nl> index 00000000000 . . d417e93ffb8 <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / typecheck / ppl / sampleModel_incorrect . php . exp <nl> <nl> + File " sampleModel_incorrect . php " , line 35 , characters 18 - 21 : <nl> + Invalid argument ( Typing [ 4110 ] ) <nl> + File " sampleModel_incorrect . php " , line 27 , characters 32 - 34 : <nl> + This is an int <nl> + File " sampleModel_incorrect . php " , line 35 , characters 18 - 21 : <nl> + It is incompatible with a string <nl> mmm a / hphp / hack / test / typecheck / ppl / special_functions_correct . php <nl> ppp b / hphp / hack / test / typecheck / ppl / special_functions_correct . php <nl> function sample ( int $ k ) : void { } <nl> function observe ( int $ k ) : void { } <nl> function condition ( int $ k ) : void { } <nl> function factor ( int $ k ) : void { } <nl> + function sample_model ( int $ k ) : void { } <nl> <nl> class Infer { <nl> public function sample ( int $ k ) : string { <nl> public function observe ( int $ k ) : string { <nl> public function condition ( string $ s ) : int { <nl> return 0 ; <nl> } <nl> + public function sample_model ( int $ k ) : string { <nl> + return " " ; <nl> + } <nl> } <nl> <nl> < < __PPL > > <nl> public function test ( ) : void { <nl> $ x = sample ( 1 ) ; <nl> $ x = factor ( $ x ) ; <nl> $ x = observe ( $ x ) ; <nl> - condition ( $ x ) ; <nl> + $ x = condition ( $ x ) ; <nl> + sample_model ( $ x ) ; <nl> } <nl> } <nl> mmm a / hphp / hack / test / typecheck / ppl / special_functions_namespaced_correct . php <nl> ppp b / hphp / hack / test / typecheck / ppl / special_functions_namespaced_correct . php <nl> public function observe ( string $ k ) : string { <nl> public function condition ( string $ s ) : int { <nl> return 0 ; <nl> } <nl> + public function sample_model ( string $ s ) : int { <nl> + return 0 ; <nl> + } <nl> } <nl> <nl> function sample ( int $ k ) : void { } <nl> function observe ( int $ k ) : void { } <nl> function condition ( int $ k ) : void { } <nl> function factor ( int $ k ) : void { } <nl> + function sample_model ( int $ k ) : void { } <nl> <nl> / / / / PPL . php <nl> < ? hh / / strict <nl> public function test ( ) : void { <nl> $ x = sample ( " hi " ) ; <nl> $ x = factor ( " hi " ) ; <nl> $ x = observe ( " hi " ) ; <nl> - condition ( " hi " ) ; <nl> + $ x = condition ( " hi " ) ; <nl> + $ x = sample_model ( " hi " ) ; <nl> <nl> $ x = \ sample ( " hi " ) ; <nl> $ x = \ factor ( " hi " ) ; <nl> $ x = \ observe ( " hi " ) ; <nl> - \ condition ( " hi " ) ; <nl> + $ x = \ condition ( " hi " ) ; <nl> + $ x = \ sample_model ( " hi " ) ; <nl> } <nl> } <nl> mmm a / hphp / hack / test / typecheck / ppl / special_functions_namespaced_outside_ppl_correct . php <nl> ppp b / hphp / hack / test / typecheck / ppl / special_functions_namespaced_outside_ppl_correct . php <nl> <nl> / / / / Infer . php <nl> < ? hh / / strict <nl> <nl> + / / There are five special functions that are rewritten in < < __PPL > > annotated <nl> + / / files . They should be typechecked as if they were calls to ` Infer - > method ` <nl> + / / in those cases , but we want to make sure that when they are not in a <nl> + / / < < __PPL > > file , they refer to the correct functions , in the namespace and <nl> + / / globally . <nl> + <nl> class Infer { <nl> public function sample ( int $ k ) : int { <nl> return 0 ; <nl> public function observe ( int $ k ) : int { <nl> public function condition ( int $ s ) : int { <nl> return 0 ; <nl> } <nl> + public function sample_model ( int $ s ) : int { <nl> + return 0 ; <nl> + } <nl> } <nl> <nl> function sample ( vec < string > $ k ) : void { } <nl> function observe ( vec < string > $ k ) : void { } <nl> function condition ( vec < string > $ k ) : void { } <nl> function factor ( vec < string > $ k ) : void { } <nl> + function sample_model ( vec < string > $ k ) : void { } <nl> <nl> / / / / PPL . php <nl> < ? hh / / strict <nl> function sample ( string $ k ) : void { } <nl> function observe ( string $ k ) : void { } <nl> function condition ( string $ k ) : void { } <nl> function factor ( string $ k ) : void { } <nl> + function sample_model ( string $ k ) : void { } <nl> <nl> class MyClass { <nl> public function test ( ) : void { <nl> public function test ( ) : void { <nl> factor ( " hi " ) ; <nl> observe ( " hi " ) ; <nl> condition ( " hi " ) ; <nl> + sample_model ( " hi " ) ; <nl> <nl> \ sample ( vec [ ] ) ; <nl> \ factor ( vec [ ] ) ; <nl> \ observe ( vec [ ] ) ; <nl> \ condition ( vec [ ] ) ; <nl> + \ sample_model ( vec [ ] ) ; <nl> } <nl> } <nl>
Add sampleModel to Infer class and rewrite it
facebook/hhvm
d398c4d0b6d0492659881352e92abb32934bf25e
2018-08-28T00:29:24Z
mmm a / src / citra_qt / debugger / graphics_cmdlists . cpp <nl> ppp b / src / citra_qt / debugger / graphics_cmdlists . cpp <nl> TextureInfoDockWidget : : TextureInfoDockWidget ( const Pica : : DebugUtils : : TextureInfo <nl> format_choice - > addItem ( tr ( " I8 " ) ) ; <nl> format_choice - > addItem ( tr ( " A8 " ) ) ; <nl> format_choice - > addItem ( tr ( " IA4 " ) ) ; <nl> - format_choice - > addItem ( tr ( " UNK10 " ) ) ; <nl> + format_choice - > addItem ( tr ( " I4 " ) ) ; <nl> format_choice - > addItem ( tr ( " A4 " ) ) ; <nl> format_choice - > addItem ( tr ( " ETC1 " ) ) ; <nl> format_choice - > addItem ( tr ( " ETC1A4 " ) ) ; <nl> mmm a / src / video_core / pica . h <nl> ppp b / src / video_core / pica . h <nl> struct Regs { <nl> case TextureFormat : : IA8 : <nl> return 4 ; <nl> <nl> + case TextureFormat : : I4 : <nl> case TextureFormat : : A4 : <nl> return 1 ; <nl> <nl>
Merge pull request from Subv / ia4
yuzu-emu/yuzu
ef828a1cddf9b628e498ed6aa9f7778d01b7d10e
2015-07-19T18:23:04Z
mmm a / ios / sdk / WeexSDK / Sources / Utility / WXUtility . h <nl> ppp b / ios / sdk / WeexSDK / Sources / Utility / WXUtility . h <nl> extern _Nonnull SEL WXSwizzledSelectorForSelector ( _Nonnull SEL selector ) ; <nl> <nl> @ interface WXUtility : NSObject <nl> <nl> + + ( void ) setNotStat : ( BOOL ) notStat ; <nl> + + ( BOOL ) notStat ; <nl> / * * <nl> * @ abstract Returns the environment of current application , you can get some nessary properties such as appVersion 、 sdkVersion 、 appName etc . <nl> * <nl> mmm a / ios / sdk / WeexSDK / Sources / Utility / WXUtility . m <nl> ppp b / ios / sdk / WeexSDK / Sources / Utility / WXUtility . m <nl> CGPoint WXPixelPointResize ( CGPoint value ) <nl> value . y * WXScreenResizeRadio ( ) ) ; <nl> return new ; <nl> } <nl> - <nl> + static BOOL WXNotStat ; <nl> @ implementation WXUtility <nl> <nl> + ( NSDictionary * ) getEnvironment <nl> + ( NSString * ) registeredDeviceName { <nl> <nl> + ( void ) addStatTrack : ( NSString * ) appName <nl> { <nl> - if ( ! appName ) { <nl> + if ( ! appName | | [ self notStat ] ) { <nl> return ; <nl> } <nl> <nl> + ( void ) delete : ( NSString * ) service { <nl> SecItemDelete ( ( CFDictionaryRef ) keychainQuery ) ; <nl> } <nl> <nl> + + ( void ) setNotStat : ( BOOL ) notStat { <nl> + WXNotStat = YES ; <nl> + } <nl> + <nl> + + ( BOOL ) notStat { <nl> + return WXNotStat ; <nl> + } <nl> + <nl> @ end <nl>
* [ ios ] add trace for sdk
apache/incubator-weex
2d3ef8e11c803d5c0faaf18015be52dee66648fb
2016-06-29T13:18:37Z
mmm a / lib / Sema / TypeCheckSwitchStmt . cpp <nl> ppp b / lib / Sema / TypeCheckSwitchStmt . cpp <nl> namespace { <nl> bool InEditor = TC . Context . LangOpts . DiagnosticsEditorMode ; <nl> <nl> if ( JustNeedsDefault ) { <nl> - OS < < tok : : kw_default < < " : " < < Placeholder < < " \ n " ; <nl> + OS < < tok : : kw_default < < " : \ n " < < Placeholder < < " \ n " ; <nl> if ( Empty ) { <nl> TC . Context . Diags . diagnose ( StartLoc , diag : : empty_switch_stmt ) <nl> . fixItInsert ( EndLoc , Buffer . str ( ) ) ; <nl> namespace { <nl> for ( auto & flat : flats ) { <nl> OS < < tok : : kw_case < < " " ; <nl> flat . show ( OS ) ; <nl> - OS < < " : " < < Placeholder < < " \ n " ; <nl> + OS < < " : \ n " < < Placeholder < < " \ n " ; <nl> } <nl> } <nl> <nl> mmm a / test / FixCode / fixits - empty - switch - multifile . swift . result <nl> ppp b / test / FixCode / fixits - empty - switch - multifile . swift . result <nl> <nl> <nl> func foo1 ( _ e : EMulti ) { <nl> switch e { <nl> - case . e1 : < # code # > <nl> - case . e2 : < # code # > <nl> - case . e3 ( _ ) : < # code # > <nl> + case . e1 : <nl> + < # code # > <nl> + case . e2 : <nl> + < # code # > <nl> + case . e3 ( _ ) : <nl> + < # code # > <nl> } <nl> } <nl> mmm a / test / FixCode / fixits - empty - switch . swift . result <nl> ppp b / test / FixCode / fixits - empty - switch . swift . result <nl> enum E1 { <nl> <nl> func foo1 ( _ e : E1 ) { <nl> switch e { <nl> - case . e1 : < # code # > <nl> - case . e2 : < # code # > <nl> - case . e3 : < # code # > <nl> + case . e1 : <nl> + < # code # > <nl> + case . e2 : <nl> + < # code # > <nl> + case . e3 : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo1 ( _ i : Int ) { <nl> switch i { <nl> - default : < # code # > <nl> + default : <nl> + < # code # > <nl> } <nl> } <nl> mmm a / test / FixCode / fixits - switch . swift . result <nl> ppp b / test / FixCode / fixits - switch . swift . result <nl> func foo1 ( _ e : E1 ) - > Int { <nl> switch ( e ) { <nl> case . e1 : <nl> return 1 <nl> - case . e2 : < # code # > <nl> - case . e3 : < # code # > <nl> - case . e4 : < # code # > <nl> + case . e2 : <nl> + < # code # > <nl> + case . e3 : <nl> + < # code # > <nl> + case . e4 : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo2 ( _ i : Int ) - > Int { <nl> switch i { <nl> case 1 : <nl> return 1 <nl> - default : < # code # > <nl> + default : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo3 ( _ c : Character ) - > Character { <nl> switch c { <nl> case " a " : <nl> return " a " <nl> - default : < # code # > <nl> + default : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo4 ( _ e : E2 ) - > Int { <nl> switch e { <nl> case . e2 : <nl> return 1 <nl> - case . e1 ( _ , _ ) : < # code # > <nl> - case . e3 ( _ ) : < # code # > <nl> - case . e4 ( _ ) : < # code # > <nl> - case . e5 ( _ , _ ) : < # code # > <nl> - case . e6 ( _ , _ ) : < # code # > <nl> - case . e7 : < # code # > <nl> - case . e8 ( _ , _ , _ ) : < # code # > <nl> - case . e9 ( _ , _ , _ ) : < # code # > <nl> + case . e1 ( _ , _ ) : <nl> + < # code # > <nl> + case . e3 ( _ ) : <nl> + < # code # > <nl> + case . e4 ( _ ) : <nl> + < # code # > <nl> + case . e5 ( _ , _ ) : <nl> + < # code # > <nl> + case . e6 ( _ , _ ) : <nl> + < # code # > <nl> + case . e7 : <nl> + < # code # > <nl> + case . e8 ( _ , _ , _ ) : <nl> + < # code # > <nl> + case . e9 ( _ , _ , _ ) : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo5 ( _ e : E1 ) - > Int { <nl> switch e { <nl> case _ where e . rawValue > 0 : <nl> return 1 <nl> - case . e1 : < # code # > <nl> - case . e2 : < # code # > <nl> - case . e3 : < # code # > <nl> - case . e4 : < # code # > <nl> + case . e1 : <nl> + < # code # > <nl> + case . e2 : <nl> + < # code # > <nl> + case . e3 : <nl> + < # code # > <nl> + case . e4 : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo6 ( _ e : E2 ) - > Int { <nl> switch e { <nl> case let . e1 ( x , y ) : <nl> return x + y <nl> - case . e2 ( _ ) : < # code # > <nl> - case . e3 ( _ ) : < # code # > <nl> - case . e4 ( _ ) : < # code # > <nl> - case . e5 ( _ , _ ) : < # code # > <nl> - case . e6 ( _ , _ ) : < # code # > <nl> - case . e7 : < # code # > <nl> - case . e8 ( _ , _ , _ ) : < # code # > <nl> - case . e9 ( _ , _ , _ ) : < # code # > <nl> + case . e2 ( _ ) : <nl> + < # code # > <nl> + case . e3 ( _ ) : <nl> + < # code # > <nl> + case . e4 ( _ ) : <nl> + < # code # > <nl> + case . e5 ( _ , _ ) : <nl> + < # code # > <nl> + case . e6 ( _ , _ ) : <nl> + < # code # > <nl> + case . e7 : <nl> + < # code # > <nl> + case . e8 ( _ , _ , _ ) : <nl> + < # code # > <nl> + case . e9 ( _ , _ , _ ) : <nl> + < # code # > <nl> } <nl> } <nl> <nl> func foo7 ( _ e : E2 ) - > Int { <nl> case . e2 ( 1 ) : return 0 <nl> case . e1 : return 0 <nl> case . e3 : return 0 <nl> - case . e2 ( _ ) : < # code # > <nl> - case . e4 ( _ ) : < # code # > <nl> - case . e5 ( _ , _ ) : < # code # > <nl> - case . e6 ( _ , _ ) : < # code # > <nl> - case . e7 : < # code # > <nl> - case . e8 ( _ , _ , _ ) : < # code # > <nl> - case . e9 ( _ , _ , _ ) : < # code # > <nl> + case . e2 ( _ ) : <nl> + < # code # > <nl> + case . e4 ( _ ) : <nl> + < # code # > <nl> + case . e5 ( _ , _ ) : <nl> + < # code # > <nl> + case . e6 ( _ , _ ) : <nl> + < # code # > <nl> + case . e7 : <nl> + < # code # > <nl> + case . e8 ( _ , _ , _ ) : <nl> + < # code # > <nl> + case . e9 ( _ , _ , _ ) : <nl> + < # code # > <nl> } <nl> } <nl> mmm a / test / stmt / switch_stmt1 . swift <nl> ppp b / test / stmt / switch_stmt1 . swift <nl> func foo1 ( e : E , i : Int ) { <nl> switch e { } / / expected - error { { switch must be exhaustive } } <nl> / / expected - note @ - 1 { { missing case : ' . e1 ' } } <nl> / / expected - note @ - 2 { { missing case : ' . e2 ' } } <nl> - switch i { } / / expected - error { { ' switch ' statement body must have at least one ' case ' or ' default ' block ; do you want to add a default case ? } } { { 13 - 13 = default : < # code # > \ n } } <nl> + switch i { } / / expected - error { { ' switch ' statement body must have at least one ' case ' or ' default ' block ; do you want to add a default case ? } } { { 13 - 13 = default : \ n < # code # > \ n } } <nl> } <nl> mmm a / test / stmt / switch_stmt2 . swift <nl> ppp b / test / stmt / switch_stmt2 . swift <nl> func foo1 ( e : E ) { <nl> <nl> func foo2 ( i : Int ) { <nl> switch i { / / expected - error { { switch must be exhaustive } } <nl> - / / expected - note @ - 1 { { do you want to add a default clause ? } } { { 3 - 3 = default : < # code # > \ n } } <nl> + / / expected - note @ - 1 { { do you want to add a default clause ? } } { { 3 - 3 = default : \ n < # code # > \ n } } <nl> case 1 : return <nl> } <nl> } <nl> mmm a / test / stmt / switch_stmt_editor1 . swift <nl> ppp b / test / stmt / switch_stmt_editor1 . swift <nl> enum E { <nl> <nl> func foo1 ( e : E , i : Int ) { <nl> switch e { } / / expected - error { { switch must be exhaustive } } <nl> - / / expected - note @ - 1 { { do you want to add missing cases ? } } { { 13 - 13 = case . e1 : < # code # > \ ncase . e2 : < # code # > \ n } } <nl> - switch i { } / / expected - error { { ' switch ' statement body must have at least one ' case ' or ' default ' block ; do you want to add a default case ? } } { { 13 - 13 = default : < # code # > \ n } } <nl> + / / expected - note @ - 1 { { do you want to add missing cases ? } } { { 13 - 13 = case . e1 : \ n < # code # > \ ncase . e2 : \ n < # code # > \ n } } <nl> + switch i { } / / expected - error { { ' switch ' statement body must have at least one ' case ' or ' default ' block ; do you want to add a default case ? } } { { 13 - 13 = default : \ n < # code # > \ n } } <nl> } <nl> mmm a / test / stmt / switch_stmt_editor2 . swift <nl> ppp b / test / stmt / switch_stmt_editor2 . swift <nl> enum E { <nl> <nl> func foo1 ( e : E ) { <nl> switch e { / / expected - error { { switch must be exhaustive } } <nl> - / / expected - note @ - 1 { { do you want to add missing cases ? } } { { 3 - 3 = case . e2 : < # code # > \ n } } <nl> + / / expected - note @ - 1 { { do you want to add missing cases ? } } { { 3 - 3 = case . e2 : \ n < # code # > \ n } } <nl> case . e1 : return <nl> } <nl> } <nl> <nl> func foo2 ( i : Int ) { <nl> switch i { / / expected - error { { switch must be exhaustive } } <nl> - / / expected - note @ - 1 { { do you want to add a default clause ? } } { { 3 - 3 = default : < # code # > \ n } } <nl> + / / expected - note @ - 1 { { do you want to add a default clause ? } } { { 3 - 3 = default : \ n < # code # > \ n } } <nl> case 1 : return <nl> } <nl> } <nl>
FixCode : Add a new line between switch label and the code placeholder . rdar : / / 32121847 ( )
apple/swift
b6d753067b793be7278292ab44006df3118c33fa
2017-05-13T19:21:48Z
mmm a / lib / IDE / SyntaxModel . cpp <nl> ppp b / lib / IDE / SyntaxModel . cpp <nl> std : : pair < bool , Expr * > ModelASTWalker : : walkToExprPre ( Expr * E ) { <nl> SN . Kind = SyntaxStructureKind : : Parameter ; <nl> SN . NameRange = NR ; <nl> SN . BodyRange = charSourceRangeFromSourceRange ( SM , E - > getSourceRange ( ) ) ; <nl> - if ( NR . isValid ( ) ) <nl> + if ( NR . isValid ( ) ) { <nl> SN . Range = charSourceRangeFromSourceRange ( SM , SourceRange ( NR . getStart ( ) , <nl> E - > getEndLoc ( ) ) ) ; <nl> + passTokenNodesUntil ( NR . getStart ( ) , <nl> + PassNodesBehavior : : ExcludeNodeAtLocation ) ; <nl> + if ( ! TokenNodes . empty ( ) ) <nl> + const_cast < SyntaxNode & > ( TokenNodes . front ( ) ) . Kind = SyntaxNodeKind : : <nl> + Identifier ; <nl> + } <nl> else <nl> SN . Range = SN . BodyRange ; <nl> <nl> std : : pair < bool , Expr * > ModelASTWalker : : walkToExprPre ( Expr * E ) { <nl> } <nl> SN . BodyRange = innerCharSourceRangeFromSourceRange ( SM , E - > getSourceRange ( ) ) ; <nl> pushStructureNode ( SN , E ) ; <nl> + } else if ( auto * Tup = dyn_cast < TupleExpr > ( E ) ) { <nl> + for ( unsigned I = 0 ; I < Tup - > getNumElements ( ) ; + + I ) { <nl> + SourceLoc NameLoc = Tup - > getElementNameLoc ( I ) ; <nl> + if ( NameLoc . isValid ( ) ) { <nl> + passTokenNodesUntil ( NameLoc , PassNodesBehavior : : ExcludeNodeAtLocation ) ; <nl> + if ( ! TokenNodes . empty ( ) ) { <nl> + const_cast < SyntaxNode & > ( TokenNodes . front ( ) ) . Kind = SyntaxNodeKind : : <nl> + Identifier ; <nl> + } <nl> + } <nl> + } <nl> } <nl> <nl> return { true , E } ; <nl> mmm a / test / IDE / coloring . swift <nl> ppp b / test / IDE / coloring . swift <nl> let black = # colorLiteral ( red : 0 , green : 0 , blue : 0 , alpha : 1 ) <nl> " - - \ " \ ( x ) - - " <nl> / / CHECK : < str > " - - \ " < / str > \ < anchor > ( < / anchor > x < anchor > ) < / anchor > < str > - - " < / str > <nl> <nl> + func keywordAsLabel1 ( in : Int ) { } <nl> + / / CHECK : < kw > func < / kw > keywordAsLabel1 ( in : < type > Int < / type > ) { } <nl> + func keywordAsLabel2 ( for : Int ) { } <nl> + / / CHECK : < kw > func < / kw > keywordAsLabel2 ( for : < type > Int < / type > ) { } <nl> + <nl> + func foo1 ( ) { <nl> + / / CHECK : < kw > func < / kw > foo1 ( ) { <nl> + keywordAsLabel1 ( in : 1 ) <nl> + / / CHECK : keywordAsLabel1 ( in : < int > 1 < / int > ) <nl> + keywordAsLabel2 ( for : 1 ) <nl> + / / CHECK : keywordAsLabel2 ( for : < int > 1 < / int > ) <nl> + } <nl> + <nl> / / Keep this as the last test <nl> / * * <nl> Trailing off . . . <nl> mmm a / test / SourceKit / SyntaxMapData / syntaxmap - object - literals . swift . response <nl> ppp b / test / SourceKit / SyntaxMapData / syntaxmap - object - literals . swift . response <nl> <nl> key . length : 40 <nl> } , <nl> { <nl> - key . kind : source . lang . swift . syntaxtype . keyword , <nl> + key . kind : source . lang . swift . syntaxtype . identifier , <nl> key . offset : 165 , <nl> key . length : 3 <nl> } , <nl> <nl> key . length : 50 <nl> } , <nl> { <nl> - key . kind : source . lang . swift . syntaxtype . keyword , <nl> + key . kind : source . lang . swift . syntaxtype . identifier , <nl> key . offset : 228 , <nl> key . length : 3 <nl> } , <nl>
[ Syntax ] Avoid highlighting keyword - like labels in call arguments as … ( )
apple/swift
500fdd22d1e647b842f1428f8ea6200258da7189
2016-07-07T05:40:44Z
mmm a / src / heap / spaces . cc <nl> ppp b / src / heap / spaces . cc <nl> void MemoryChunk : : Unlink ( ) { <nl> set_next_chunk ( NULL ) ; <nl> } <nl> <nl> - void MemoryAllocator : : ShrinkChunk ( MemoryChunk * chunk , size_t bytes_to_shrink ) { <nl> - DCHECK_GE ( bytes_to_shrink , static_cast < size_t > ( GetCommitPageSize ( ) ) ) ; <nl> - DCHECK_EQ ( 0u , bytes_to_shrink % GetCommitPageSize ( ) ) ; <nl> - Address free_start = chunk - > area_end_ - bytes_to_shrink ; <nl> - / / Don ' t adjust the size of the page . The area is just uncomitted but not <nl> - / / released . <nl> - chunk - > area_end_ - = bytes_to_shrink ; <nl> - UncommitBlock ( free_start , bytes_to_shrink ) ; <nl> - if ( chunk - > IsFlagSet ( MemoryChunk : : IS_EXECUTABLE ) ) { <nl> - if ( chunk - > reservation_ . IsReserved ( ) ) <nl> - chunk - > reservation_ . Guard ( chunk - > area_end_ ) ; <nl> - else <nl> - base : : OS : : Guard ( chunk - > area_end_ , GetCommitPageSize ( ) ) ; <nl> - } <nl> - } <nl> - <nl> MemoryChunk * MemoryAllocator : : AllocateChunk ( size_t reserve_area_size , <nl> size_t commit_area_size , <nl> Executability executable , <nl> size_t Page : : AvailableInFreeList ( ) { <nl> } <nl> <nl> size_t Page : : ShrinkToHighWaterMark ( ) { <nl> + / / Shrinking only makes sense outside of the CodeRange , where we don ' t care <nl> + / / about address space fragmentation . <nl> + base : : VirtualMemory * reservation = reserved_memory ( ) ; <nl> + if ( ! reservation - > IsReserved ( ) ) return 0 ; <nl> + <nl> / / Shrink pages to high water mark . The water mark points either to a filler <nl> / / or the area_end . <nl> HeapObject * filler = HeapObject : : FromAddress ( HighWaterMark ( ) ) ; <nl> size_t Page : : ShrinkToHighWaterMark ( ) { <nl> static_cast < size_t > ( area_end ( ) - filler - > address ( ) - FreeSpace : : kSize ) , <nl> MemoryAllocator : : GetCommitPageSize ( ) ) ; <nl> if ( unused > 0 ) { <nl> + DCHECK_EQ ( 0u , unused % MemoryAllocator : : GetCommitPageSize ( ) ) ; <nl> if ( FLAG_trace_gc_verbose ) { <nl> PrintIsolate ( heap ( ) - > isolate ( ) , " Shrinking page % p : end % p - > % p \ n " , <nl> reinterpret_cast < void * > ( this ) , <nl> size_t Page : : ShrinkToHighWaterMark ( ) { <nl> filler - > address ( ) , <nl> static_cast < int > ( area_end ( ) - filler - > address ( ) - unused ) , <nl> ClearRecordedSlots : : kNo ) ; <nl> - heap ( ) - > memory_allocator ( ) - > ShrinkChunk ( this , unused ) ; <nl> + heap ( ) - > memory_allocator ( ) - > PartialFreeMemory ( <nl> + this , address ( ) + size ( ) - unused , unused ) ; <nl> CHECK ( filler - > IsFiller ( ) ) ; <nl> CHECK_EQ ( filler - > address ( ) + filler - > Size ( ) , area_end ( ) ) ; <nl> } <nl> void Page : : DestroyBlackArea ( Address start , Address end ) { <nl> - static_cast < int > ( end - start ) ) ; <nl> } <nl> <nl> - size_t MemoryAllocator : : PartialFreeMemory ( MemoryChunk * chunk , <nl> - Address start_free ) { <nl> - / / We do not allow partial shrink for code . <nl> - DCHECK ( chunk - > executable ( ) = = NOT_EXECUTABLE ) ; <nl> - <nl> - intptr_t size ; <nl> + void MemoryAllocator : : PartialFreeMemory ( MemoryChunk * chunk , Address start_free , <nl> + size_t bytes_to_free ) { <nl> base : : VirtualMemory * reservation = chunk - > reserved_memory ( ) ; <nl> DCHECK ( reservation - > IsReserved ( ) ) ; <nl> - size = static_cast < intptr_t > ( reservation - > size ( ) ) ; <nl> - <nl> - size_t to_free_size = size - ( start_free - chunk - > address ( ) ) ; <nl> - <nl> - DCHECK ( size_ . Value ( ) > = to_free_size ) ; <nl> - size_ . Decrement ( to_free_size ) ; <nl> + DCHECK_GE ( size_ . Value ( ) , bytes_to_free ) ; <nl> + size_ . Decrement ( bytes_to_free ) ; <nl> isolate_ - > counters ( ) - > memory_allocated ( ) - > Decrement ( <nl> - static_cast < int > ( to_free_size ) ) ; <nl> - chunk - > set_size ( size - to_free_size ) ; <nl> - <nl> + static_cast < int > ( bytes_to_free ) ) ; <nl> + chunk - > size_ - = bytes_to_free ; <nl> + chunk - > area_end_ - = bytes_to_free ; <nl> + if ( chunk - > IsFlagSet ( MemoryChunk : : IS_EXECUTABLE ) ) { <nl> + DCHECK_EQ ( 0 , reinterpret_cast < uintptr_t > ( chunk - > area_end_ ) % <nl> + static_cast < uintptr_t > ( GetCommitPageSize ( ) ) ) ; <nl> + DCHECK_EQ ( chunk - > address ( ) + chunk - > size ( ) , <nl> + chunk - > area_end ( ) + CodePageGuardSize ( ) ) ; <nl> + chunk - > reservation_ . Guard ( chunk - > area_end_ ) ; <nl> + } <nl> reservation - > ReleasePartial ( start_free ) ; <nl> - return to_free_size ; <nl> } <nl> <nl> void MemoryAllocator : : PreFreeMemory ( MemoryChunk * chunk ) { <nl> void PagedSpace : : ShrinkImmortalImmovablePages ( ) { <nl> DCHECK ( page - > IsFlagSet ( Page : : NEVER_EVACUATE ) ) ; <nl> size_t unused = page - > ShrinkToHighWaterMark ( ) ; <nl> accounting_stats_ . DecreaseCapacity ( static_cast < intptr_t > ( unused ) ) ; <nl> - / / Do not account for the unused space as uncommitted because the counter <nl> - / / is kept in sync with page size which is also not adjusted for those <nl> - / / chunks . <nl> + AccountUncommitted ( unused ) ; <nl> } <nl> } <nl> <nl> void LargeObjectSpace : : FreeUnmarkedObjects ( ) { <nl> if ( ( free_start = current - > GetAddressToShrink ( ) ) ! = 0 ) { <nl> current - > ClearOutOfLiveRangeSlots ( free_start ) ; <nl> RemoveChunkMapEntries ( current , free_start ) ; <nl> - const size_t freed = <nl> - heap ( ) - > memory_allocator ( ) - > PartialFreeMemory ( current , free_start ) ; <nl> - size_ - = freed ; <nl> - AccountUncommitted ( freed ) ; <nl> + const size_t bytes_to_free = <nl> + current - > size ( ) - ( free_start - current - > address ( ) ) ; <nl> + heap ( ) - > memory_allocator ( ) - > PartialFreeMemory ( current , free_start , <nl> + bytes_to_free ) ; <nl> + size_ - = bytes_to_free ; <nl> + AccountUncommitted ( bytes_to_free ) ; <nl> } <nl> previous = current ; <nl> current = current - > next_page ( ) ; <nl> mmm a / src / heap / spaces . h <nl> ppp b / src / heap / spaces . h <nl> class V8_EXPORT_PRIVATE MemoryAllocator { <nl> MemoryChunk * AllocateChunk ( size_t reserve_area_size , size_t commit_area_size , <nl> Executability executable , Space * space ) ; <nl> <nl> - void ShrinkChunk ( MemoryChunk * chunk , size_t bytes_to_shrink ) ; <nl> - <nl> Address ReserveAlignedMemory ( size_t requested , size_t alignment , <nl> base : : VirtualMemory * controller ) ; <nl> Address AllocateAlignedMemory ( size_t reserve_size , size_t commit_size , <nl> class V8_EXPORT_PRIVATE MemoryAllocator { <nl> void FreeMemory ( base : : VirtualMemory * reservation , Executability executable ) ; <nl> void FreeMemory ( Address addr , size_t size , Executability executable ) ; <nl> <nl> - / / Returns the size of the freed memory in bytes . <nl> - size_t PartialFreeMemory ( MemoryChunk * chunk , Address start_free ) ; <nl> + / / Partially release | bytes_to_free | bytes starting at | start_free | . Note that <nl> + / / internally memory is freed from | start_free | to the end of the reservation . <nl> + / / Additional memory beyond the page is not accounted though , so <nl> + / / | bytes_to_free | is computed by the caller . <nl> + void PartialFreeMemory ( MemoryChunk * chunk , Address start_free , <nl> + size_t bytes_to_free ) ; <nl> <nl> / / Commit a contiguous block of memory from the initial chunk . Assumes that <nl> / / the address is not NULL , the size is greater than zero , and that the <nl>
Reland " [ heap ] Use partial free when shrinking instead of uncommitting "
v8/v8
1b4934b9ce7aae28a39f56ff577311278c7615db
2017-06-13T09:30:30Z
mmm a / src / csharp / Grpc . Core / Grpc . Core . nuspec <nl> ppp b / src / csharp / Grpc . Core / Grpc . Core . nuspec <nl> <nl> < file src = " bin / ReleaseSigned / Grpc . Core . xml " target = " lib / net45 " / > <nl> < file src = " * * \ * . cs " target = " src " / > <nl> < file src = " Grpc . Core . targets " target = " \ build \ net45 \ Grpc . Core . targets " / > <nl> - < file src = " . . / nativelibs / windows_x86 / grpc_csharp_ext . dll " target = " / build / native / bin / windows_x86 / grpc_csharp_ext . dll " / > <nl> - < file src = " . . / nativelibs / windows_x64 / grpc_csharp_ext . dll " target = " / build / native / bin / windows_x64 / grpc_csharp_ext . dll " / > <nl> - < file src = " . . / nativelibs / linux_x86 / libgrpc_csharp_ext . so " target = " / build / native / bin / linux_x86 / libgrpc_csharp_ext . so " / > <nl> - < file src = " . . / nativelibs / linux_x64 / libgrpc_csharp_ext . so " target = " / build / native / bin / linux_x64 / libgrpc_csharp_ext . so " / > <nl> - < file src = " . . / nativelibs / macosx_x86 / libgrpc_csharp_ext . dylib " target = " / build / native / bin / macosx_x86 / libgrpc_csharp_ext . dylib " / > <nl> - < file src = " . . / nativelibs / macosx_x64 / libgrpc_csharp_ext . dylib " target = " / build / native / bin / macosx_x64 / libgrpc_csharp_ext . dylib " / > <nl> + < ! - - without backslashes in the the source path , nuget won ' t copy the files - - > <nl> + < file src = " . . \ nativelibs \ windows_x86 \ grpc_csharp_ext . dll " target = " / build / native / bin / windows_x86 / grpc_csharp_ext . dll " / > <nl> + < file src = " . . \ nativelibs \ windows_x64 \ grpc_csharp_ext . dll " target = " / build / native / bin / windows_x64 / grpc_csharp_ext . dll " / > <nl> + < file src = " . . \ nativelibs \ linux_x86 \ libgrpc_csharp_ext . so " target = " / build / native / bin / linux_x86 / libgrpc_csharp_ext . so " / > <nl> + < file src = " . . \ nativelibs \ linux_x64 \ libgrpc_csharp_ext . so " target = " / build / native / bin / linux_x64 / libgrpc_csharp_ext . so " / > <nl> + < file src = " . . \ nativelibs \ macosx_x86 \ libgrpc_csharp_ext . dylib " target = " / build / native / bin / macosx_x86 / libgrpc_csharp_ext . dylib " / > <nl> + < file src = " . . \ nativelibs \ macosx_x64 \ libgrpc_csharp_ext . dylib " target = " / build / native / bin / macosx_x64 / libgrpc_csharp_ext . dylib " / > <nl> < / files > <nl> < / package > <nl>
Merge pull request from jtattermusch / csharp_fix_nuget_build
grpc/grpc
c356891848d7d62da915b689ade1c00c03765864
2016-06-24T17:14:57Z
new file mode 100644 <nl> index 000000000000 . . ab3d29d08248 <nl> mmm / dev / null <nl> ppp b / test / SourceKit / CursorInfo / rdar_31758709 . swift <nl> <nl> + / / Checks that we don ' t crash <nl> + / / RUN : % sourcekitd - test - req = cursor - pos = 8 : 19 % s - - % s | % FileCheck % s <nl> + / / CHECK : source . lang . swift . ref . class <nl> + <nl> + class ImageSet { <nl> + class StandImageSet { } <nl> + func foo ( ) { <nl> + / * here : * / StandImageSet ( ) <nl> + } <nl> + } <nl>
Merge pull request from nathawes / rdar31758709 - cursor - info - crasher
apple/swift
03c125979bbeded4aadf3b5e920093f5d238b4da
2017-04-25T00:41:28Z
mmm a / tests / test_other . py <nl> ppp b / tests / test_other . py <nl> def check_simd ( self , expected_simds , expected_out ) : <nl> assert simds > = expected_simds , ' expecting to see at least % d SIMD * uses , but seeing % d ' % ( expected_simds , simds ) <nl> <nl> def test_autovectorize_linpack ( self ) : <nl> + # autovectorization of this stopped in LLVM 6 . 0 . TODO : investigate when SIMD arrives in wasm <nl> + return <nl> Popen ( [ PYTHON , EMCC , path_from_root ( ' tests ' , ' linpack . c ' ) , ' - O2 ' , ' - s ' , ' SIMD = 1 ' , ' - DSP ' , ' - s ' , ' PRECISE_F32 = 1 ' , ' - - profiling ' , ' - s ' , ' WASM = 0 ' ] ) . communicate ( ) <nl> self . check_simd ( 30 , ' Unrolled Single Precision ' ) <nl> <nl>
SIMD test stopped autovectorizing in 6 . 0 [ ci skip ]
emscripten-core/emscripten
91267c2f014afdab5e68c20d63df8a9236e9c4bb
2018-05-21T21:37:16Z
mmm a / html / admin / css / dashboardView . css <nl> ppp b / html / admin / css / dashboardView . css <nl> <nl> <nl> . statClient { <nl> float : left ; <nl> - height : 120px ; <nl> + height : 70px ; <nl> width : 203px ; <nl> margin - left : 9px ; <nl> margin - bottom : 12px ; <nl> <nl> } <nl> <nl> . statGroups . statChart { <nl> - margin - left : - 45px ! important ; <nl> + margin - left : - 55px ! important ; <nl> + margin - top : - 50px ! important ; <nl> } <nl> <nl> . nv - axislabel { <nl> <nl> margin - top : 0 ! important ; <nl> padding - top : 0 ! important ; <nl> height : 140px ; <nl> - width : 255px ; <nl> + / * width : 255px ; * / <nl> + width : 272px ; <nl> } <nl> <nl> . svgDetailClass { <nl> <nl> } <nl> <nl> . boxHeader { <nl> - background - color : # 686766 ; <nl> + margin - top : 5px ; <nl> + / * background - color : # 686766 ; * / <nl> + color : black ; <nl> + opacity : 0 . 25 ; <nl> + } <nl> + <nl> + . boxHeader : hover { <nl> + opacity : 1 . 0 ; <nl> } <nl> <nl> . boxHeader h6 { <nl> padding - top : 0 ! important ; <nl> - color : white ; <nl> - margin - left : 5px ; <nl> + color : black ; <nl> + margin - left : 10px ; <nl> margin - top : 0 ! important ; <nl> margin - bottom : - 15px ! important ; <nl> } <nl> <nl> . activeSwitch : hover { <nl> cursor : default ! important ; <nl> } <nl> + <nl> + . statClient : hover { <nl> + opacity : 1 ! important ; <nl> + } <nl> mmm a / html / admin / js / views / dashboardView . js <nl> ppp b / html / admin / js / views / dashboardView . js <nl> var dashboardView = Backbone . View . extend ( { <nl> ' < li class = " statClient " id = " ' + figure . identifier + ' " > ' + <nl> ' < div class = " boxHeader " > < h6 class = " dashboardH6 " > ' + figure . name + <nl> ' < / h6 > ' + <nl> - ' < i class = " icon - remove icon - white db - hide " value = " ' + figure . identifier + ' " > < / i > ' + <nl> - ' < i class = " icon - info - sign icon - white db - info " value = " ' + figure . identifier + <nl> + ' < i class = " icon - remove db - hide " value = " ' + figure . identifier + ' " > < / i > ' + <nl> + ' < i class = " icon - info - sign db - info " value = " ' + figure . identifier + <nl> ' " title = " ' + figure . description + ' " > < / i > ' + <nl> - ' < i class = " icon - zoom - in icon - white db - zoom " value = " ' + figure . identifier + ' " > < / i > ' + <nl> + ' < i class = " icon - zoom - in db - zoom " value = " ' + figure . identifier + ' " > < / i > ' + <nl> ' < / div > ' + <nl> ' < div class = " statChart " id = " ' + figure . identifier + ' Chart " > < svg class = " svgClass " / > < / div > ' + <nl> ' < / li > ' <nl>
minimized graph design
arangodb/arangodb
c6dcc833c118116263e04bf34eb4588acdb699d4
2013-08-05T13:06:11Z
mmm a / tests / Makefile <nl> ppp b / tests / Makefile <nl> <nl> CXX ? = g + + <nl> CXXFLAGS = - Wall - pedantic - std = c + + 11 - pthread - Wconversion - O3 - I . . / include - fmax - errors = 1 <nl> - LDPFALGS = - pthread <nl> + LDPFALGS = - pthread - lsystemd <nl> <nl> CPP_FILES : = $ ( wildcard * . cpp ) <nl> OBJ_FILES : = $ ( addprefix . / , $ ( notdir $ ( CPP_FILES : . cpp = . o ) ) ) <nl>
fix link to systemd in tests
gabime/spdlog
3ca19a85802f67d89cb2cb95b70922ddc48c8c75
2019-03-22T12:01:34Z
mmm a / src / heap . cc <nl> ppp b / src / heap . cc <nl> bool Heap : : Contains ( HeapObject * value ) { <nl> <nl> <nl> bool Heap : : Contains ( Address addr ) { <nl> - if ( OS : : IsOutsideAllocatedSpace ( addr ) ) return false ; <nl> + if ( isolate_ - > memory_allocator ( ) - > IsOutsideAllocatedSpace ( addr ) ) return false ; <nl> return HasBeenSetUp ( ) & & <nl> ( new_space_ . ToSpaceContains ( addr ) | | <nl> old_pointer_space_ - > Contains ( addr ) | | <nl> bool Heap : : InSpace ( HeapObject * value , AllocationSpace space ) { <nl> <nl> <nl> bool Heap : : InSpace ( Address addr , AllocationSpace space ) { <nl> - if ( OS : : IsOutsideAllocatedSpace ( addr ) ) return false ; <nl> + if ( isolate_ - > memory_allocator ( ) - > IsOutsideAllocatedSpace ( addr ) ) return false ; <nl> if ( ! HasBeenSetUp ( ) ) return false ; <nl> <nl> switch ( space ) { <nl> mmm a / src / platform - cygwin . cc <nl> ppp b / src / platform - cygwin . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> - <nl> const char * OS : : LocalTimezone ( double time ) { <nl> if ( std : : isnan ( time ) ) return " " ; <nl> time_t tv = static_cast < time_t > ( floor ( time / msPerSecond ) ) ; <nl> double OS : : LocalTimeOffset ( ) { <nl> } <nl> <nl> <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock_guard ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * address ) { <nl> - return address < lowest_ever_allocated | | address > = highest_ever_allocated ; <nl> - } <nl> - <nl> - <nl> void * OS : : Allocate ( const size_t requested , <nl> size_t * allocated , <nl> bool is_executable ) { <nl> void * OS : : Allocate ( const size_t requested , <nl> return NULL ; <nl> } <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , msize ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * base , size_t size , bool is_executable ) { <nl> if ( NULL = = VirtualAlloc ( base , size , MEM_COMMIT , prot ) ) { <nl> return false ; <nl> } <nl> - <nl> - UpdateAllocatedSpaceLimits ( base , static_cast < int > ( size ) ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / call this setup code within the same millisecond . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ; <nl> srandom ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> - } <nl> - <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> } <nl> <nl> <nl> mmm a / src / platform - freebsd . cc <nl> ppp b / src / platform - freebsd . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> - <nl> const char * OS : : LocalTimezone ( double time ) { <nl> if ( std : : isnan ( time ) ) return " " ; <nl> time_t tv = static_cast < time_t > ( floor ( time / msPerSecond ) ) ; <nl> double OS : : LocalTimeOffset ( ) { <nl> } <nl> <nl> <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock_guard ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * address ) { <nl> - return address < lowest_ever_allocated | | address > = highest_ever_allocated ; <nl> - } <nl> - <nl> - <nl> void * OS : : Allocate ( const size_t requested , <nl> size_t * allocated , <nl> bool executable ) { <nl> void * OS : : Allocate ( const size_t requested , <nl> return NULL ; <nl> } <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , msize ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * base , size_t size , bool is_executable ) { <nl> kMmapFdOffset ) ) { <nl> return false ; <nl> } <nl> - <nl> - UpdateAllocatedSpaceLimits ( base , size ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / call this setup code within the same millisecond . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ; <nl> srandom ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> - } <nl> - <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> } <nl> <nl> <nl> mmm a / src / platform - linux . cc <nl> ppp b / src / platform - linux . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> - <nl> # ifdef __arm__ <nl> <nl> bool OS : : ArmUsingHardFloat ( ) { <nl> double OS : : LocalTimeOffset ( ) { <nl> } <nl> <nl> <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock_guard ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * address ) { <nl> - return address < lowest_ever_allocated | | address > = highest_ever_allocated ; <nl> - } <nl> - <nl> - <nl> void * OS : : Allocate ( const size_t requested , <nl> size_t * allocated , <nl> bool is_executable ) { <nl> void * OS : : Allocate ( const size_t requested , <nl> return NULL ; <nl> } <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , msize ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * base , size_t size , bool is_executable ) { <nl> return false ; <nl> } <nl> <nl> - UpdateAllocatedSpaceLimits ( base , size ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / Seed the random number generator . We preserve microsecond resolution . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ^ ( getpid ( ) < < 16 ) ; <nl> srandom ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> - } <nl> - <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> } <nl> <nl> <nl> mmm a / src / platform - macos . cc <nl> ppp b / src / platform - macos . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> - <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * address ) { <nl> - return address < lowest_ever_allocated | | address > = highest_ever_allocated ; <nl> - } <nl> - <nl> - <nl> / / Constants used for mmap . <nl> / / kMmapFd is used to pass vm_alloc flags to tag the region with the user <nl> / / defined tag 255 This helps identify V8 - allocated regions in memory analysis <nl> void * OS : : Allocate ( const size_t requested , <nl> return NULL ; <nl> } <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , msize ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * address , <nl> kMmapFdOffset ) ) { <nl> return false ; <nl> } <nl> - <nl> - UpdateAllocatedSpaceLimits ( address , size ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / Seed the random number generator . We preserve microsecond resolution . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ^ ( getpid ( ) < < 16 ) ; <nl> srandom ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> - } <nl> - <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> } <nl> <nl> <nl> mmm a / src / platform - openbsd . cc <nl> ppp b / src / platform - openbsd . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> - <nl> const char * OS : : LocalTimezone ( double time ) { <nl> if ( std : : isnan ( time ) ) return " " ; <nl> time_t tv = static_cast < time_t > ( floor ( time / msPerSecond ) ) ; <nl> double OS : : LocalTimeOffset ( ) { <nl> } <nl> <nl> <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * address ) { <nl> - return address < lowest_ever_allocated | | address > = highest_ever_allocated ; <nl> - } <nl> - <nl> - <nl> void * OS : : Allocate ( const size_t requested , <nl> size_t * allocated , <nl> bool is_executable ) { <nl> void * OS : : Allocate ( const size_t requested , <nl> return NULL ; <nl> } <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , msize ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * base , size_t size , bool is_executable ) { <nl> kMmapFdOffset ) ) { <nl> return false ; <nl> } <nl> - <nl> - UpdateAllocatedSpaceLimits ( base , size ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / Seed the random number generator . We preserve microsecond resolution . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ^ ( getpid ( ) < < 16 ) ; <nl> srandom ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> - } <nl> - <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> } <nl> <nl> <nl> mmm a / src / platform - solaris . cc <nl> ppp b / src / platform - solaris . cc <nl> namespace v8 { <nl> namespace internal { <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> - <nl> const char * OS : : LocalTimezone ( double time ) { <nl> if ( std : : isnan ( time ) ) return " " ; <nl> time_t tv = static_cast < time_t > ( floor ( time / msPerSecond ) ) ; <nl> double OS : : LocalTimeOffset ( ) { <nl> } <nl> <nl> <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock_guard ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * address ) { <nl> - return address < lowest_ever_allocated | | address > = highest_ever_allocated ; <nl> - } <nl> - <nl> - <nl> void * OS : : Allocate ( const size_t requested , <nl> size_t * allocated , <nl> bool is_executable ) { <nl> void * OS : : Allocate ( const size_t requested , <nl> return NULL ; <nl> } <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , msize ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * base , size_t size , bool is_executable ) { <nl> kMmapFdOffset ) ) { <nl> return false ; <nl> } <nl> - <nl> - UpdateAllocatedSpaceLimits ( base , size ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / call this setup code within the same millisecond . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ; <nl> srandom ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> - } <nl> - <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> } <nl> <nl> <nl> mmm a / src / platform - win32 . cc <nl> ppp b / src / platform - win32 . cc <nl> double ceiling ( double x ) { <nl> } <nl> <nl> <nl> - static Mutex * limit_mutex = NULL ; <nl> - <nl> # if V8_TARGET_ARCH_IA32 <nl> static void MemMoveWrapper ( void * dest , const void * src , size_t size ) { <nl> memmove ( dest , src , size ) ; <nl> void OS : : StrNCpy ( Vector < char > dest , const char * src , size_t n ) { <nl> # undef _TRUNCATE <nl> # undef STRUNCATE <nl> <nl> - / / We keep the lowest and highest addresses mapped as a quick way of <nl> - / / determining that pointers are outside the heap ( used mostly in assertions <nl> - / / and verification ) . The estimate is conservative , i . e . , not all addresses in <nl> - / / ' allocated ' space are actually allocated to our heap . The range is <nl> - / / [ lowest , highest ) , inclusive on the low and and exclusive on the high end . <nl> - static void * lowest_ever_allocated = reinterpret_cast < void * > ( - 1 ) ; <nl> - static void * highest_ever_allocated = reinterpret_cast < void * > ( 0 ) ; <nl> - <nl> - <nl> - static void UpdateAllocatedSpaceLimits ( void * address , int size ) { <nl> - ASSERT ( limit_mutex ! = NULL ) ; <nl> - LockGuard < Mutex > lock_guard ( limit_mutex ) ; <nl> - <nl> - lowest_ever_allocated = Min ( lowest_ever_allocated , address ) ; <nl> - highest_ever_allocated = <nl> - Max ( highest_ever_allocated , <nl> - reinterpret_cast < void * > ( reinterpret_cast < char * > ( address ) + size ) ) ; <nl> - } <nl> - <nl> - <nl> - bool OS : : IsOutsideAllocatedSpace ( void * pointer ) { <nl> - if ( pointer < lowest_ever_allocated | | pointer > = highest_ever_allocated ) <nl> - return true ; <nl> - / / Ask the Windows API <nl> - if ( IsBadWritePtr ( pointer , 1 ) ) <nl> - return true ; <nl> - return false ; <nl> - } <nl> - <nl> <nl> / / Get the system ' s page size used by VirtualAlloc ( ) or the next power <nl> / / of two . The reason for always returning a power of two is that the <nl> void * OS : : Allocate ( const size_t requested , <nl> ASSERT ( IsAligned ( reinterpret_cast < size_t > ( mbase ) , OS : : AllocateAlignment ( ) ) ) ; <nl> <nl> * allocated = msize ; <nl> - UpdateAllocatedSpaceLimits ( mbase , static_cast < int > ( msize ) ) ; <nl> return mbase ; <nl> } <nl> <nl> bool VirtualMemory : : CommitRegion ( void * base , size_t size , bool is_executable ) { <nl> if ( NULL = = VirtualAlloc ( base , size , MEM_COMMIT , prot ) ) { <nl> return false ; <nl> } <nl> - <nl> - UpdateAllocatedSpaceLimits ( base , static_cast < int > ( size ) ) ; <nl> return true ; <nl> } <nl> <nl> void OS : : SetUp ( ) { <nl> / / call this setup code within the same millisecond . <nl> uint64_t seed = static_cast < uint64_t > ( TimeCurrentMillis ( ) ) ; <nl> srand ( static_cast < unsigned int > ( seed ) ) ; <nl> - limit_mutex = new Mutex ( ) ; <nl> } <nl> <nl> - <nl> - void OS : : TearDown ( ) { <nl> - delete limit_mutex ; <nl> - } <nl> - <nl> - <nl> } } / / namespace v8 : : internal <nl> mmm a / src / platform . h <nl> ppp b / src / platform . h <nl> class OS { <nl> / / called after CPU initialization . <nl> static void PostSetUp ( ) ; <nl> <nl> - / / Clean up platform - OS - related things . Called once at VM shutdown . <nl> - static void TearDown ( ) ; <nl> - <nl> / / Returns the accumulated user time for thread . This routine <nl> / / can be used for profiling . The implementation should <nl> / / strive for high - precision timer resolution , preferable <nl> class OS { <nl> / / Get the Alignment guaranteed by Allocate ( ) . <nl> static size_t AllocateAlignment ( ) ; <nl> <nl> - / / Returns an indication of whether a pointer is in a space that <nl> - / / has been allocated by Allocate ( ) . This method may conservatively <nl> - / / always return false , but giving more accurate information may <nl> - / / improve the robustness of the stack dump code in the presence of <nl> - / / heap corruption . <nl> - static bool IsOutsideAllocatedSpace ( void * pointer ) ; <nl> - <nl> / / Sleep for a number of milliseconds . <nl> static void Sleep ( const int milliseconds ) ; <nl> <nl> mmm a / src / spaces . cc <nl> ppp b / src / spaces . cc <nl> Address CodeRange : : AllocateRawMemory ( const size_t requested_size , <nl> } <nl> ASSERT ( * allocated < = current . size ) ; <nl> ASSERT ( IsAddressAligned ( current . start , MemoryChunk : : kAlignment ) ) ; <nl> - if ( ! MemoryAllocator : : CommitExecutableMemory ( code_range_ , <nl> - current . start , <nl> - commit_size , <nl> - * allocated ) ) { <nl> + if ( ! isolate_ - > memory_allocator ( ) - > CommitExecutableMemory ( code_range_ , <nl> + current . start , <nl> + commit_size , <nl> + * allocated ) ) { <nl> * allocated = 0 ; <nl> return NULL ; <nl> } <nl> Address CodeRange : : AllocateRawMemory ( const size_t requested_size , <nl> <nl> <nl> bool CodeRange : : CommitRawMemory ( Address start , size_t length ) { <nl> - return code_range_ - > Commit ( start , length , true ) ; <nl> + return isolate_ - > memory_allocator ( ) - > CommitMemory ( start , length , EXECUTABLE ) ; <nl> } <nl> <nl> <nl> MemoryAllocator : : MemoryAllocator ( Isolate * isolate ) <nl> capacity_ ( 0 ) , <nl> capacity_executable_ ( 0 ) , <nl> size_ ( 0 ) , <nl> - size_executable_ ( 0 ) { <nl> + size_executable_ ( 0 ) , <nl> + lowest_ever_allocated_ ( reinterpret_cast < void * > ( - 1 ) ) , <nl> + highest_ever_allocated_ ( reinterpret_cast < void * > ( 0 ) ) { <nl> } <nl> <nl> <nl> void MemoryAllocator : : TearDown ( ) { <nl> } <nl> <nl> <nl> + bool MemoryAllocator : : CommitMemory ( Address base , <nl> + size_t size , <nl> + Executability executable ) { <nl> + if ( ! VirtualMemory : : CommitRegion ( base , size , executable = = EXECUTABLE ) ) { <nl> + return false ; <nl> + } <nl> + UpdateAllocatedSpaceLimits ( base , base + size ) ; <nl> + return true ; <nl> + } <nl> + <nl> + <nl> void MemoryAllocator : : FreeMemory ( VirtualMemory * reservation , <nl> Executability executable ) { <nl> / / TODO ( gc ) make code_range part of memory allocator ? <nl> Address MemoryAllocator : : AllocateAlignedMemory ( size_t reserve_size , <nl> base = NULL ; <nl> } <nl> } else { <nl> - if ( ! reservation . Commit ( base , commit_size , false ) ) { <nl> + if ( reservation . Commit ( base , commit_size , false ) ) { <nl> + UpdateAllocatedSpaceLimits ( base , base + commit_size ) ; <nl> + } else { <nl> base = NULL ; <nl> } <nl> } <nl> bool MemoryChunk : : CommitArea ( size_t requested ) { <nl> Address start = address ( ) + committed_size + guard_size ; <nl> size_t length = commit_size - committed_size ; <nl> if ( reservation_ . IsReserved ( ) ) { <nl> - if ( ! reservation_ . Commit ( start , length , IsFlagSet ( IS_EXECUTABLE ) ) ) { <nl> + Executability executable = IsFlagSet ( IS_EXECUTABLE ) <nl> + ? EXECUTABLE : NOT_EXECUTABLE ; <nl> + if ( ! heap ( ) - > isolate ( ) - > memory_allocator ( ) - > CommitMemory ( <nl> + start , length , executable ) ) { <nl> return false ; <nl> } <nl> } else { <nl> void MemoryAllocator : : Free ( MemoryChunk * chunk ) { <nl> bool MemoryAllocator : : CommitBlock ( Address start , <nl> size_t size , <nl> Executability executable ) { <nl> - if ( ! VirtualMemory : : CommitRegion ( start , size , executable ) ) return false ; <nl> + if ( ! CommitMemory ( start , size , executable ) ) return false ; <nl> <nl> if ( Heap : : ShouldZapGarbage ( ) ) { <nl> ZapBlock ( start , size ) ; <nl> bool MemoryAllocator : : CommitExecutableMemory ( VirtualMemory * vm , <nl> return false ; <nl> } <nl> <nl> + UpdateAllocatedSpaceLimits ( start , <nl> + start + CodePageAreaStartOffset ( ) + <nl> + commit_size - CodePageGuardStartOffset ( ) ) ; <nl> return true ; <nl> } <nl> <nl> mmm a / src / spaces . h <nl> ppp b / src / spaces . h <nl> class MemoryAllocator { <nl> return ( Available ( ) / Page : : kPageSize ) * Page : : kMaxNonCodeHeapObjectSize ; <nl> } <nl> <nl> + / / Returns an indication of whether a pointer is in a space that has <nl> + / / been allocated by this MemoryAllocator . <nl> + V8_INLINE ( bool IsOutsideAllocatedSpace ( const void * address ) ) const { <nl> + return address < lowest_ever_allocated_ | | <nl> + address > = highest_ever_allocated_ ; <nl> + } <nl> + <nl> # ifdef DEBUG <nl> / / Reports statistic info of the space . <nl> void ReportStatistics ( ) ; <nl> class MemoryAllocator { <nl> Executability executable , <nl> VirtualMemory * controller ) ; <nl> <nl> + bool CommitMemory ( Address addr , size_t size , Executability executable ) ; <nl> + <nl> void FreeMemory ( VirtualMemory * reservation , Executability executable ) ; <nl> void FreeMemory ( Address addr , size_t size , Executability executable ) ; <nl> <nl> class MemoryAllocator { <nl> return CodePageAreaEndOffset ( ) - CodePageAreaStartOffset ( ) ; <nl> } <nl> <nl> - MUST_USE_RESULT static bool CommitExecutableMemory ( VirtualMemory * vm , <nl> - Address start , <nl> - size_t commit_size , <nl> - size_t reserved_size ) ; <nl> + MUST_USE_RESULT bool CommitExecutableMemory ( VirtualMemory * vm , <nl> + Address start , <nl> + size_t commit_size , <nl> + size_t reserved_size ) ; <nl> <nl> private : <nl> Isolate * isolate_ ; <nl> class MemoryAllocator { <nl> / / Allocated executable space size in bytes . <nl> size_t size_executable_ ; <nl> <nl> + / / We keep the lowest and highest addresses allocated as a quick way <nl> + / / of determining that pointers are outside the heap . The estimate is <nl> + / / conservative , i . e . not all addrsses in ' allocated ' space are allocated <nl> + / / to our heap . The range is [ lowest , highest [ , inclusive on the low end <nl> + / / and exclusive on the high end . <nl> + void * lowest_ever_allocated_ ; <nl> + void * highest_ever_allocated_ ; <nl> + <nl> struct MemoryAllocationCallbackRegistration { <nl> MemoryAllocationCallbackRegistration ( MemoryAllocationCallback callback , <nl> ObjectSpace space , <nl> class MemoryAllocator { <nl> Page * InitializePagesInChunk ( int chunk_id , int pages_in_chunk , <nl> PagedSpace * owner ) ; <nl> <nl> + void UpdateAllocatedSpaceLimits ( void * low , void * high ) { <nl> + lowest_ever_allocated_ = Min ( lowest_ever_allocated_ , low ) ; <nl> + highest_ever_allocated_ = Max ( highest_ever_allocated_ , high ) ; <nl> + } <nl> + <nl> DISALLOW_IMPLICIT_CONSTRUCTORS ( MemoryAllocator ) ; <nl> } ; <nl> <nl> mmm a / src / v8 . cc <nl> ppp b / src / v8 . cc <nl> void V8 : : TearDown ( ) { <nl> call_completed_callbacks_ = NULL ; <nl> <nl> Sampler : : TearDown ( ) ; <nl> - OS : : TearDown ( ) ; <nl> } <nl> <nl> <nl> mmm a / test / cctest / test - alloc . cc <nl> ppp b / test / cctest / test - alloc . cc <nl> class Block { <nl> <nl> TEST ( CodeRange ) { <nl> const int code_range_size = 32 * MB ; <nl> - OS : : SetUp ( ) ; <nl> - Isolate : : Current ( ) - > InitializeLoggingAndCounters ( ) ; <nl> - CodeRange * code_range = new CodeRange ( Isolate : : Current ( ) ) ; <nl> - code_range - > SetUp ( code_range_size ) ; <nl> + CcTest : : InitializeVM ( ) ; <nl> + CodeRange code_range ( reinterpret_cast < Isolate * > ( CcTest : : isolate ( ) ) ) ; <nl> + code_range . SetUp ( code_range_size ) ; <nl> int current_allocated = 0 ; <nl> int total_allocated = 0 ; <nl> List < Block > blocks ( 1000 ) ; <nl> TEST ( CodeRange ) { <nl> ( Page : : kMaxNonCodeHeapObjectSize < < ( Pseudorandom ( ) % 3 ) ) + <nl> Pseudorandom ( ) % 5000 + 1 ; <nl> size_t allocated = 0 ; <nl> - Address base = code_range - > AllocateRawMemory ( requested , <nl> - requested , <nl> - & allocated ) ; <nl> + Address base = code_range . AllocateRawMemory ( requested , <nl> + requested , <nl> + & allocated ) ; <nl> CHECK ( base ! = NULL ) ; <nl> blocks . Add ( Block ( base , static_cast < int > ( allocated ) ) ) ; <nl> current_allocated + = static_cast < int > ( allocated ) ; <nl> TEST ( CodeRange ) { <nl> } else { <nl> / / Free a block . <nl> int index = Pseudorandom ( ) % blocks . length ( ) ; <nl> - code_range - > FreeRawMemory ( blocks [ index ] . base , blocks [ index ] . size ) ; <nl> + code_range . FreeRawMemory ( blocks [ index ] . base , blocks [ index ] . size ) ; <nl> current_allocated - = blocks [ index ] . size ; <nl> if ( index < blocks . length ( ) - 1 ) { <nl> blocks [ index ] = blocks . RemoveLast ( ) ; <nl> TEST ( CodeRange ) { <nl> } <nl> } <nl> <nl> - code_range - > TearDown ( ) ; <nl> - delete code_range ; <nl> + code_range . TearDown ( ) ; <nl> } <nl>
Drop OS : : IsOutsideAllocatedSpace ( ) and move the tracking to the MemoryAllocator .
v8/v8
2fdadd779460aa5503bbd814c44c9df129276e8c
2013-09-05T08:17:57Z
mmm a / hphp / hack / src / naming / naming_global . ml <nl> ppp b / hphp / hack / src / naming / naming_global . ml <nl> module GEnv = struct <nl> raise File_provider . File_provider_stale <nl> <nl> let type_canon_name ctx name = <nl> - Naming_heap . Types . get_canon_name ctx ( canon_key name ) <nl> + Naming_provider . get_type_canon_name ctx ( canon_key name ) <nl> <nl> let type_pos ctx name = <nl> let name = Option . value ( type_canon_name ctx name ) ~ default : name in <nl> module Env = struct <nl> | Naming_types . TTypedef - > FileInfo . Typedef <nl> | Naming_types . TRecordDef - > FileInfo . RecordDef <nl> in <nl> - match Naming_heap . Types . get_canon_name ctx name_key with <nl> + match Naming_provider . get_type_canon_name ctx name_key with <nl> | Some _ - > ( ) <nl> | None - > <nl> ( * We store redundant info in this case , but if the position is a * ) <nl> module Env = struct <nl> ( ) <nl> else <nl> let name_key = canon_key name in <nl> - match Naming_heap . Types . get_canon_name ctx name_key with <nl> + match Naming_provider . get_type_canon_name ctx name_key with <nl> | Some canonical - > validate canonical Errors . error_name_already_bound <nl> | None - > <nl> ( * Check to prevent collision with attribute classes <nl> module Env = struct <nl> attr_prefix ^ String . sub name_key 1 ( name_len - 1 ) <nl> in <nl> begin <nl> - match Naming_heap . Types . get_canon_name ctx alt_name_key with <nl> + match Naming_provider . get_type_canon_name ctx alt_name_key with <nl> | Some alt_canonical - > <nl> validate alt_canonical Errors . error_class_attribute_already_bound <nl> | None - > ( ) <nl> mmm a / hphp / hack / src / providers / naming_provider . ml <nl> ppp b / hphp / hack / src / providers / naming_provider . ml <nl> let get_type_pos_and_kind ( name : string ) : <nl> let get_type_path_and_kind ( name : string ) : <nl> ( Relative_path . t * Naming_types . kind_of_type ) option = <nl> Naming_heap . Types . get_filename_and_kind name <nl> + <nl> + let get_type_canon_name ( ctx : Provider_context . t ) ( name : string ) : <nl> + string option = <nl> + Naming_heap . Types . get_canon_name ctx name <nl> mmm a / hphp / hack / src / providers / naming_provider . mli <nl> ppp b / hphp / hack / src / providers / naming_provider . mli <nl> val get_type_pos_and_kind : <nl> reverse naming table . * ) <nl> val get_type_path_and_kind : <nl> string - > ( Relative_path . t * Naming_types . kind_of_type ) option <nl> + <nl> + ( * * Look up the canonical name for the given type . * ) <nl> + val get_type_canon_name : Provider_context . t - > string - > string option <nl>
Create ` Naming_provider . get_canon_name `
facebook/hhvm
64dcc5a2bb4324d0ed26b85d59fb6a873025e986
2020-02-29T01:09:18Z
mmm a / hphp / runtime / base / string - buffer . cpp <nl> ppp b / hphp / runtime / base / string - buffer . cpp <nl> void StringBuffer : : clear ( ) { <nl> <nl> void StringBuffer : : release ( ) { <nl> if ( m_str ) { <nl> + assert ( m_str - > getCount ( ) = = 0 ) ; <nl> m_buffer [ m_len ] = 0 ; / / appease StringData : : checkSane ( ) <nl> m_str - > release ( ) ; <nl> } <nl> char * StringBuffer : : appendCursor ( int size ) { <nl> } else if ( m_cap - m_len < size ) { <nl> m_buffer [ m_len ] = 0 ; <nl> m_str - > setSize ( m_len ) ; <nl> - MutableSlice s = m_str - > reserve ( m_len + size ) ; <nl> + auto const tmp = m_str - > reserve ( m_len + size ) ; <nl> + if ( UNLIKELY ( tmp ! = m_str ) ) { <nl> + assert ( m_str - > getCount ( ) = = 0 ) ; <nl> + m_str - > release ( ) ; <nl> + m_str = tmp ; <nl> + } <nl> + auto const s = m_str - > mutableSlice ( ) ; <nl> m_buffer = s . ptr ; <nl> m_cap = s . len ; <nl> } <nl> void StringBuffer : : growBy ( int spaceRequired ) { <nl> <nl> m_buffer [ m_len ] = 0 ; <nl> m_str - > setSize ( m_len ) ; <nl> - MutableSlice s = m_str - > reserve ( new_size ) ; <nl> + auto const tmp = m_str - > reserve ( new_size ) ; <nl> + if ( UNLIKELY ( tmp ! = m_str ) ) { <nl> + assert ( m_str - > getCount ( ) = = 0 ) ; <nl> + m_str - > release ( ) ; <nl> + m_str = tmp ; <nl> + } <nl> + auto const s = m_str - > mutableSlice ( ) ; <nl> m_buffer = s . ptr ; <nl> m_cap = s . len ; <nl> } <nl> mmm a / hphp / runtime / base / string - data - inl . h <nl> ppp b / hphp / runtime / base / string - data - inl . h <nl> inline StringData * StringData : : Make ( const StringData * s1 , const char * lit2 ) { <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> - inline StringData * StringData : : MakeMalloced ( const char * data , int len ) { <nl> - auto const sd = static_cast < StringData * > ( malloc ( sizeof ( StringData ) ) ) ; <nl> - try { <nl> - sd - > initMalloc ( data , len ) ; <nl> - } catch ( . . . ) { <nl> - free ( sd ) ; <nl> - throw ; <nl> - } <nl> - assert ( sd - > checkSane ( ) ) ; <nl> - return sd ; <nl> - } <nl> - <nl> - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> - <nl> inline void StringData : : destruct ( ) { <nl> assert ( checkSane ( ) ) ; <nl> <nl> / / N . B . APC code assumes it is legal to call destruct ( ) on a static <nl> / / string . Probably it shouldn ' t do that . . . . <nl> if ( ! isStatic ( ) ) { <nl> - releaseDataSlowPath ( ) ; <nl> + assert ( m_data = = static_cast < void * > ( this + 1 ) ) ; <nl> free ( this ) ; <nl> } <nl> } <nl> inline void StringData : : invalidateHash ( ) { <nl> assert ( ! isImmutable ( ) ) ; <nl> assert ( getCount ( ) < = 1 ) ; <nl> m_hash = 0 ; <nl> + assert ( checkSane ( ) ) ; <nl> } <nl> <nl> inline void StringData : : setSize ( int len ) { <nl> inline void StringData : : setSize ( int len ) { <nl> m_data [ len ] = 0 ; <nl> m_len = len ; <nl> m_hash = 0 ; <nl> + assert ( checkSane ( ) ) ; <nl> } <nl> <nl> inline StringData * StringData : : modifyChar ( int offset , char c ) { <nl> assert ( offset > = 0 & & offset < size ( ) & & ! isStatic ( ) ) ; <nl> assert ( getCount ( ) < = 1 ) ; <nl> <nl> - if ( isImmutable ( ) ) escalate ( size ( ) ) ; <nl> - m_data [ offset ] = c ; <nl> - m_hash = 0 ; <nl> - <nl> - return this ; <nl> + auto const sd = isShared ( ) ? escalate ( size ( ) ) : this ; <nl> + sd - > m_data [ offset ] = c ; <nl> + sd - > m_hash = 0 ; <nl> + return sd ; <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> inline StringData * StringData : : modifyChar ( int offset , char c ) { <nl> } <nl> <nl> # endif <nl> - <nl> - <nl> mmm a / hphp / runtime / base / string - data . cpp <nl> ppp b / hphp / runtime / base / string - data . cpp <nl> StringData * StringData : : Make ( const char * data , CopyStringMode ) { <nl> } <nl> <nl> HOT_FUNC <nl> - void StringData : : initMalloc ( const char * data , int len ) { <nl> + StringData * StringData : : MakeMalloced ( const char * data , int len ) { <nl> if ( UNLIKELY ( uint32_t ( len ) > MaxSize ) ) { <nl> throw_string_too_large ( len ) ; <nl> } <nl> <nl> - m_lenAndCount = len ; <nl> - m_capAndHash = - static_cast < uint32_t > ( len + 1 ) ; / / cap < 0 means malloc ' d <nl> - m_data = static_cast < char * > ( malloc ( len + 1 ) ) ; <nl> + auto const cap = static_cast < uint32_t > ( len ) + 1 ; <nl> + auto const sd = static_cast < StringData * > ( <nl> + std : : malloc ( sizeof ( StringData ) + cap ) <nl> + ) ; <nl> <nl> - m_data [ len ] = 0 ; <nl> - memcpy ( m_data , data , len ) ; <nl> + sd - > m_lenAndCount = len ; <nl> + sd - > m_capAndHash = cap ; <nl> + sd - > m_data = reinterpret_cast < char * > ( sd + 1 ) ; <nl> <nl> - assert ( m_hash = = 0 ) ; <nl> - assert ( m_count = = 0 ) ; <nl> - assert ( checkSane ( ) ) ; <nl> - assert ( mode ( ) = = Mode : : Malloc ) ; <nl> + sd - > m_data [ len ] = 0 ; <nl> + auto const mcret = memcpy ( sd - > m_data , data , len ) ; <nl> + auto const ret = reinterpret_cast < StringData * > ( mcret ) - 1 ; <nl> + <nl> + assert ( ret = = sd ) ; <nl> + assert ( ret - > m_hash = = 0 ) ; <nl> + assert ( ret - > m_count = = 0 ) ; <nl> + assert ( ret - > isFlat ( ) ) ; <nl> + assert ( ret - > checkSane ( ) ) ; <nl> + return ret ; <nl> } <nl> <nl> HOT_FUNC <nl> StringData * StringData : : Make ( StringSlice s1 , const char * lit2 ) { <nl> HOT_FUNC NEVER_INLINE <nl> void StringData : : releaseDataSlowPath ( ) { <nl> assert ( ! isFlat ( ) ) ; <nl> + assert ( isShared ( ) ) ; <nl> assert ( checkSane ( ) ) ; <nl> <nl> - auto const loadedMode = modeNonFlat ( ) ; <nl> - <nl> - if ( loadedMode = = Mode : : Smart ) { <nl> - smart_free ( m_data ) ; <nl> - freeForSize ( this , sizeof ( StringData ) + promotedPayload ( ) - > oldFlatCap ) ; <nl> - return ; <nl> - } <nl> - <nl> - if ( loadedMode = = Mode : : Shared ) { <nl> - sharedPayload ( ) - > shared - > decRef ( ) ; <nl> - delist ( ) ; <nl> - freeForSize ( this , sizeof ( StringData ) + sizeof ( SharedPayload ) ) ; <nl> - return ; <nl> - } <nl> - <nl> - assert ( loadedMode = = Mode : : Malloc ) ; <nl> - free ( m_data ) ; <nl> + sharedPayload ( ) - > shared - > decRef ( ) ; <nl> + delist ( ) ; <nl> + freeForSize ( this , sizeof ( StringData ) + sizeof ( SharedPayload ) ) ; <nl> } <nl> <nl> HOT_FUNC <nl> StringData * StringData : : Make ( int reserveLen ) { <nl> return sd ; <nl> } <nl> <nl> - void StringData : : append ( const char * s , int len ) { <nl> + StringData * StringData : : append ( StringSlice range ) { <nl> assert ( ! isStatic ( ) & & getCount ( ) < = 1 ) ; <nl> <nl> - if ( len = = 0 ) return ; <nl> + auto s = range . ptr ; <nl> + auto const len = range . len ; <nl> + <nl> + if ( len = = 0 ) return this ; <nl> if ( UNLIKELY ( uint32_t ( len ) > MaxSize ) ) { <nl> throw_string_too_large ( len ) ; <nl> } <nl> void StringData : : append ( const char * s , int len ) { <nl> throw_string_too_large2 ( size_t ( len ) + size_t ( m_len ) ) ; <nl> } <nl> <nl> - const uint32_t newLen = m_len + len ; <nl> + auto const newLen = m_len + len ; <nl> <nl> / * <nl> - * In case we ' re being to asked to append our own string , we need to <nl> - * load the old pointer value ( it might change when we reserve <nl> - * below ) . <nl> - * <nl> - * We don ' t allow appending with an interior pointers here , although <nl> - * we may be asked to append less than the whole string . <nl> + * We may have an aliasing append . We don ' t allow appending with an <nl> + * interior pointer , although we may be asked to append less than <nl> + * the whole string in an aliasing situation . <nl> * / <nl> - auto const oldDataPtr = rawdata ( ) ; <nl> assert ( uintptr_t ( s ) < = uintptr_t ( rawdata ( ) ) | | <nl> uintptr_t ( s ) > = uintptr_t ( rawdata ( ) + capacity ( ) ) ) ; <nl> assert ( s ! = rawdata ( ) | | len < = m_len ) ; <nl> <nl> - auto const mslice = UNLIKELY ( isShared ( ) ) ? escalate ( newLen ) <nl> + auto const target = UNLIKELY ( isShared ( ) ) ? escalate ( newLen ) <nl> : reserve ( newLen ) ; <nl> - if ( UNLIKELY ( s = = oldDataPtr ) ) s = mslice . ptr ; <nl> + auto const mslice = target - > mutableSlice ( ) ; <nl> <nl> / * <nl> * memcpy is safe even if it ' s a self appendmmmthe regions will be <nl> - * disjoint , since s can ' t point past our oldDataPtr , and len is <nl> - * smaller than the old length . <nl> + * disjoint , since s can ' t point past the start of our source <nl> + * pointer , and len is smaller than the old length . <nl> * / <nl> memcpy ( mslice . ptr + m_len , s , len ) ; <nl> <nl> - setSize ( newLen ) ; <nl> - assert ( checkSane ( ) ) ; <nl> - } <nl> - <nl> - MutableSlice StringData : : reserve ( int cap ) { <nl> - assert ( ! isImmutable ( ) & & m_count < = 1 & & cap > = 0 ) ; <nl> - if ( cap + 1 < = capacity ( ) ) return mutableSlice ( ) ; <nl> - <nl> - switch ( mode ( ) ) { <nl> - default : assert ( false ) ; <nl> - case Mode : : Flat : <nl> - { <nl> - auto const newData = static_cast < char * > ( smart_malloc ( cap + 1 ) ) ; <nl> - memcpy ( newData , m_data , m_len + 1 ) ; / / includes \ 0 <nl> - m_data = newData ; <nl> - promotedPayload ( ) - > oldFlatCap = m_cap ; <nl> - setModeAndCap ( Mode : : Smart , cap + 1 ) ; <nl> - } <nl> - break ; <nl> - case Mode : : Smart : <nl> - / / We only use geometric growth when we ' re heading to the smart <nl> - / / allocator . This is mostly because it was what was tested as <nl> - / / a perf win , but it might make sense to do it for Mode : : Malloc <nl> - / / as well . Will be revisited soon . <nl> - cap + = cap > > 2 ; <nl> - if ( cap > MaxCap ) cap = MaxCap ; <nl> - m_data = static_cast < char * > ( smart_realloc ( m_data , cap + 1 ) ) ; <nl> - setModeAndCap ( Mode : : Smart , cap + 1 ) ; <nl> - break ; <nl> - case Mode : : Malloc : <nl> - m_data = static_cast < char * > ( realloc ( m_data , cap + 1 ) ) ; <nl> - setModeAndCap ( Mode : : Malloc , cap + 1 ) ; <nl> - break ; <nl> - } <nl> + target - > setSize ( newLen ) ; <nl> + assert ( target - > checkSane ( ) ) ; <nl> <nl> - assert ( checkSane ( ) ) ; <nl> - return MutableSlice ( m_data , cap ) ; <nl> + return target ; <nl> } <nl> <nl> - StringData * StringData : : shrink ( int len ) { <nl> - setSize ( len ) ; <nl> + StringData * StringData : : reserve ( int cap ) { <nl> + assert ( ! isImmutable ( ) & & m_count < = 1 & & cap > = 0 ) ; <nl> + assert ( isFlat ( ) ) ; <nl> <nl> - / / Only shrink allocation for malloc ' d strings . <nl> - if ( mode ( ) = = Mode : : Malloc ) { <nl> - m_data = ( char * ) realloc ( m_data , len + 1 ) ; <nl> - setModeAndCap ( Mode : : Malloc , len + 1 ) ; <nl> - } <nl> + if ( cap + 1 < = capacity ( ) ) return this ; <nl> <nl> - return this ; <nl> + cap + = cap > > 2 ; <nl> + if ( cap > MaxCap ) cap = MaxCap ; <nl> + auto const sd = Make ( cap ) ; <nl> + auto const src = slice ( ) ; <nl> + auto const dst = sd - > mutableData ( ) ; <nl> + sd - > setSize ( src . len ) ; <nl> + auto const mcret = memcpy ( dst , src . ptr , src . len ) ; <nl> + auto const ret = static_cast < StringData * > ( mcret ) - 1 ; <nl> + assert ( ret = = sd ) ; <nl> + assert ( ret - > checkSane ( ) ) ; <nl> + return ret ; <nl> } <nl> <nl> StringData * StringData : : copy ( bool sharedMemory / * = false * / ) const { <nl> StringData * StringData : : copy ( bool sharedMemory / * = false * / ) const { <nl> return StringData : : Make ( slice ( ) , CopyString ) ; <nl> } <nl> <nl> - / * <nl> - * Change to smart - malloced string . Then returns a mutable slice of <nl> - * the usable string buffer ( minus space for the null terminator ) . <nl> - * / <nl> - MutableSlice StringData : : escalate ( uint32_t cap ) { <nl> + / / State transition from Mode : : Shared to Mode : : Flat . <nl> + StringData * StringData : : escalate ( uint32_t cap ) { <nl> assert ( isShared ( ) & & ! isStatic ( ) & & cap > = m_len ) ; <nl> <nl> - auto const buf = static_cast < char * > ( smart_malloc ( cap + 1 ) ) ; <nl> - auto const s = slice ( ) ; <nl> - memcpy ( buf , s . ptr , s . len ) ; <nl> - buf [ s . len ] = 0 ; <nl> - <nl> - sharedPayload ( ) - > shared - > decRef ( ) ; <nl> - delist ( ) ; <nl> - <nl> - / / We have to store this so we know what to free later . <nl> - promotedPayload ( ) - > oldFlatCap = sizeof ( SharedPayload ) ; <nl> - <nl> - m_data = buf ; <nl> - setModeAndCap ( Mode : : Smart , cap + 1 ) ; <nl> - / / clear precomputed hashcode XXX why <nl> - m_hash = 0 ; <nl> - assert ( checkSane ( ) ) ; <nl> - return MutableSlice ( buf , cap ) ; <nl> + auto const sd = Make ( cap ) ; <nl> + auto const src = slice ( ) ; <nl> + auto const dst = sd - > mutableData ( ) ; <nl> + sd - > setSize ( src . len ) ; <nl> + auto const mcret = memcpy ( dst , src . ptr , src . len ) ; <nl> + auto const ret = static_cast < StringData * > ( mcret ) - 1 ; <nl> + assert ( ret = = sd ) ; <nl> + assert ( ret - > checkSane ( ) ) ; <nl> + return ret ; <nl> } <nl> <nl> void StringData : : dump ( ) const { <nl> StringData * StringData : : getChar ( int offset ) const { <nl> return GetStaticString ( " " ) ; <nl> } <nl> <nl> - void StringData : : inc ( ) { <nl> + StringData * StringData : : increment ( ) { <nl> assert ( ! isStatic ( ) ) ; <nl> assert ( ! empty ( ) ) ; <nl> <nl> - if ( isImmutable ( ) ) { <nl> - escalate ( m_len + 1 ) ; <nl> - } else { <nl> - reserve ( m_len + 1 ) ; <nl> - } <nl> + auto const sd = UNLIKELY ( isShared ( ) ) <nl> + ? escalate ( m_len + 1 ) <nl> + : reserve ( m_len + 1 ) ; <nl> + sd - > incrementHelper ( ) ; <nl> + return sd ; <nl> + } <nl> + <nl> + void StringData : : incrementHelper ( ) { <nl> m_hash = 0 ; <nl> <nl> enum class CharKind { <nl> bool StringData : : checkSane ( ) const { <nl> assert ( m_data & & m_data ! = voidPayload ( ) ) ; <nl> } <nl> <nl> - if ( isSmart ( ) ) { <nl> - assert ( promotedPayload ( ) - > oldFlatCap < capacity ( ) ) ; <nl> - assert ( promotedPayload ( ) - > oldFlatCap > = sizeof ( PromotedPayload ) ) ; <nl> - } <nl> - <nl> return true ; <nl> } <nl> <nl> mmm a / hphp / runtime / base / string - data . h <nl> ppp b / hphp / runtime / base / string - data . h <nl> enum ReserveStringMode { ReserveString } ; <nl> * Here ' s a breakdown of string modes , and which configurations are <nl> * allowed in which allocation mode : <nl> * <nl> - * | MakeLowMalloced | MakeMalloced | Normal Make ( request local ) <nl> - * + mmmmmmmmmmmmmmm - - + mmmmmmmmmmmmmmm - + mmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> - * Flat | X | | X <nl> - * Smart | | | X <nl> - * Malloc | | X | <nl> - * Shared | | | X <nl> - * <nl> - * The mode discrimination logic is the following : <nl> - * <nl> - * mode : = m_data = = this + 1 ? Flat : <nl> - * m_cap > 0 ? Smart : <nl> - * m_cap = = 0 ? Shared : Malloc ; <nl> - * <nl> - * ( For this , in Malloc mode , the buffer capacity is actually - m_cap . ) <nl> + * | LowMalloced | Malloced | Normal ( request local ) <nl> + * + mmmmmmmmmmmm - + mmmmmmmmm - + mmmmmmmmmmmmmmmmmmmmmmmm <nl> + * Flat | X | X | X <nl> + * Shared | | | X <nl> * / <nl> - class StringData { <nl> - StringData ( const StringData & ) ; / / disable copying <nl> - StringData & operator = ( const StringData & ) ; <nl> - <nl> - enum class Mode : uint8_t { <nl> - Flat = 0x0 , / / string immediately follows StringData in memory <nl> - Shared = 0x1 , / / shared memory string <nl> - Malloc = 0x2 , / / m_big . data is malloc ' d <nl> - Smart = 0x3 , / / m_big . data is smart_malloc ' d <nl> - } ; <nl> - <nl> - / / When a string transitions from either Flat or Shared to Smart , <nl> - / / we need to keep the old capacity around in the previous Flat <nl> - / / slot so we know what to tell the allocator the size was when we <nl> - / / free this . <nl> - / / <nl> - / / TODO ( # 1802148 ) : make append ( ) always allocate a new string so <nl> - / / Mode : : Smart can go away . <nl> - struct PromotedPayload { <nl> - uint32_t oldFlatCap ; <nl> - } ; <nl> - <nl> - struct SharedPayload { <nl> - SweepNode node ; <nl> - SharedVariant * shared ; <nl> - } ; <nl> - <nl> - public : <nl> + struct StringData { <nl> / * <nl> * Max length of a string , not counting the terminal 0 . <nl> * <nl> class StringData { <nl> * <nl> * StringDatas allocated with this function must be freed by calling <nl> * destruct ( ) , instead of release ( ) . <nl> + * <nl> + * Important : no string functions which change the StringData may be <nl> + * called on the returned pointer ( e . g . append ) . These functions <nl> + * below are marked by saying they require the string to be request <nl> + * local . <nl> * / <nl> static StringData * MakeMalloced ( const char * data , int len ) ; <nl> <nl> class StringData { <nl> return nullptr ; <nl> } <nl> <nl> - void append ( StringSlice r ) { append ( r . ptr , r . len ) ; } <nl> - void append ( const char * s , int len ) ; <nl> + / * <nl> + * Append the supplied range to this string . If there is not <nl> + * sufficient capacity in this string to contain the range , a new <nl> + * string may be returned . <nl> + * <nl> + * Pre : ! isStatic ( ) & & getCount ( ) < = 1 <nl> + * Pre : the string is request - local <nl> + * / <nl> + StringData * append ( StringSlice r ) ; <nl> + <nl> + / / TODO ( # 2846749 ) : replace uses with appropriate : : Make calls . <nl> StringData * copy ( bool sharedMemory = false ) const ; <nl> <nl> / * <nl> * Reserve space for a string of length ` maxLen ' ( not counting null <nl> * terminator ) . <nl> * <nl> - * Returns a slice with the same extents as mutableSlice . <nl> + * May not be called for strings created with MakeMalloced or <nl> + * MakeLowMalloced . <nl> + * <nl> + * Returns : possibly a new StringData , if we had to reallocate . The <nl> + * returned pointer is not yet incref ' d . <nl> * / <nl> - MutableSlice reserve ( int maxLen ) ; <nl> + StringData * reserve ( int maxLen ) ; <nl> <nl> / * <nl> * Returns a mutable slice with extents sized to the * buffer * this <nl> class StringData { <nl> return StringSlice ( m_data , m_len ) ; <nl> } <nl> <nl> - StringData * shrink ( int len ) ; / / setSize and maybe realloc <nl> - <nl> / * <nl> * If external users of this object want to modify it ( e . g . through <nl> * mutableSlice or mutableData ( ) ) , they are responsible for either <nl> class StringData { <nl> * <nl> * For shared strings , returns zero . <nl> * / <nl> - uint32_t capacity ( ) const { <nl> - return std : : abs ( m_cap ) ; <nl> - } <nl> + uint32_t capacity ( ) const { return m_cap ; } <nl> <nl> DataType isNumericWithVal ( int64_t & lval , double & dval , int allow_errors ) const ; <nl> bool isNumeric ( ) const ; <nl> class StringData { <nl> * Pre : offset > = 0 & & offset < size ( ) <nl> * getCount ( ) < = 1 <nl> * ! isStatic ( ) <nl> + * string must be request local <nl> * / <nl> StringData * modifyChar ( int offset , char c ) ; <nl> <nl> class StringData { <nl> * / <nl> StringData * getChar ( int offset ) const ; <nl> <nl> - void inc ( ) ; <nl> + / * <nl> + * Increment this string in the manner of php ' s + + operator . May <nl> + * return a new string if it had to resize . <nl> + * <nl> + * Pre : ! isStatic ( ) & & ! isEmpty ( ) <nl> + * string must be request local <nl> + * / <nl> + StringData * increment ( ) ; <nl> <nl> / * <nl> * Type conversion functions . <nl> class StringData { <nl> static uint32_t DefCnsHandle ( const StringData * cnsName , bool persistent ) ; <nl> static Array GetConstants ( ) ; <nl> <nl> + private : <nl> + struct SharedPayload { <nl> + SweepNode node ; <nl> + SharedVariant * shared ; <nl> + } ; <nl> + <nl> private : <nl> static StringData * MakeLowMalloced ( StringSlice ) ; <nl> static StringData * InsertStaticString ( StringSlice ) ; <nl> <nl> + StringData ( const StringData & ) = delete ; <nl> + StringData & operator = ( const StringData & ) = delete ; <nl> ~ StringData ( ) = delete ; <nl> <nl> private : <nl> class StringData { <nl> SharedPayload * sharedPayload ( ) { <nl> return static_cast < SharedPayload * > ( voidPayload ( ) ) ; <nl> } <nl> - const PromotedPayload * promotedPayload ( ) const { <nl> - return static_cast < const PromotedPayload * > ( voidPayload ( ) ) ; <nl> - } <nl> - PromotedPayload * promotedPayload ( ) { <nl> - return static_cast < PromotedPayload * > ( voidPayload ( ) ) ; <nl> - } <nl> <nl> - void initMalloc ( const char * data , int len ) ; <nl> void releaseData ( ) ; <nl> void releaseDataSlowPath ( ) ; <nl> int numericCompare ( const StringData * v2 ) const ; <nl> - MutableSlice escalate ( uint32_t cap ) ; <nl> + StringData * escalate ( uint32_t cap ) ; <nl> void enlist ( ) ; <nl> void delist ( ) ; <nl> + void incrementHelper ( ) ; <nl> <nl> void destructLowMalloc ( ) ATTRIBUTE_COLD ; <nl> <nl> class StringData { <nl> bool isShared ( ) const { return ! m_cap ; } <nl> bool isImmutable ( ) const { return isStatic ( ) | | isShared ( ) ; } <nl> bool isFlat ( ) const { return m_data = = voidPayload ( ) ; } <nl> - bool isSmart ( ) const { return ! isFlat ( ) & & m_cap > 0 ; } <nl> - <nl> - Mode modeNonFlat ( ) const { <nl> - assert ( ! isFlat ( ) ) ; <nl> - return m_cap > 0 ? Mode : : Smart : <nl> - m_cap = = 0 ? Mode : : Shared : Mode : : Malloc ; <nl> - } <nl> - <nl> - Mode mode ( ) const { <nl> - if ( isFlat ( ) ) return Mode : : Flat ; <nl> - return modeNonFlat ( ) ; <nl> - } <nl> - <nl> - void setModeAndCap ( Mode newMode , uint32_t cap ) { <nl> - assert ( newMode ! = Mode : : Flat ) ; <nl> - assert ( cap < std : : numeric_limits < int32_t > : : max ( ) ) ; <nl> - m_cap = newMode = = Mode : : Smart ? cap : <nl> - newMode = = Mode : : Shared ? 0 : - cap ; <nl> - assert ( mode ( ) = = newMode ) ; <nl> - } <nl> <nl> / / Only call preCompute ( ) and setStatic ( ) in a thread - neutral context ! <nl> void preCompute ( ) const ; <nl> mmm a / hphp / runtime / base / tv - arith . cpp <nl> ppp b / hphp / runtime / base / tv - arith . cpp <nl> struct Inc { <nl> <nl> void nonNumericString ( Cell & cell ) const { <nl> auto const sd = cell . m_data . pstr ; <nl> - auto const newSd = StringData : : Make ( sd , CopyString ) ; <nl> - newSd - > inc ( ) ; <nl> + auto const newSd = [ & ] ( ) - > StringData * { <nl> + auto const tmp = StringData : : Make ( sd , CopyString ) ; <nl> + auto const tmp2 = tmp - > increment ( ) ; <nl> + if ( tmp2 ! = tmp ) { <nl> + assert ( tmp - > getCount ( ) = = 0 ) ; <nl> + tmp - > release ( ) ; <nl> + return tmp2 ; <nl> + } <nl> + return tmp ; <nl> + } ( ) ; <nl> newSd - > incRefCount ( ) ; <nl> decRefStr ( sd ) ; <nl> cellCopy ( make_tv < KindOfString > ( newSd ) , cell ) ; <nl> mmm a / hphp / runtime / base / type - string . cpp <nl> ppp b / hphp / runtime / base / type - string . cpp <nl> String & String : : operator + = ( litstr s ) { <nl> m_px = StringData : : Make ( s , CopyString ) ; <nl> m_px - > setRefCount ( 1 ) ; <nl> } else if ( m_px - > getCount ( ) = = 1 ) { <nl> - m_px - > append ( s , strlen ( s ) ) ; <nl> + auto const tmp = m_px - > append ( StringSlice ( s , strlen ( s ) ) ) ; <nl> + if ( UNLIKELY ( tmp ! = m_px ) ) StringBase : : operator = ( tmp ) ; <nl> } else { <nl> StringData * px = StringData : : Make ( m_px , s ) ; <nl> px - > setRefCount ( 1 ) ; <nl> String & String : : operator + = ( CStrRef str ) { <nl> if ( empty ( ) ) { <nl> StringBase : : operator = ( str . m_px ) ; <nl> } else if ( m_px - > getCount ( ) = = 1 ) { <nl> - m_px - > append ( str . slice ( ) ) ; <nl> + auto tmp = m_px - > append ( str . slice ( ) ) ; <nl> + if ( UNLIKELY ( tmp ! = m_px ) ) StringBase : : operator = ( tmp ) ; <nl> } else { <nl> StringData * px = StringData : : Make ( m_px , str . slice ( ) ) ; <nl> decRefStr ( m_px ) ; <nl> String & String : : operator + = ( const StringSlice & slice ) { <nl> return * this ; <nl> } <nl> if ( m_px & & m_px - > getCount ( ) = = 1 ) { <nl> - m_px - > append ( slice ) ; <nl> + auto const tmp = m_px - > append ( slice ) ; <nl> + if ( UNLIKELY ( tmp ! = m_px ) ) StringBase : : operator = ( tmp ) ; <nl> return * this ; <nl> } <nl> if ( empty ( ) ) { <nl> mmm a / hphp / runtime / base / type - string . h <nl> ppp b / hphp / runtime / base / type - string . h <nl> class String : protected SmartPtr < StringData > { <nl> } <nl> CStrRef shrink ( int len ) { <nl> assert ( m_px ) ; <nl> - m_px - > shrink ( len ) ; <nl> + m_px - > setSize ( len ) ; <nl> return * this ; <nl> } <nl> MutableSlice reserve ( int size ) { <nl> - return m_px ? m_px - > reserve ( size ) : MutableSlice ( " " , 0 ) ; <nl> + if ( ! m_px ) return MutableSlice ( " " , 0 ) ; <nl> + auto const tmp = m_px - > reserve ( size ) ; <nl> + if ( UNLIKELY ( tmp ! = m_px ) ) StringBase : : operator = ( tmp ) ; <nl> + return m_px - > mutableSlice ( ) ; <nl> } <nl> const char * c_str ( ) const { <nl> return m_px ? m_px - > data ( ) : " " ; <nl> mmm a / hphp / runtime / base / type - variant . h <nl> ppp b / hphp / runtime / base / type - variant . h <nl> inline Variant & concat_assign ( Variant & v1 , litstr s2 ) = delete ; <nl> <nl> inline Variant & concat_assign ( Variant & v1 , CStrRef s2 ) { <nl> if ( v1 . getType ( ) = = KindOfString ) { <nl> - StringData * data = v1 . getStringData ( ) ; <nl> - if ( data - > getCount ( ) = = 1 ) { <nl> - data - > append ( s2 . data ( ) , s2 . size ( ) ) ; <nl> + auto & str = v1 . asStrRef ( ) ; <nl> + if ( str - > getCount ( ) = = 1 ) { <nl> + str + = StringSlice { s2 . data ( ) , static_cast < uint32_t > ( s2 . size ( ) ) } ; <nl> return v1 ; <nl> } <nl> } <nl> - String s1 = v1 . toString ( ) ; <nl> - s1 + = s2 ; <nl> <nl> + auto s1 = v1 . toString ( ) ; <nl> + s1 + = s2 ; <nl> v1 = s1 ; <nl> return v1 ; <nl> } <nl> mmm a / hphp / runtime / vm / runtime . cpp <nl> ppp b / hphp / runtime / vm / runtime . cpp <nl> concat_ss ( StringData * v1 , StringData * v2 ) { <nl> / / have to release the string here <nl> v1 - > decRefCount ( ) ; <nl> return ret ; <nl> - } else { <nl> - v1 - > append ( v2 - > slice ( ) ) ; <nl> - decRefStr ( v2 ) ; <nl> - return v1 ; <nl> } <nl> + <nl> + auto const newV1 = v1 - > append ( v2 - > slice ( ) ) ; <nl> + decRefStr ( v2 ) ; <nl> + if ( UNLIKELY ( newV1 ! = v1 ) ) { <nl> + assert ( v1 - > getCount ( ) = = 1 ) ; <nl> + v1 - > release ( ) ; <nl> + newV1 - > incRefCount ( ) ; <nl> + return newV1 ; <nl> + } <nl> + return v1 ; <nl> } <nl> <nl> / * * <nl>
Remove string modes except Flat and Shared
facebook/hhvm
e1322d52dd1a607c78afa87d9625091b780e0c14
2013-09-10T20:22:09Z
mmm a / Marlin / pins . h <nl> ppp b / Marlin / pins . h <nl> <nl> # define FAN_PIN 4 <nl> # endif <nl> <nl> + # ifdef NUM_SERVOS <nl> + # define SERVO0_PIN - 1 <nl> + <nl> + # if NUM_SERVOS > 1 <nl> + # define SERVO1_PIN - 1 <nl> + # endif <nl> + <nl> + # if NUM_SERVOS > 2 <nl> + # define SERVO2_PIN - 1 <nl> + # endif <nl> + <nl> + # if NUM_SERVOS > 3 <nl> + # define SERVO3_PIN - 1 <nl> + # endif <nl> + # endif <nl> + <nl> # define PS_ON_PIN - 1 <nl> # define KILL_PIN - 1 <nl> <nl>
Merge pull request from DerSchultze / Sanguinololu - servo
MarlinFirmware/Marlin
3ffc9651b1c428ec4e6e6799390660194bcbcdcf
2014-04-12T23:37:28Z
mmm a / xbmc / RenderSystemDX . h <nl> ppp b / xbmc / RenderSystemDX . h <nl> class CRenderSystemDX : public CRenderSystemBase <nl> DWORD m_defaultD3DUsage ; <nl> D3DPOOL m_defaultD3DPool ; <nl> bool m_useWindowedDX ; <nl> + <nl> CCriticalSection m_resourceSection ; <nl> std : : vector < ID3DResource * > m_resources ; <nl> <nl> mmm a / xbmc / WinSystemWin32 . cpp <nl> ppp b / xbmc / WinSystemWin32 . cpp <nl> bool CWinSystemWin32 : : InitWindowSystem ( ) <nl> <nl> bool CWinSystemWin32 : : DestroyWindowSystem ( ) <nl> { <nl> + RestoreDesktopResolution ( m_nScreen ) ; <nl> return true ; <nl> } <nl> <nl> bool CWinSystemWin32 : : SetFullScreen ( bool fullScreen , RESOLUTION_INFO & res , bool <nl> { <nl> CLog : : Log ( LOGDEBUG , " % s ( % s ) on screen % d with size % dx % d , refresh % f % s " , __FUNCTION__ , ! fullScreen ? " windowed " : ( g_guiSettings . GetBool ( " videoscreen . fakefullscreen " ) ? " windowed fullscreen " : " true fullscreen " ) , res . iScreen , res . iWidth , res . iHeight , res . fRefreshRate , ( res . dwFlags & D3DPRESENTFLAG_INTERLACED ) ? " i " : " " ) ; <nl> <nl> + bool forceResize = false ; <nl> + <nl> + if ( m_nScreen ! = res . iScreen ) <nl> + { <nl> + forceResize = true ; <nl> + RestoreDesktopResolution ( m_nScreen ) ; <nl> + } <nl> + <nl> if ( ! m_bFullScreen & & fullScreen ) <nl> { <nl> - / / save position of window mode <nl> + / / save position of windowed mode <nl> WINDOWINFO wi ; <nl> GetWindowInfo ( m_hWnd , & wi ) ; <nl> m_nLeft = wi . rcClient . left ; <nl> bool CWinSystemWin32 : : SetFullScreen ( bool fullScreen , RESOLUTION_INFO & res , bool <nl> } <nl> <nl> m_bFullScreen = fullScreen ; <nl> - bool forceResize = ( m_nScreen ! = res . iScreen ) ; <nl> m_nScreen = res . iScreen ; <nl> m_nWidth = res . iWidth ; <nl> m_nHeight = res . iHeight ; <nl> bool CWinSystemWin32 : : SetFullScreen ( bool fullScreen , RESOLUTION_INFO & res , bool <nl> return true ; <nl> } <nl> <nl> + void CWinSystemWin32 : : RestoreDesktopResolution ( int screen ) <nl> + { <nl> + int resIdx = RES_DESKTOP ; <nl> + for ( int idx = RES_DESKTOP ; idx < RES_DESKTOP + GetNumScreens ( ) ; idx + + ) <nl> + { <nl> + if ( g_settings . m_ResInfo [ idx ] . iScreen = = screen ) <nl> + { <nl> + resIdx = idx ; <nl> + break ; <nl> + } <nl> + } <nl> + ChangeResolution ( g_settings . m_ResInfo [ resIdx ] ) ; <nl> + } <nl> + <nl> const MONITOR_DETAILS & CWinSystemWin32 : : GetMonitor ( int screen ) const <nl> { <nl> for ( unsigned int monitor = 0 ; monitor < m_MonitorsInfo . size ( ) ; monitor + + ) <nl> mmm a / xbmc / WinSystemWin32 . h <nl> ppp b / xbmc / WinSystemWin32 . h <nl> class CWinSystemWin32 : public CWinSystemBase <nl> virtual bool CreateBlankWindows ( ) ; <nl> virtual bool BlankNonActiveMonitors ( bool bBlank ) ; <nl> const MONITOR_DETAILS & GetMonitor ( int screen ) const ; <nl> + void RestoreDesktopResolution ( int screen ) ; <nl> / * ! <nl> \ brief Adds a resolution to the list of resolutions if we don ' t already have it <nl> \ param res resolution to add . <nl>
[ WIN32 ] DX resolution switching - Trac Part 2 - restore resolution when quitting or changing screen
xbmc/xbmc
edce859275d30c79396435e6eb4de66238d01e7e
2010-06-21T07:33:18Z
mmm a / include / v8 . h <nl> ppp b / include / v8 . h <nl> template < class T > class EXPORT_INLINE Handle { <nl> / * * <nl> * Returns true if the handle is empty . <nl> * / <nl> - bool IsEmpty ( ) { return val_ = = 0 ; } <nl> + bool IsEmpty ( ) const { return val_ = = 0 ; } <nl> <nl> - T * operator - > ( ) ; <nl> + T * operator - > ( ) const ; <nl> <nl> - T * operator * ( ) ; <nl> + T * operator * ( ) const ; <nl> <nl> / * * <nl> * Sets the handle to be empty . IsEmpty ( ) will then return true . <nl> template < class T > class EXPORT_INLINE Handle { <nl> * to which they refer are identical . <nl> * The handles ' references are not checked . <nl> * / <nl> - template < class S > bool operator = = ( Handle < S > that ) { <nl> + template < class S > bool operator = = ( Handle < S > that ) const { <nl> void * * a = reinterpret_cast < void * * > ( * * this ) ; <nl> void * * b = reinterpret_cast < void * * > ( * that ) ; <nl> if ( a = = 0 ) return b = = 0 ; <nl> template < class T > class EXPORT_INLINE Handle { <nl> * the objects to which they refer are different . <nl> * The handles ' references are not checked . <nl> * / <nl> - template < class S > bool operator ! = ( Handle < S > that ) { <nl> + template < class S > bool operator ! = ( Handle < S > that ) const { <nl> return ! operator = = ( that ) ; <nl> } <nl> <nl> template < class T > class EXPORT_INLINE Persistent : public Handle < T > { <nl> / * * <nl> * Checks if the handle holds the only reference to an object . <nl> * / <nl> - bool IsNearDeath ( ) ; <nl> + bool IsNearDeath ( ) const ; <nl> <nl> / * * <nl> * Returns true if the handle ' s reference is weak . <nl> * / <nl> - bool IsWeak ( ) ; <nl> + bool IsWeak ( ) const ; <nl> <nl> private : <nl> friend class ImplementationUtilities ; <nl> class EXPORT Script { <nl> * / <nl> class EXPORT Message { <nl> public : <nl> - Local < String > Get ( ) ; <nl> - Local < String > GetSourceLine ( ) ; <nl> + Local < String > Get ( ) const ; <nl> + Local < String > GetSourceLine ( ) const ; <nl> <nl> - Handle < Value > GetScriptResourceName ( ) ; <nl> + Handle < Value > GetScriptResourceName ( ) const ; <nl> <nl> / * * <nl> * Returns the number , 1 - based , of the line where the error occurred . <nl> * / <nl> - int GetLineNumber ( ) ; <nl> + int GetLineNumber ( ) const ; <nl> <nl> / * * <nl> * Returns the index within the script of the first character where <nl> * the error occurred . <nl> * / <nl> - int GetStartPosition ( ) ; <nl> + int GetStartPosition ( ) const ; <nl> <nl> / * * <nl> * Returns the index within the script of the last character where <nl> * the error occurred . <nl> * / <nl> - int GetEndPosition ( ) ; <nl> + int GetEndPosition ( ) const ; <nl> <nl> / * * <nl> * Returns the index within the line of the first character where <nl> * the error occurred . <nl> * / <nl> - int GetStartColumn ( ) ; <nl> + int GetStartColumn ( ) const ; <nl> <nl> / * * <nl> * Returns the index within the line of the last character where <nl> * the error occurred . <nl> * / <nl> - int GetEndColumn ( ) ; <nl> + int GetEndColumn ( ) const ; <nl> <nl> / / TODO ( 1245381 ) : Print to a string instead of on a FILE . <nl> static void PrintCurrentStackTrace ( FILE * out ) ; <nl> class EXPORT Value : public Data { <nl> * Returns true if this value is the undefined value . See ECMA - 262 <nl> * 4 . 3 . 10 . <nl> * / <nl> - bool IsUndefined ( ) ; <nl> + bool IsUndefined ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is the null value . See ECMA - 262 <nl> * 4 . 3 . 11 . <nl> * / <nl> - bool IsNull ( ) ; <nl> + bool IsNull ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is true . <nl> * / <nl> - bool IsTrue ( ) ; <nl> + bool IsTrue ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is false . <nl> * / <nl> - bool IsFalse ( ) ; <nl> + bool IsFalse ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is an instance of the String type . <nl> * See ECMA - 262 8 . 4 . <nl> * / <nl> - bool IsString ( ) ; <nl> + bool IsString ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is a function . <nl> * / <nl> - bool IsFunction ( ) ; <nl> + bool IsFunction ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is an array . <nl> * / <nl> - bool IsArray ( ) ; <nl> + bool IsArray ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is an object . <nl> * / <nl> - bool IsObject ( ) ; <nl> + bool IsObject ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is boolean . <nl> * / <nl> - bool IsBoolean ( ) ; <nl> + bool IsBoolean ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is a number . <nl> * / <nl> - bool IsNumber ( ) ; <nl> + bool IsNumber ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is external . <nl> * / <nl> - bool IsExternal ( ) ; <nl> + bool IsExternal ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is a 32 - bit signed integer . <nl> * / <nl> - bool IsInt32 ( ) ; <nl> + bool IsInt32 ( ) const ; <nl> <nl> / * * <nl> * Returns true if this value is a Date . <nl> * / <nl> - bool IsDate ( ) ; <nl> + bool IsDate ( ) const ; <nl> <nl> - Local < Boolean > ToBoolean ( ) ; <nl> - Local < Number > ToNumber ( ) ; <nl> - Local < String > ToString ( ) ; <nl> - Local < String > ToDetailString ( ) ; <nl> - Local < Object > ToObject ( ) ; <nl> - Local < Integer > ToInteger ( ) ; <nl> - Local < Uint32 > ToUint32 ( ) ; <nl> - Local < Int32 > ToInt32 ( ) ; <nl> + Local < Boolean > ToBoolean ( ) const ; <nl> + Local < Number > ToNumber ( ) const ; <nl> + Local < String > ToString ( ) const ; <nl> + Local < String > ToDetailString ( ) const ; <nl> + Local < Object > ToObject ( ) const ; <nl> + Local < Integer > ToInteger ( ) const ; <nl> + Local < Uint32 > ToUint32 ( ) const ; <nl> + Local < Int32 > ToInt32 ( ) const ; <nl> <nl> / * * <nl> * Attempts to convert a string to an array index . <nl> * Returns an empty handle if the conversion fails . <nl> * / <nl> - Local < Uint32 > ToArrayIndex ( ) ; <nl> + Local < Uint32 > ToArrayIndex ( ) const ; <nl> <nl> - bool BooleanValue ( ) ; <nl> - double NumberValue ( ) ; <nl> - int64_t IntegerValue ( ) ; <nl> - uint32_t Uint32Value ( ) ; <nl> - int32_t Int32Value ( ) ; <nl> + bool BooleanValue ( ) const ; <nl> + double NumberValue ( ) const ; <nl> + int64_t IntegerValue ( ) const ; <nl> + uint32_t Uint32Value ( ) const ; <nl> + int32_t Int32Value ( ) const ; <nl> <nl> / * * JS = = * / <nl> - bool Equals ( Handle < Value > that ) ; <nl> - bool StrictEquals ( Handle < Value > that ) ; <nl> + bool Equals ( Handle < Value > that ) const ; <nl> + bool StrictEquals ( Handle < Value > that ) const ; <nl> } ; <nl> <nl> <nl> class EXPORT Primitive : public Value { } ; <nl> * / <nl> class EXPORT Boolean : public Primitive { <nl> public : <nl> - bool Value ( ) ; <nl> + bool Value ( ) const ; <nl> static inline Handle < Boolean > New ( bool value ) ; <nl> } ; <nl> <nl> class EXPORT String : public Primitive { <nl> / * * <nl> * Returns the number of characters in this string . <nl> * / <nl> - int Length ( ) ; <nl> + int Length ( ) const ; <nl> <nl> / * * <nl> * Returns the number of bytes in the UTF - 8 encoded <nl> * representation of this string . <nl> * / <nl> - int Utf8Length ( ) ; <nl> + int Utf8Length ( ) const ; <nl> <nl> / * * <nl> * Write the contents of the string to an external buffer . <nl> class EXPORT String : public Primitive { <nl> * \ return The number of characters copied to the buffer <nl> * excluding the NULL terminator . <nl> * / <nl> - int Write ( uint16_t * buffer , int start = 0 , int length = - 1 ) ; / / UTF - 16 <nl> - int WriteAscii ( char * buffer , int start = 0 , int length = - 1 ) ; / / ASCII <nl> - int WriteUtf8 ( char * buffer , int length = - 1 ) ; / / UTF - 8 <nl> + int Write ( uint16_t * buffer , int start = 0 , int length = - 1 ) const ; / / UTF - 16 <nl> + int WriteAscii ( char * buffer , int start = 0 , int length = - 1 ) const ; / / ASCII <nl> + int WriteUtf8 ( char * buffer , int length = - 1 ) const ; / / UTF - 8 <nl> <nl> / * * <nl> * Returns true if the string is external <nl> * / <nl> - bool IsExternal ( ) ; <nl> + bool IsExternal ( ) const ; <nl> <nl> / * * <nl> * Returns true if the string is both external and ascii <nl> * / <nl> - bool IsExternalAscii ( ) ; <nl> + bool IsExternalAscii ( ) const ; <nl> / * * <nl> * An ExternalStringResource is a wrapper around a two - byte string <nl> * buffer that resides outside V8 ' s heap . Implement an <nl> class EXPORT String : public Primitive { <nl> * Get the ExternalStringResource for an external string . Only <nl> * valid if IsExternal ( ) returns true . <nl> * / <nl> - ExternalStringResource * GetExternalStringResource ( ) ; <nl> + ExternalStringResource * GetExternalStringResource ( ) const ; <nl> <nl> / * * <nl> * Get the ExternalAsciiStringResource for an external ascii string . <nl> * Only valid if IsExternalAscii ( ) returns true . <nl> * / <nl> - ExternalAsciiStringResource * GetExternalAsciiStringResource ( ) ; <nl> + ExternalAsciiStringResource * GetExternalAsciiStringResource ( ) const ; <nl> <nl> static String * Cast ( v8 : : Value * obj ) ; <nl> <nl> class EXPORT String : public Primitive { <nl> * / <nl> class EXPORT Number : public Primitive { <nl> public : <nl> - double Value ( ) ; <nl> + double Value ( ) const ; <nl> static Local < Number > New ( double value ) ; <nl> static Number * Cast ( v8 : : Value * obj ) ; <nl> private : <nl> class EXPORT Number : public Primitive { <nl> class EXPORT Integer : public Number { <nl> public : <nl> static Local < Integer > New ( int32_t value ) ; <nl> - int64_t Value ( ) ; <nl> + int64_t Value ( ) const ; <nl> static Integer * Cast ( v8 : : Value * obj ) ; <nl> private : <nl> Integer ( ) ; <nl> class EXPORT Integer : public Number { <nl> * / <nl> class EXPORT Int32 : public Integer { <nl> public : <nl> - int32_t Value ( ) ; <nl> + int32_t Value ( ) const ; <nl> private : <nl> Int32 ( ) ; <nl> } ; <nl> class EXPORT Int32 : public Integer { <nl> * / <nl> class EXPORT Uint32 : public Integer { <nl> public : <nl> - uint32_t Value ( ) ; <nl> + uint32_t Value ( ) const ; <nl> private : <nl> Uint32 ( ) ; <nl> } ; <nl> class EXPORT Date : public Value { <nl> * A specialization of Value : : NumberValue that is more efficient <nl> * because we know the structure of this object . <nl> * / <nl> - double NumberValue ( ) ; <nl> + double NumberValue ( ) const ; <nl> <nl> static Date * Cast ( v8 : : Value * obj ) ; <nl> } ; <nl> class EXPORT Object : public Value { <nl> * / <nl> class EXPORT Array : public Object { <nl> public : <nl> - uint32_t Length ( ) ; <nl> + uint32_t Length ( ) const ; <nl> <nl> static Local < Array > New ( int length = 0 ) ; <nl> static Array * Cast ( Value * obj ) ; <nl> class EXPORT Array : public Object { <nl> * / <nl> class EXPORT Function : public Object { <nl> public : <nl> - Local < Object > NewInstance ( ) ; <nl> - Local < Object > NewInstance ( int argc , Handle < Value > argv [ ] ) ; <nl> + Local < Object > NewInstance ( ) const ; <nl> + Local < Object > NewInstance ( int argc , Handle < Value > argv [ ] ) const ; <nl> Local < Value > Call ( Handle < Object > recv , int argc , Handle < Value > argv [ ] ) ; <nl> void SetName ( Handle < String > name ) ; <nl> - Handle < Value > GetName ( ) ; <nl> + Handle < Value > GetName ( ) const ; <nl> static Function * Cast ( Value * obj ) ; <nl> private : <nl> Function ( ) ; <nl> class EXPORT External : public Value { <nl> public : <nl> static Local < External > New ( void * value ) ; <nl> static External * Cast ( Value * obj ) ; <nl> - void * Value ( ) ; <nl> + void * Value ( ) const ; <nl> private : <nl> External ( ) ; <nl> } ; <nl> Persistent < T > Persistent < T > : : New ( Handle < T > that ) { <nl> <nl> <nl> template < class T > <nl> - bool Persistent < T > : : IsNearDeath ( ) { <nl> + bool Persistent < T > : : IsNearDeath ( ) const { <nl> if ( this - > IsEmpty ( ) ) return false ; <nl> return V8 : : IsGlobalNearDeath ( reinterpret_cast < void * * > ( * * this ) ) ; <nl> } <nl> <nl> <nl> template < class T > <nl> - bool Persistent < T > : : IsWeak ( ) { <nl> + bool Persistent < T > : : IsWeak ( ) const { <nl> if ( this - > IsEmpty ( ) ) return false ; <nl> return V8 : : IsGlobalWeak ( reinterpret_cast < void * * > ( * * this ) ) ; <nl> } <nl> void Persistent < T > : : ClearWeak ( ) { <nl> } <nl> <nl> template < class T > <nl> - T * Handle < T > : : operator - > ( ) { <nl> + T * Handle < T > : : operator - > ( ) const { <nl> return val_ ; <nl> } <nl> <nl> <nl> template < class T > <nl> - T * Handle < T > : : operator * ( ) { <nl> + T * Handle < T > : : operator * ( ) const { <nl> return val_ ; <nl> } <nl> <nl> mmm a / src / api . cc <nl> ppp b / src / api . cc <nl> static inline bool EmptyCheck ( const char * location , v8 : : Handle < v8 : : Data > obj ) { <nl> } <nl> <nl> <nl> - static inline bool EmptyCheck ( const char * location , v8 : : Data * obj ) { <nl> + static inline bool EmptyCheck ( const char * location , const v8 : : Data * obj ) { <nl> return ( obj = = 0 ) ? ReportEmptyHandle ( location ) : false ; <nl> } <nl> <nl> void v8 : : TryCatch : : SetCaptureMessage ( bool value ) { <nl> / / mmm M e s s a g e mmm <nl> <nl> <nl> - Local < String > Message : : Get ( ) { <nl> + Local < String > Message : : Get ( ) const { <nl> ON_BAILOUT ( " v8 : : Message : : Get ( ) " , return Local < String > ( ) ) ; <nl> HandleScope scope ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < String > Message : : Get ( ) { <nl> } <nl> <nl> <nl> - v8 : : Handle < Value > Message : : GetScriptResourceName ( ) { <nl> + v8 : : Handle < Value > Message : : GetScriptResourceName ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Message : : GetScriptResourceName ( ) " ) ) { <nl> return Local < String > ( ) ; <nl> } <nl> static i : : Handle < i : : Object > CallV8HeapFunction ( const char * name , <nl> } <nl> <nl> <nl> - int Message : : GetLineNumber ( ) { <nl> + int Message : : GetLineNumber ( ) const { <nl> ON_BAILOUT ( " v8 : : Message : : GetLineNumber ( ) " , return - 1 ) ; <nl> HandleScope scope ; <nl> EXCEPTION_PREAMBLE ( ) ; <nl> int Message : : GetLineNumber ( ) { <nl> } <nl> <nl> <nl> - int Message : : GetStartPosition ( ) { <nl> + int Message : : GetStartPosition ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Message : : GetStartPosition ( ) " ) ) return 0 ; <nl> HandleScope scope ; <nl> <nl> int Message : : GetStartPosition ( ) { <nl> } <nl> <nl> <nl> - int Message : : GetEndPosition ( ) { <nl> + int Message : : GetEndPosition ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Message : : GetEndPosition ( ) " ) ) return 0 ; <nl> HandleScope scope ; <nl> i : : Handle < i : : JSObject > data_obj = Utils : : OpenHandle ( this ) ; <nl> int Message : : GetEndPosition ( ) { <nl> } <nl> <nl> <nl> - int Message : : GetStartColumn ( ) { <nl> + int Message : : GetStartColumn ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Message : : GetStartColumn ( ) " ) ) return 0 ; <nl> HandleScope scope ; <nl> i : : Handle < i : : JSObject > data_obj = Utils : : OpenHandle ( this ) ; <nl> int Message : : GetStartColumn ( ) { <nl> } <nl> <nl> <nl> - int Message : : GetEndColumn ( ) { <nl> + int Message : : GetEndColumn ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Message : : GetEndColumn ( ) " ) ) return 0 ; <nl> HandleScope scope ; <nl> i : : Handle < i : : JSObject > data_obj = Utils : : OpenHandle ( this ) ; <nl> int Message : : GetEndColumn ( ) { <nl> } <nl> <nl> <nl> - Local < String > Message : : GetSourceLine ( ) { <nl> + Local < String > Message : : GetSourceLine ( ) const { <nl> ON_BAILOUT ( " v8 : : Message : : GetSourceLine ( ) " , return Local < String > ( ) ) ; <nl> HandleScope scope ; <nl> EXCEPTION_PREAMBLE ( ) ; <nl> void Message : : PrintCurrentStackTrace ( FILE * out ) { <nl> <nl> / / mmm D a t a mmm <nl> <nl> - bool Value : : IsUndefined ( ) { <nl> + bool Value : : IsUndefined ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsUndefined ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsUndefined ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsNull ( ) { <nl> + bool Value : : IsNull ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsNull ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsNull ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsTrue ( ) { <nl> + bool Value : : IsTrue ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsTrue ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsTrue ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsFalse ( ) { <nl> + bool Value : : IsFalse ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsFalse ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsFalse ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsFunction ( ) { <nl> + bool Value : : IsFunction ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsFunction ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsJSFunction ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsString ( ) { <nl> + bool Value : : IsString ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsString ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsString ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsArray ( ) { <nl> + bool Value : : IsArray ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsArray ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsJSArray ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsObject ( ) { <nl> + bool Value : : IsObject ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsObject ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsJSObject ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsNumber ( ) { <nl> + bool Value : : IsNumber ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsNumber ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsNumber ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsBoolean ( ) { <nl> + bool Value : : IsBoolean ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsBoolean ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsBoolean ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsExternal ( ) { <nl> + bool Value : : IsExternal ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsExternal ( ) " ) ) return false ; <nl> return Utils : : OpenHandle ( this ) - > IsProxy ( ) ; <nl> } <nl> <nl> <nl> - bool Value : : IsInt32 ( ) { <nl> + bool Value : : IsInt32 ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsInt32 ( ) " ) ) return false ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> if ( obj - > IsSmi ( ) ) return true ; <nl> bool Value : : IsInt32 ( ) { <nl> } <nl> <nl> <nl> - bool Value : : IsDate ( ) { <nl> + bool Value : : IsDate ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IsDate ( ) " ) ) return false ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> return obj - > HasSpecificClassOf ( i : : Heap : : Date_symbol ( ) ) ; <nl> } <nl> <nl> <nl> - Local < String > Value : : ToString ( ) { <nl> + Local < String > Value : : ToString ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToString ( ) " ) ) return Local < String > ( ) ; <nl> LOG_API ( " ToString " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < String > Value : : ToString ( ) { <nl> } <nl> <nl> <nl> - Local < String > Value : : ToDetailString ( ) { <nl> + Local < String > Value : : ToDetailString ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToDetailString ( ) " ) ) return Local < String > ( ) ; <nl> LOG_API ( " ToDetailString " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < String > Value : : ToDetailString ( ) { <nl> } <nl> <nl> <nl> - Local < v8 : : Object > Value : : ToObject ( ) { <nl> + Local < v8 : : Object > Value : : ToObject ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToObject ( ) " ) ) return Local < v8 : : Object > ( ) ; <nl> LOG_API ( " ToObject " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < v8 : : Object > Value : : ToObject ( ) { <nl> } <nl> <nl> <nl> - Local < Boolean > Value : : ToBoolean ( ) { <nl> + Local < Boolean > Value : : ToBoolean ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToBoolean ( ) " ) ) return Local < Boolean > ( ) ; <nl> LOG_API ( " ToBoolean " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < Boolean > Value : : ToBoolean ( ) { <nl> } <nl> <nl> <nl> - Local < Number > Value : : ToNumber ( ) { <nl> + Local < Number > Value : : ToNumber ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToNumber ( ) " ) ) return Local < Number > ( ) ; <nl> LOG_API ( " ToNumber " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < Number > Value : : ToNumber ( ) { <nl> } <nl> <nl> <nl> - Local < Integer > Value : : ToInteger ( ) { <nl> + Local < Integer > Value : : ToInteger ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToInteger ( ) " ) ) return Local < Integer > ( ) ; <nl> LOG_API ( " ToInteger " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> v8 : : Date * v8 : : Date : : Cast ( v8 : : Value * that ) { <nl> } <nl> <nl> <nl> - bool Value : : BooleanValue ( ) { <nl> + bool Value : : BooleanValue ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : BooleanValue ( ) " ) ) return false ; <nl> LOG_API ( " BooleanValue " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> bool Value : : BooleanValue ( ) { <nl> } <nl> <nl> <nl> - double Value : : NumberValue ( ) { <nl> + double Value : : NumberValue ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : NumberValue ( ) " ) ) return i : : OS : : nan_value ( ) ; <nl> LOG_API ( " NumberValue " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> double Value : : NumberValue ( ) { <nl> } <nl> <nl> <nl> - int64_t Value : : IntegerValue ( ) { <nl> + int64_t Value : : IntegerValue ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : IntegerValue ( ) " ) ) return 0 ; <nl> LOG_API ( " IntegerValue " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> int64_t Value : : IntegerValue ( ) { <nl> } <nl> <nl> <nl> - Local < Int32 > Value : : ToInt32 ( ) { <nl> + Local < Int32 > Value : : ToInt32 ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToInt32 ( ) " ) ) return Local < Int32 > ( ) ; <nl> LOG_API ( " ToInt32 " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < Int32 > Value : : ToInt32 ( ) { <nl> } <nl> <nl> <nl> - Local < Uint32 > Value : : ToUint32 ( ) { <nl> + Local < Uint32 > Value : : ToUint32 ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToUint32 ( ) " ) ) return Local < Uint32 > ( ) ; <nl> LOG_API ( " ToUInt32 " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < Uint32 > Value : : ToUint32 ( ) { <nl> } <nl> <nl> <nl> - Local < Uint32 > Value : : ToArrayIndex ( ) { <nl> + Local < Uint32 > Value : : ToArrayIndex ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : ToArrayIndex ( ) " ) ) return Local < Uint32 > ( ) ; <nl> LOG_API ( " ToArrayIndex " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < Uint32 > Value : : ToArrayIndex ( ) { <nl> } <nl> <nl> <nl> - int32_t Value : : Int32Value ( ) { <nl> + int32_t Value : : Int32Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : Int32Value ( ) " ) ) return 0 ; <nl> LOG_API ( " Int32Value " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> int32_t Value : : Int32Value ( ) { <nl> } <nl> <nl> <nl> - bool Value : : Equals ( Handle < Value > that ) { <nl> + bool Value : : Equals ( Handle < Value > that ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : Equals ( ) " ) <nl> | | EmptyCheck ( " v8 : : Value : : Equals ( ) " , this ) <nl> | | EmptyCheck ( " v8 : : Value : : Equals ( ) " , that ) ) <nl> bool Value : : Equals ( Handle < Value > that ) { <nl> } <nl> <nl> <nl> - bool Value : : StrictEquals ( Handle < Value > that ) { <nl> + bool Value : : StrictEquals ( Handle < Value > that ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : StrictEquals ( ) " ) <nl> | | EmptyCheck ( " v8 : : Value : : StrictEquals ( ) " , this ) <nl> | | EmptyCheck ( " v8 : : Value : : StrictEquals ( ) " , that ) ) <nl> bool Value : : StrictEquals ( Handle < Value > that ) { <nl> } <nl> <nl> <nl> - uint32_t Value : : Uint32Value ( ) { <nl> + uint32_t Value : : Uint32Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Value : : Uint32Value ( ) " ) ) return 0 ; <nl> LOG_API ( " Uint32Value " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> void v8 : : Object : : TurnOnAccessCheck ( ) { <nl> } <nl> <nl> <nl> - Local < v8 : : Object > Function : : NewInstance ( ) { <nl> + Local < v8 : : Object > Function : : NewInstance ( ) const { <nl> return NewInstance ( 0 , NULL ) ; <nl> } <nl> <nl> <nl> Local < v8 : : Object > Function : : NewInstance ( int argc , <nl> - v8 : : Handle < v8 : : Value > argv [ ] ) { <nl> + v8 : : Handle < v8 : : Value > argv [ ] ) const { <nl> ON_BAILOUT ( " v8 : : Function : : NewInstance ( ) " , return Local < v8 : : Object > ( ) ) ; <nl> LOG_API ( " Function : : NewInstance " ) ; <nl> HandleScope scope ; <nl> void Function : : SetName ( v8 : : Handle < v8 : : String > name ) { <nl> } <nl> <nl> <nl> - Handle < Value > Function : : GetName ( ) { <nl> + Handle < Value > Function : : GetName ( ) const { <nl> i : : Handle < i : : JSFunction > func = Utils : : OpenHandle ( this ) ; <nl> return Utils : : ToLocal ( i : : Handle < i : : Object > ( func - > shared ( ) - > name ( ) ) ) ; <nl> } <nl> <nl> <nl> - int String : : Length ( ) { <nl> + int String : : Length ( ) const { <nl> if ( IsDeadCheck ( " v8 : : String : : Length ( ) " ) ) return 0 ; <nl> return Utils : : OpenHandle ( this ) - > length ( ) ; <nl> } <nl> <nl> <nl> - int String : : Utf8Length ( ) { <nl> + int String : : Utf8Length ( ) const { <nl> if ( IsDeadCheck ( " v8 : : String : : Utf8Length ( ) " ) ) return 0 ; <nl> return Utils : : OpenHandle ( this ) - > Utf8Length ( ) ; <nl> } <nl> <nl> <nl> - int String : : WriteUtf8 ( char * buffer , int capacity ) { <nl> + int String : : WriteUtf8 ( char * buffer , int capacity ) const { <nl> if ( IsDeadCheck ( " v8 : : String : : WriteUtf8 ( ) " ) ) return 0 ; <nl> LOG_API ( " String : : WriteUtf8 " ) ; <nl> i : : Handle < i : : String > str = Utils : : OpenHandle ( this ) ; <nl> int String : : WriteUtf8 ( char * buffer , int capacity ) { <nl> } <nl> <nl> <nl> - int String : : WriteAscii ( char * buffer , int start , int length ) { <nl> + int String : : WriteAscii ( char * buffer , int start , int length ) const { <nl> if ( IsDeadCheck ( " v8 : : String : : WriteAscii ( ) " ) ) return 0 ; <nl> LOG_API ( " String : : WriteAscii " ) ; <nl> ASSERT ( start > = 0 & & length > = - 1 ) ; <nl> int String : : WriteAscii ( char * buffer , int start , int length ) { <nl> } <nl> <nl> <nl> - int String : : Write ( uint16_t * buffer , int start , int length ) { <nl> + int String : : Write ( uint16_t * buffer , int start , int length ) const { <nl> if ( IsDeadCheck ( " v8 : : String : : Write ( ) " ) ) return 0 ; <nl> LOG_API ( " String : : Write " ) ; <nl> ASSERT ( start > = 0 & & length > = - 1 ) ; <nl> int String : : Write ( uint16_t * buffer , int start , int length ) { <nl> } <nl> <nl> <nl> - bool v8 : : String : : IsExternal ( ) { <nl> + bool v8 : : String : : IsExternal ( ) const { <nl> EnsureInitialized ( " v8 : : String : : IsExternal ( ) " ) ; <nl> i : : Handle < i : : String > str = Utils : : OpenHandle ( this ) ; <nl> i : : StringShape shape ( * str ) ; <nl> bool v8 : : String : : IsExternal ( ) { <nl> } <nl> <nl> <nl> - bool v8 : : String : : IsExternalAscii ( ) { <nl> + bool v8 : : String : : IsExternalAscii ( ) const { <nl> EnsureInitialized ( " v8 : : String : : IsExternalAscii ( ) " ) ; <nl> i : : Handle < i : : String > str = Utils : : OpenHandle ( this ) ; <nl> i : : StringShape shape ( * str ) ; <nl> bool v8 : : String : : IsExternalAscii ( ) { <nl> } <nl> <nl> <nl> - v8 : : String : : ExternalStringResource * v8 : : String : : GetExternalStringResource ( ) { <nl> + v8 : : String : : ExternalStringResource * <nl> + v8 : : String : : GetExternalStringResource ( ) const { <nl> EnsureInitialized ( " v8 : : String : : GetExternalStringResource ( ) " ) ; <nl> i : : Handle < i : : String > str = Utils : : OpenHandle ( this ) ; <nl> ASSERT ( str - > IsExternalTwoByteString ( ) ) ; <nl> v8 : : String : : ExternalStringResource * v8 : : String : : GetExternalStringResource ( ) { <nl> <nl> <nl> v8 : : String : : ExternalAsciiStringResource * <nl> - v8 : : String : : GetExternalAsciiStringResource ( ) { <nl> + v8 : : String : : GetExternalAsciiStringResource ( ) const { <nl> EnsureInitialized ( " v8 : : String : : GetExternalAsciiStringResource ( ) " ) ; <nl> i : : Handle < i : : String > str = Utils : : OpenHandle ( this ) ; <nl> ASSERT ( str - > IsExternalAsciiString ( ) ) ; <nl> v8 : : String : : ExternalAsciiStringResource * <nl> } <nl> <nl> <nl> - double Number : : Value ( ) { <nl> + double Number : : Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Number : : Value ( ) " ) ) return 0 ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> return obj - > Number ( ) ; <nl> } <nl> <nl> <nl> - bool Boolean : : Value ( ) { <nl> + bool Boolean : : Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Boolean : : Value ( ) " ) ) return false ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> return obj - > IsTrue ( ) ; <nl> } <nl> <nl> <nl> - int64_t Integer : : Value ( ) { <nl> + int64_t Integer : : Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Integer : : Value ( ) " ) ) return 0 ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> if ( obj - > IsSmi ( ) ) { <nl> int64_t Integer : : Value ( ) { <nl> } <nl> <nl> <nl> - int32_t Int32 : : Value ( ) { <nl> + int32_t Int32 : : Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Int32 : : Value ( ) " ) ) return 0 ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> if ( obj - > IsSmi ( ) ) { <nl> int32_t Int32 : : Value ( ) { <nl> } <nl> <nl> <nl> - void * External : : Value ( ) { <nl> + void * External : : Value ( ) const { <nl> if ( IsDeadCheck ( " v8 : : External : : Value ( ) " ) ) return 0 ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> return reinterpret_cast < void * > ( i : : Proxy : : cast ( * obj ) - > proxy ( ) ) ; <nl> Local < v8 : : Value > v8 : : Date : : New ( double time ) { <nl> } <nl> <nl> <nl> - double v8 : : Date : : NumberValue ( ) { <nl> + double v8 : : Date : : NumberValue ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Date : : NumberValue ( ) " ) ) return 0 ; <nl> LOG_API ( " Date : : NumberValue " ) ; <nl> i : : Handle < i : : Object > obj = Utils : : OpenHandle ( this ) ; <nl> Local < v8 : : Array > v8 : : Array : : New ( int length ) { <nl> } <nl> <nl> <nl> - uint32_t v8 : : Array : : Length ( ) { <nl> + uint32_t v8 : : Array : : Length ( ) const { <nl> if ( IsDeadCheck ( " v8 : : Array : : Length ( ) " ) ) return 0 ; <nl> i : : Handle < i : : JSArray > obj = Utils : : OpenHandle ( this ) ; <nl> i : : Object * length = obj - > length ( ) ; <nl> mmm a / src / api . h <nl> ppp b / src / api . h <nl> class Utils { <nl> v8 : : internal : : Handle < v8 : : internal : : TypeSwitchInfo > obj ) ; <nl> <nl> static inline v8 : : internal : : Handle < v8 : : internal : : TemplateInfo > <nl> - OpenHandle ( Template * that ) ; <nl> + OpenHandle ( const Template * that ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : FunctionTemplateInfo > <nl> - OpenHandle ( FunctionTemplate * that ) ; <nl> + OpenHandle ( const FunctionTemplate * that ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : ObjectTemplateInfo > <nl> - OpenHandle ( ObjectTemplate * that ) ; <nl> + OpenHandle ( const ObjectTemplate * that ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : Object > <nl> - OpenHandle ( Data * data ) ; <nl> + OpenHandle ( const Data * data ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : JSObject > <nl> - OpenHandle ( v8 : : Object * data ) ; <nl> + OpenHandle ( const v8 : : Object * data ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : JSArray > <nl> - OpenHandle ( v8 : : Array * data ) ; <nl> + OpenHandle ( const v8 : : Array * data ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : String > <nl> - OpenHandle ( String * data ) ; <nl> + OpenHandle ( const String * data ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : JSFunction > <nl> - OpenHandle ( Script * data ) ; <nl> + OpenHandle ( const Script * data ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : JSFunction > <nl> - OpenHandle ( Function * data ) ; <nl> + OpenHandle ( const Function * data ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : JSObject > <nl> - OpenHandle ( Message * message ) ; <nl> + OpenHandle ( const Message * message ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : Context > <nl> - OpenHandle ( v8 : : Context * context ) ; <nl> + OpenHandle ( const v8 : : Context * context ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : SignatureInfo > <nl> - OpenHandle ( v8 : : Signature * sig ) ; <nl> + OpenHandle ( const v8 : : Signature * sig ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : TypeSwitchInfo > <nl> - OpenHandle ( v8 : : TypeSwitch * that ) ; <nl> + OpenHandle ( const v8 : : TypeSwitch * that ) ; <nl> static inline v8 : : internal : : Handle < v8 : : internal : : Proxy > <nl> - OpenHandle ( v8 : : External * that ) ; <nl> + OpenHandle ( const v8 : : External * that ) ; <nl> } ; <nl> <nl> <nl> MAKE_TO_LOCAL ( Uint32ToLocal , Object , Uint32 ) <nl> / / Implementations of OpenHandle <nl> <nl> # define MAKE_OPEN_HANDLE ( From , To ) \ <nl> - v8 : : internal : : Handle < v8 : : internal : : To > Utils : : OpenHandle ( v8 : : From * that ) { \ <nl> + v8 : : internal : : Handle < v8 : : internal : : To > Utils : : OpenHandle ( const v8 : : From * that ) { \ <nl> return v8 : : internal : : Handle < v8 : : internal : : To > ( \ <nl> - reinterpret_cast < v8 : : internal : : To * * > ( that ) ) ; \ <nl> + reinterpret_cast < v8 : : internal : : To * * > ( const_cast < v8 : : From * > ( that ) ) ) ; \ <nl> } <nl> <nl> MAKE_OPEN_HANDLE ( Template , TemplateInfo ) <nl>
Added more constness to the api . There are still some methods back
v8/v8
569fb985ce05c0e011d78da2eb8a3cc596cf1afa
2009-01-08T11:35:34Z
mmm a / src / common / hex_util . cpp <nl> ppp b / src / common / hex_util . cpp <nl> std : : vector < u8 > HexStringToVector ( std : : string_view str , bool little_endian ) { <nl> return out ; <nl> } <nl> <nl> - std : : string HexVectorToString ( const std : : vector < u8 > & vector , bool upper ) { <nl> - std : : string out ; <nl> - for ( u8 c : vector ) <nl> - out + = fmt : : format ( upper ? " { : 02X } " : " { : 02x } " , c ) ; <nl> - return out ; <nl> - } <nl> - <nl> std : : array < u8 , 16 > operator " " _array16 ( const char * str , std : : size_t len ) { <nl> if ( len ! = 32 ) { <nl> LOG_ERROR ( Common , <nl> mmm a / src / common / hex_util . h <nl> ppp b / src / common / hex_util . h <nl> <nl> # include < array > <nl> # include < cstddef > <nl> # include < string > <nl> + # include < type_traits > <nl> # include < vector > <nl> # include < fmt / format . h > <nl> # include " common / common_types . h " <nl> std : : array < u8 , Size > HexStringToArray ( std : : string_view str ) { <nl> return out ; <nl> } <nl> <nl> - std : : string HexVectorToString ( const std : : vector < u8 > & vector , bool upper = true ) ; <nl> + template < typename ContiguousContainer > <nl> + std : : string HexToString ( const ContiguousContainer & data , bool upper = true ) { <nl> + static_assert ( std : : is_same_v < typename ContiguousContainer : : value_type , u8 > , <nl> + " Underlying type within the contiguous container must be u8 . " ) ; <nl> <nl> - template < std : : size_t Size > <nl> - std : : string HexArrayToString ( std : : array < u8 , Size > array , bool upper = true ) { <nl> std : : string out ; <nl> - for ( u8 c : array ) <nl> + for ( const u8 c : data ) { <nl> out + = fmt : : format ( upper ? " { : 02X } " : " { : 02x } " , c ) ; <nl> + } <nl> return out ; <nl> } <nl> <nl> mmm a / src / core / crypto / key_manager . cpp <nl> ppp b / src / core / crypto / key_manager . cpp <nl> void KeyManager : : WriteKeyToFile ( KeyCategory category , std : : string_view keyname , <nl> < < " # If you are experiencing issues involving keys , it may help to delete this file \ n " ; <nl> } <nl> <nl> - file < < fmt : : format ( " \ n { } = { } " , keyname , Common : : HexArrayToString ( key ) ) ; <nl> + file < < fmt : : format ( " \ n { } = { } " , keyname , Common : : HexToString ( key ) ) ; <nl> AttemptLoadKeyFile ( yuzu_keys_dir , yuzu_keys_dir , filename , category = = KeyCategory : : Title ) ; <nl> } <nl> <nl> void KeyManager : : SetKey ( S128KeyType id , Key128 key , u64 field1 , u64 field2 ) { <nl> Key128 rights_id ; <nl> std : : memcpy ( rights_id . data ( ) , & field2 , sizeof ( u64 ) ) ; <nl> std : : memcpy ( rights_id . data ( ) + sizeof ( u64 ) , & field1 , sizeof ( u64 ) ) ; <nl> - WriteKeyToFile ( KeyCategory : : Title , Common : : HexArrayToString ( rights_id ) , key ) ; <nl> + WriteKeyToFile ( KeyCategory : : Title , Common : : HexToString ( rights_id ) , key ) ; <nl> } <nl> <nl> auto category = KeyCategory : : Standard ; <nl> mmm a / src / core / file_sys / ips_layer . cpp <nl> ppp b / src / core / file_sys / ips_layer . cpp <nl> void IPSwitchCompiler : : Parse ( ) { <nl> LOG_INFO ( Loader , <nl> " [ IPSwitchCompiler ( ' { } ' ) ] - Patching value at offset 0x { : 08X } " <nl> " with byte string ' { } ' " , <nl> - patch_text - > GetName ( ) , offset , Common : : HexVectorToString ( replace ) ) ; <nl> + patch_text - > GetName ( ) , offset , Common : : HexToString ( replace ) ) ; <nl> } <nl> <nl> patch . records . insert_or_assign ( offset , std : : move ( replace ) ) ; <nl> mmm a / src / core / file_sys / patch_manager . cpp <nl> ppp b / src / core / file_sys / patch_manager . cpp <nl> std : : vector < VirtualFile > PatchManager : : CollectPatches ( const std : : vector < VirtualD <nl> if ( ! compiler . IsValid ( ) ) <nl> continue ; <nl> <nl> - auto this_build_id = Common : : HexArrayToString ( compiler . GetBuildID ( ) ) ; <nl> + auto this_build_id = Common : : HexToString ( compiler . GetBuildID ( ) ) ; <nl> this_build_id = <nl> this_build_id . substr ( 0 , this_build_id . find_last_not_of ( ' 0 ' ) + 1 ) ; <nl> <nl> std : : vector < u8 > PatchManager : : PatchNSO ( const std : : vector < u8 > & nso , const std : : st <nl> return nso ; <nl> } <nl> <nl> - const auto build_id_raw = Common : : HexArrayToString ( header . build_id ) ; <nl> + const auto build_id_raw = Common : : HexToString ( header . build_id ) ; <nl> const auto build_id = build_id_raw . substr ( 0 , build_id_raw . find_last_not_of ( ' 0 ' ) + 1 ) ; <nl> <nl> if ( Settings : : values . dump_nso ) { <nl> std : : vector < u8 > PatchManager : : PatchNSO ( const std : : vector < u8 > & nso , const std : : st <nl> } <nl> <nl> bool PatchManager : : HasNSOPatch ( const std : : array < u8 , 32 > & build_id_ ) const { <nl> - const auto build_id_raw = Common : : HexArrayToString ( build_id_ ) ; <nl> + const auto build_id_raw = Common : : HexToString ( build_id_ ) ; <nl> const auto build_id = build_id_raw . substr ( 0 , build_id_raw . find_last_not_of ( ' 0 ' ) + 1 ) ; <nl> <nl> LOG_INFO ( Loader , " Querying NSO patch existence for build_id = { } " , build_id ) ; <nl> bool PatchManager : : HasNSOPatch ( const std : : array < u8 , 32 > & build_id_ ) const { <nl> static std : : optional < CheatList > ReadCheatFileFromFolder ( const Core : : System & system , u64 title_id , <nl> const std : : array < u8 , 0x20 > & build_id_ , <nl> const VirtualDir & base_path , bool upper ) { <nl> - const auto build_id_raw = Common : : HexArrayToString ( build_id_ , upper ) ; <nl> + const auto build_id_raw = Common : : HexToString ( build_id_ , upper ) ; <nl> const auto build_id = build_id_raw . substr ( 0 , sizeof ( u64 ) * 2 ) ; <nl> const auto file = base_path - > GetFile ( fmt : : format ( " { } . txt " , build_id ) ) ; <nl> <nl> mmm a / src / core / file_sys / registered_cache . cpp <nl> ppp b / src / core / file_sys / registered_cache . cpp <nl> static bool FollowsNcaIdFormat ( std : : string_view name ) { <nl> <nl> static std : : string GetRelativePathFromNcaID ( const std : : array < u8 , 16 > & nca_id , bool second_hex_upper , <nl> bool within_two_digit ) { <nl> - if ( ! within_two_digit ) <nl> - return fmt : : format ( " / { } . nca " , Common : : HexArrayToString ( nca_id , second_hex_upper ) ) ; <nl> + if ( ! within_two_digit ) { <nl> + return fmt : : format ( " / { } . nca " , Common : : HexToString ( nca_id , second_hex_upper ) ) ; <nl> + } <nl> <nl> Core : : Crypto : : SHA256Hash hash { } ; <nl> mbedtls_sha256 ( nca_id . data ( ) , nca_id . size ( ) , hash . data ( ) , 0 ) ; <nl> return fmt : : format ( " / 000000 { : 02X } / { } . nca " , hash [ 0 ] , <nl> - Common : : HexArrayToString ( nca_id , second_hex_upper ) ) ; <nl> + Common : : HexToString ( nca_id , second_hex_upper ) ) ; <nl> } <nl> <nl> static std : : string GetCNMTName ( TitleType type , u64 title_id ) { <nl> std : : vector < ContentProviderEntry > RegisteredCache : : ListEntriesFilter ( <nl> } <nl> <nl> static std : : shared_ptr < NCA > GetNCAFromNSPForID ( const NSP & nsp , const NcaID & id ) { <nl> - const auto file = nsp . GetFile ( fmt : : format ( " { } . nca " , Common : : HexArrayToString ( id , false ) ) ) ; <nl> - if ( file = = nullptr ) <nl> + auto file = nsp . GetFile ( fmt : : format ( " { } . nca " , Common : : HexToString ( id , false ) ) ) ; <nl> + if ( file = = nullptr ) { <nl> return nullptr ; <nl> - return std : : make_shared < NCA > ( file ) ; <nl> + } <nl> + return std : : make_shared < NCA > ( std : : move ( file ) ) ; <nl> } <nl> <nl> InstallResult RegisteredCache : : InstallEntry ( const XCI & xci , bool overwrite_if_exists , <nl> mmm a / src / core / file_sys / submission_package . cpp <nl> ppp b / src / core / file_sys / submission_package . cpp <nl> void NSP : : ReadNCAs ( const std : : vector < VirtualFile > & files ) { <nl> const auto section0 = nca - > GetSubdirectories ( ) [ 0 ] ; <nl> <nl> for ( const auto & inner_file : section0 - > GetFiles ( ) ) { <nl> - if ( inner_file - > GetExtension ( ) ! = " cnmt " ) <nl> + if ( inner_file - > GetExtension ( ) ! = " cnmt " ) { <nl> continue ; <nl> + } <nl> <nl> const CNMT cnmt ( inner_file ) ; <nl> auto & ncas_title = ncas [ cnmt . GetTitleID ( ) ] ; <nl> <nl> ncas_title [ { cnmt . GetType ( ) , ContentRecordType : : Meta } ] = nca ; <nl> for ( const auto & rec : cnmt . GetContentRecords ( ) ) { <nl> - const auto id_string = Common : : HexArrayToString ( rec . nca_id , false ) ; <nl> - const auto next_file = pfs - > GetFile ( fmt : : format ( " { } . nca " , id_string ) ) ; <nl> + const auto id_string = Common : : HexToString ( rec . nca_id , false ) ; <nl> + auto next_file = pfs - > GetFile ( fmt : : format ( " { } . nca " , id_string ) ) ; <nl> + <nl> if ( next_file = = nullptr ) { <nl> LOG_WARNING ( Service_FS , <nl> " NCA with ID { } . nca is listed in content metadata , but cannot " <nl> void NSP : : ReadNCAs ( const std : : vector < VirtualFile > & files ) { <nl> continue ; <nl> } <nl> <nl> - auto next_nca = std : : make_shared < NCA > ( next_file , nullptr , 0 , keys ) ; <nl> - if ( next_nca - > GetType ( ) = = NCAContentType : : Program ) <nl> + auto next_nca = std : : make_shared < NCA > ( std : : move ( next_file ) , nullptr , 0 , keys ) ; <nl> + if ( next_nca - > GetType ( ) = = NCAContentType : : Program ) { <nl> program_status [ cnmt . GetTitleID ( ) ] = next_nca - > GetStatus ( ) ; <nl> + } <nl> if ( next_nca - > GetStatus ( ) = = Loader : : ResultStatus : : Success | | <nl> ( next_nca - > GetStatus ( ) = = Loader : : ResultStatus : : ErrorMissingBKTRBaseRomFS & & <nl> ( cnmt . GetTitleID ( ) & 0x800 ) ! = 0 ) ) { <nl> mmm a / src / core / file_sys / xts_archive . cpp <nl> ppp b / src / core / file_sys / xts_archive . cpp <nl> NAX : : NAX ( VirtualFile file_ , std : : array < u8 , 0x10 > nca_id ) <nl> Core : : Crypto : : SHA256Hash hash { } ; <nl> mbedtls_sha256 ( nca_id . data ( ) , nca_id . size ( ) , hash . data ( ) , 0 ) ; <nl> status = Parse ( fmt : : format ( " / registered / 000000 { : 02X } / { } . nca " , hash [ 0 ] , <nl> - Common : : HexArrayToString ( nca_id , false ) ) ) ; <nl> + Common : : HexToString ( nca_id , false ) ) ) ; <nl> } <nl> <nl> NAX : : ~ NAX ( ) = default ; <nl> mmm a / src / core / hle / service / am / applets / general_backend . cpp <nl> ppp b / src / core / hle / service / am / applets / general_backend . cpp <nl> <nl> / / Licensed under GPLv2 or any later version <nl> / / Refer to the license . txt file included . <nl> <nl> - # include < string > <nl> + # include < string_view > <nl> <nl> # include " common / assert . h " <nl> # include " common / hex_util . h " <nl> <nl> <nl> namespace Service : : AM : : Applets { <nl> <nl> - static void LogCurrentStorage ( AppletDataBroker & broker , std : : string prefix ) { <nl> + static void LogCurrentStorage ( AppletDataBroker & broker , std : : string_view prefix ) { <nl> std : : unique_ptr < IStorage > storage = broker . PopNormalDataToApplet ( ) ; <nl> for ( ; storage ! = nullptr ; storage = broker . PopNormalDataToApplet ( ) ) { <nl> const auto data = storage - > GetData ( ) ; <nl> LOG_INFO ( Service_AM , <nl> - " called ( STUBBED ) , during { } recieved normal data with size = { : 08X } , data = { } " , <nl> - prefix , data . size ( ) , Common : : HexVectorToString ( data ) ) ; <nl> + " called ( STUBBED ) , during { } received normal data with size = { : 08X } , data = { } " , <nl> + prefix , data . size ( ) , Common : : HexToString ( data ) ) ; <nl> } <nl> <nl> storage = broker . PopInteractiveDataToApplet ( ) ; <nl> for ( ; storage ! = nullptr ; storage = broker . PopInteractiveDataToApplet ( ) ) { <nl> const auto data = storage - > GetData ( ) ; <nl> LOG_INFO ( Service_AM , <nl> - " called ( STUBBED ) , during { } recieved interactive data with size = { : 08X } , data = { } " , <nl> - prefix , data . size ( ) , Common : : HexVectorToString ( data ) ) ; <nl> + " called ( STUBBED ) , during { } received interactive data with size = { : 08X } , data = { } " , <nl> + prefix , data . size ( ) , Common : : HexToString ( data ) ) ; <nl> } <nl> } <nl> <nl> mmm a / src / core / hle / service / ldr / ldr . cpp <nl> ppp b / src / core / hle / service / ldr / ldr . cpp <nl> class RelocatableObject final : public ServiceFramework < RelocatableObject > { <nl> if ( ! IsValidNROHash ( hash ) ) { <nl> LOG_ERROR ( Service_LDR , <nl> " NRO hash is not present in any currently loaded NRRs ( hash = { } ) ! " , <nl> - Common : : HexArrayToString ( hash ) ) ; <nl> + Common : : HexToString ( hash ) ) ; <nl> IPC : : ResponseBuilder rb { ctx , 2 } ; <nl> rb . Push ( ERROR_MISSING_NRR_HASH ) ; <nl> return ; <nl> mmm a / src / core / loader / nso . cpp <nl> ppp b / src / core / loader / nso . cpp <nl> std : : optional < VAddr > AppLoader_NSO : : LoadModule ( Kernel : : Process & process , <nl> auto & system = Core : : System : : GetInstance ( ) ; <nl> const auto cheats = pm - > CreateCheatList ( system , nso_header . build_id ) ; <nl> if ( ! cheats . empty ( ) ) { <nl> - system . RegisterCheatList ( cheats , Common : : HexArrayToString ( nso_header . build_id ) , <nl> - load_base , load_base + program_image . size ( ) ) ; <nl> + system . RegisterCheatList ( cheats , Common : : HexToString ( nso_header . build_id ) , load_base , <nl> + load_base + program_image . size ( ) ) ; <nl> } <nl> } <nl> <nl>
common / hex_util : Combine HexVectorToString ( ) and HexArrayToString ( )
yuzu-emu/yuzu
a62088539ed02a8569814601b3b99b713c5d8a34
2019-06-12T21:54:05Z
mmm a / src / Interpreters / Aggregator . cpp <nl> ppp b / src / Interpreters / Aggregator . cpp <nl> void NO_INLINE Aggregator : : mergeSingleLevelDataImpl ( <nl> } <nl> } <nl> <nl> + # define M ( NAME ) \ <nl> + template void NO_INLINE Aggregator : : mergeSingleLevelDataImpl < decltype ( AggregatedDataVariants : : NAME ) : : element_type > ( \ <nl> + ManyAggregatedDataVariants & non_empty_data ) const ; <nl> + APPLY_FOR_VARIANTS_SINGLE_LEVEL ( M ) <nl> + # undef M <nl> <nl> template < typename Method > <nl> void NO_INLINE Aggregator : : mergeBucketImpl ( <nl> mmm a / src / Parsers / ExpressionElementParsers . cpp <nl> ppp b / src / Parsers / ExpressionElementParsers . cpp <nl> bool ParserCollectionOfLiterals < Collection > : : parseImpl ( Pos & pos , ASTPtr & node , <nl> return false ; <nl> } <nl> <nl> + template bool ParserCollectionOfLiterals < Array > : : parseImpl ( Pos & pos , ASTPtr & node , Expected & expected ) ; <nl> + template bool ParserCollectionOfLiterals < Tuple > : : parseImpl ( Pos & pos , ASTPtr & node , Expected & expected ) ; <nl> <nl> bool ParserLiteral : : parseImpl ( Pos & pos , ASTPtr & node , Expected & expected ) <nl> { <nl>
Shared build fix
ClickHouse/ClickHouse
9d908f48e1d7926b39f447a4998d70768977537d
2020-05-08T20:55:08Z
mmm a / BUILD . gn <nl> ppp b / BUILD . gn <nl> v8_source_set ( " v8_base_without_compiler " ) { <nl> " src / deoptimizer / ppc / deoptimizer - ppc . cc " , <nl> " src / diagnostics / ppc / disasm - ppc . cc " , <nl> " src / diagnostics / ppc / eh - frame - ppc . cc " , <nl> + " src / diagnostics / ppc / unwinder - ppc . cc " , <nl> " src / execution / ppc / frame - constants - ppc . cc " , <nl> " src / execution / ppc / frame - constants - ppc . h " , <nl> " src / execution / ppc / simulator - ppc . cc " , <nl> v8_source_set ( " v8_base_without_compiler " ) { <nl> " src / deoptimizer / ppc / deoptimizer - ppc . cc " , <nl> " src / diagnostics / ppc / disasm - ppc . cc " , <nl> " src / diagnostics / ppc / eh - frame - ppc . cc " , <nl> + " src / diagnostics / ppc / unwinder - ppc . cc " , <nl> " src / execution / ppc / frame - constants - ppc . cc " , <nl> " src / execution / ppc / frame - constants - ppc . h " , <nl> " src / execution / ppc / simulator - ppc . cc " , <nl> v8_source_set ( " v8_base_without_compiler " ) { <nl> " src / deoptimizer / s390 / deoptimizer - s390 . cc " , <nl> " src / diagnostics / s390 / disasm - s390 . cc " , <nl> " src / diagnostics / s390 / eh - frame - s390 . cc " , <nl> + " src / diagnostics / s390 / unwinder - s390 . cc " , <nl> " src / execution / s390 / frame - constants - s390 . cc " , <nl> " src / execution / s390 / frame - constants - s390 . h " , <nl> " src / execution / s390 / simulator - s390 . cc " , <nl> new file mode 100644 <nl> index 00000000000 . . 43c6acb609e <nl> mmm / dev / null <nl> ppp b / src / diagnostics / ppc / unwinder - ppc . cc <nl> <nl> + / / Copyright 2020 the V8 project authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + # include " src / diagnostics / unwinder . h " <nl> + namespace v8 { <nl> + void GetCalleeSavedRegistersFromEntryFrame ( void * fp , <nl> + RegisterState * register_state ) { } <nl> + } / / namespace v8 <nl> new file mode 100644 <nl> index 00000000000 . . 43c6acb609e <nl> mmm / dev / null <nl> ppp b / src / diagnostics / s390 / unwinder - s390 . cc <nl> <nl> + / / Copyright 2020 the V8 project authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . <nl> + # include " src / diagnostics / unwinder . h " <nl> + namespace v8 { <nl> + void GetCalleeSavedRegistersFromEntryFrame ( void * fp , <nl> + RegisterState * register_state ) { } <nl> + } / / namespace v8 <nl>
PPC / s390 : [ unwinder ] Restore callee saved registers after unwinding in arm32
v8/v8
370f64c0c90fd7fd2b547146d62484346fbe3fcf
2020-10-21T13:15:29Z
mmm a / Doxygen / arango - html . doxy <nl> ppp b / Doxygen / arango - html . doxy <nl> PROJECT_NAME = " ArangoDB " <nl> # This could be handy for archiving the generated documentation or <nl> # if some version control system is used . <nl> <nl> - PROJECT_NUMBER = 0 . 4 . 2 <nl> + PROJECT_NUMBER = 0 . 5 . 0 <nl> <nl> # Using the PROJECT_BRIEF tag one can provide an optional one line description for a project that appears at the top of each page and should give viewer a quick idea about the purpose of the project . Keep the description short . <nl> <nl> ALIASES + = REST { 1 } = " < tt > < b > \ 1 < / b > < / tt > " <nl> ALIASES + = GE { 1 } = " < b > \ 1 < / b > " <nl> ALIASES + = EXAMPLES = " < b > Examples < / b > < br > " <nl> ALIASES + = EXAMPLE { 2 } = " @ latexonly \ renewcommand { \ examplecap } { \ 2 } @ endlatexonly @ verbinclude \ 1 @ latexonly \ renewcommand { \ examplecap } { } @ endlatexonly " <nl> - ALIASES + = VERSION = " 0 . 4 . 2 " <nl> + ALIASES + = VERSION = " 0 . 5 . 0 " <nl> ALIASES + = EMBEDTOC { 1 } = " @ ifnot LATEX < hr > @ copydoc \ 1 < hr > @ endif " <nl> ALIASES + = RESTHEADER { 2 } = " @ if LATEX @ latexonly \ vskip 0 . 5em \ colorbox { gray } { @ endlatexonly \ 1 ( \ 2 ) @ latexonly } \ vskip 1em @ endlatexonly @ else < hr > < em > \ 1 < / em > ( \ 2 ) < hr > < br > @ endif " <nl> ALIASES + = LATEXBREAK = " @ latexonly \ vskip - 0 . 5em \ hskip 1 . 0em @ endlatexonly " <nl> mmm a / Doxygen / arango - latex . doxy <nl> ppp b / Doxygen / arango - latex . doxy <nl> PROJECT_NAME = " ArangoDB " <nl> # This could be handy for archiving the generated documentation or <nl> # if some version control system is used . <nl> <nl> - PROJECT_NUMBER = 0 . 4 . 2 <nl> + PROJECT_NUMBER = 0 . 5 . 0 <nl> <nl> # Using the PROJECT_BRIEF tag one can provide an optional one line description for a project that appears at the top of each page and should give viewer a quick idea about the purpose of the project . Keep the description short . <nl> <nl> ALIASES + = REST { 1 } = " < tt > < b > \ 1 < / b > < / tt > " <nl> ALIASES + = GE { 1 } = " < b > \ 1 < / b > " <nl> ALIASES + = EXAMPLES = " < b > Examples < / b > < br > " <nl> ALIASES + = EXAMPLE { 2 } = " @ latexonly \ renewcommand { \ examplecap } { \ 2 } @ endlatexonly @ verbinclude \ 1 @ latexonly \ renewcommand { \ examplecap } { } @ endlatexonly " <nl> - ALIASES + = VERSION = " 0 . 4 . 2 " <nl> + ALIASES + = VERSION = " 0 . 5 . 0 " <nl> ALIASES + = EMBEDTOC { 1 } = " @ ifnot LATEX < hr > @ copydoc \ 1 < hr > @ endif " <nl> ALIASES + = RESTHEADER { 2 } = " @ if LATEX @ latexonly \ vskip 0 . 5em \ colorbox { gray } { @ endlatexonly \ 1 ( \ 2 ) @ latexonly } \ vskip 1em @ endlatexonly @ else < hr > < em > \ 1 < / em > ( \ 2 ) < hr > < br > @ endif " <nl> ALIASES + = LATEXBREAK = " @ latexonly \ vskip - 0 . 5em \ hskip 1 . 0em @ endlatexonly " <nl> mmm a / Doxygen / arango - xml . doxy <nl> ppp b / Doxygen / arango - xml . doxy <nl> PROJECT_NAME = " ArangoDB " <nl> # This could be handy for archiving the generated documentation or <nl> # if some version control system is used . <nl> <nl> - PROJECT_NUMBER = 0 . 4 . 2 <nl> + PROJECT_NUMBER = 0 . 5 . 0 <nl> <nl> # Using the PROJECT_BRIEF tag one can provide an optional one line description for a project that appears at the top of each page and should give viewer a quick idea about the purpose of the project . Keep the description short . <nl> <nl> ALIASES + = REST { 1 } = " < tt > < b > \ 1 < / b > < / tt > " <nl> ALIASES + = GE { 1 } = " < b > \ 1 < / b > " <nl> ALIASES + = EXAMPLES = " < b > Examples < / b > < br > " <nl> ALIASES + = EXAMPLE { 2 } = " @ latexonly \ renewcommand { \ examplecap } { \ 2 } @ endlatexonly @ verbinclude \ 1 @ latexonly \ renewcommand { \ examplecap } { } @ endlatexonly " <nl> - ALIASES + = VERSION = " 0 . 4 . 2 " <nl> + ALIASES + = VERSION = " 0 . 5 . 0 " <nl> ALIASES + = EMBEDTOC { 1 } = " @ ifnot LATEX < hr > @ copydoc \ 1 < hr > @ endif " <nl> ALIASES + = RESTHEADER { 2 } = " @ if LATEX @ latexonly \ vskip 0 . 5em \ colorbox { gray } { @ endlatexonly \ 1 ( \ 2 ) @ latexonly } \ vskip 1em @ endlatexonly @ else < hr > < em > \ 1 < / em > ( \ 2 ) < hr > < br > @ endif " <nl> ALIASES + = LATEXBREAK = " @ latexonly \ vskip - 0 . 5em \ hskip 1 . 0em @ endlatexonly " <nl> mmm a / RestServer / home . dox <nl> ppp b / RestServer / home . dox <nl> <nl> / / / The ArangoDB consists of a server , a separate shell , which allows you to <nl> / / / administrate the server , and a set of client API for various languages . <nl> / / / <nl> - / / / @ xmlonly The HTML version of the manual can be found < ulink url = " / manuals " > here < / ulink > . @ endxmlonly <nl> + / / / @ xmlonly The HTML version of the manual can be found < ulink url = " http : / / www . arangodb . org / manuals " > here < / ulink > . @ endxmlonly <nl> / / / <nl> / / / @ warning <nl> / / / ArangoDB is currently pre - alpha . We want to have a version 1 ready by end <nl> <nl> / / / @ section ArangoDBServer ArangoDB Server ( Version @ VERSION ) <nl> / / / <nl> / / / < ul > <nl> - / / / < li > @ ref InstallManual ( < a href = " / manuals / install - manual . pdf " > pdf < / a > ) < / li > <nl> - / / / < li > @ ref UserManualServer ( < a href = " / manuals / user - manual - server . pdf " > pdf < / a > ) < / a > < / li > <nl> - / / / < li > @ ref ImplementorManual ( < a href = " / manuals / implementor - manual . pdf " > pdf < / a > ) < / li > <nl> + / / / < li > @ ref InstallManual ( < ulink url = " http : / / www . arangodb . org / manuals / install - manual . pdf " > pdf < / ulink > ) < / li > <nl> + / / / < li > @ ref UserManualServer ( < ulink url = " http : / / www . arangodb . org / manuals / user - manual - server . pdf " > pdf < / ulink > ) < / a > < / li > <nl> + / / / < li > @ ref ImplementorManual ( < ulink url = " http : / / www . arangodb . org / manuals / implementor - manual . pdf " > pdf < / ulink > ) < / li > <nl> / / / < li > @ ref RefManual < / li > <nl> / / / < li > @ ref Glossary < / li > <nl> / / / < / ul > <nl>
fixed link
arangodb/arangodb
87df71374f677d931f1a2b767cb5d06954895aa9
2012-05-12T20:37:58Z
mmm a / . travis . yml <nl> ppp b / . travis . yml <nl> <nl> - dist : trusty <nl> - sudo : true <nl> - # <nl> - language : c <nl> - # <nl> - dist : trusty <nl> - sudo : required <nl> - group : deprecated - 2017Q2 <nl> + language : python <nl> + python : <nl> + - " 2 . 7 " <nl> + <nl> notifications : <nl> email : false <nl> - # <nl> + <nl> + # Cache PlatformIO packages using Travis CI container - based infrastructure <nl> + sudo : false <nl> + cache : <nl> + pip : true <nl> + directories : <nl> + - " ~ / . platformio " <nl> + <nl> + env : <nl> + - TEST_PLATFORM = " - e megaatmega2560 " <nl> + <nl> before_install : <nl> # <nl> # Fetch the tag information for the current branch <nl> before_install : <nl> # <nl> # Publish the buildroot script folder <nl> - chmod + x $ { TRAVIS_BUILD_DIR } / buildroot / bin / * <nl> - - export PATH = $ { TRAVIS_BUILD_DIR } / buildroot / bin / : $ { PATH } <nl> - # <nl> - # Start fb X server <nl> - - " / sbin / start - stop - daemon - - start - - quiet - - pidfile / tmp / custom_xvfb_1 . pid - - make - pidfile - - background - - exec / usr / bin / Xvfb - - : 1 - ac - screen 0 1280x1024x16 " <nl> - - sleep 3 <nl> - - export DISPLAY = : 1 . 0 <nl> - # <nl> - # Teensy compiling <nl> - - lsb_release - a <nl> - - sudo apt - get - qq update <nl> - - sudo apt - get install - y binutils - arm - none - eabi gcc - arm - none - eabi lib32ncurses5 lib32z1 <nl> - # <nl> - install : <nl> - # <nl> - # Install arduino 1 . 8 . 0 <nl> - - wget http : / / downloads - 02 . arduino . cc / arduino - 1 . 8 . 0 - linux64 . tar . xz <nl> - - tar xf arduino - 1 . 8 . 0 - linux64 . tar . xz <nl> - - sudo mv arduino - 1 . 8 . 0 / usr / local / share / arduino <nl> - - ln - s / usr / local / share / arduino / arduino $ { TRAVIS_BUILD_DIR } / buildroot / bin / arduino <nl> - # <nl> - # Install : LiquidCrystal_I2C library <nl> - - git clone https : / / github . com / kiyoshigawa / LiquidCrystal_I2C . git <nl> - - mv LiquidCrystal_I2C / LiquidCrystal_I2C / usr / local / share / arduino / libraries / LiquidCrystal_I2C <nl> - # <nl> - # Install : LiquidTWI2 library <nl> - - git clone https : / / github . com / lincomatic / LiquidTWI2 . git <nl> - - sudo mv LiquidTWI2 / usr / local / share / arduino / libraries / LiquidTWI2 <nl> - # <nl> - # Install : Monochrome Graphics Library for LCDs and OLEDs <nl> - - git clone https : / / github . com / olikraus / U8glib_Arduino . git <nl> - - sudo mv U8glib_Arduino / usr / local / share / arduino / libraries / U8glib <nl> - # <nl> - # Install : L6470 Stepper Motor Driver library <nl> - # - git clone https : / / github . com / ameyer / Arduino - L6470 . git <nl> - # - sudo mv Arduino - L6470 / L6470 / usr / local / share / arduino / libraries / L6470 <nl> - # <nl> - # Install : TMC26X Stepper Motor Controller library <nl> - # - git clone https : / / github . com / trinamic / TMC26XStepper . git <nl> - # - sudo mv TMC26XStepper / usr / local / share / arduino / libraries / TMC26XStepper <nl> - # <nl> - # Install : TMC2130 Stepper Motor Controller library <nl> - - git clone https : / / github . com / teemuatlut / TMC2130Stepper . git <nl> - - sudo mv TMC2130Stepper / usr / local / share / arduino / libraries / TMC2130Stepper <nl> - # <nl> - # Install : Adafruit Neopixel library <nl> - - git clone https : / / github . com / adafruit / Adafruit_NeoPixel . git <nl> - - sudo mv Adafruit_NeoPixel / usr / local / share / arduino / libraries / Adafruit_NeoPixel <nl> - # <nl> - # Install Teensy stuff <nl> - <nl> - - wget https : / / developer . arm . com / - / media / Files / downloads / gnu - rm / 5_4 - 2016q2 / gccarmnoneeabi542016q220160622linuxtar . bz2 <nl> - - tar xf gccarmnoneeabi542016q220160622linuxtar . bz2 <nl> - - sudo mkdir - p / usr / local / share / arduino / hardware / tools / arm <nl> - - sudo mv gcc - arm - none - eabi - 5_4 - 2016q2 / * / usr / local / share / arduino / hardware / tools / arm / <nl> - <nl> - - wget https : / / github . com / ARM - software / CMSIS_5 / raw / develop / CMSIS / Lib / ARM / arm_cortexM4lf_math . lib <nl> - - sudo mv arm_cortexM4lf_math . lib / usr / local / share / arduino / hardware / tools / arm / arm - none - eabi / lib / libarm_cortexM4lf_math . a <nl> - <nl> - - git clone https : / / github . com / teemuatlut / teensyfiles_for_marlin . git <nl> - - sudo mkdir - p / usr / local / share / arduino / hardware / teensy / avr <nl> - - sudo cp teensyfiles_for_marlin / * . txt / usr / local / share / arduino / hardware / teensy / avr / <nl> - <nl> - - git clone https : / / github . com / PaulStoffregen / cores . git <nl> - - sudo mv cores / usr / local / share / arduino / hardware / teensy / avr <nl> - <nl> - # Teensy libraries <nl> + - ln - s $ { TRAVIS_BUILD_DIR } / buildroot / bin / ~ / bin <nl> <nl> - - git clone https : / / github . com / PaulStoffregen / Wire . git <nl> - - git clone https : / / github . com / PaulStoffregen / SPI . git <nl> - - git clone https : / / github . com / PaulStoffregen / Servo . git <nl> - - sudo mkdir - p / usr / local / share / arduino / hardware / teensy / avr / libraries / <nl> - - sudo mv Wire / usr / local / share / arduino / hardware / teensy / avr / libraries / <nl> - - sudo mv SPI / usr / local / share / arduino / hardware / teensy / avr / libraries / <nl> - - sudo mv Servo / usr / local / share / arduino / hardware / teensy / avr / libraries / <nl> + install : <nl> + - pip install - U platformio <nl> <nl> - - mkdir - p / usr / local / share / arduino / hardware / tools / arm <nl> - - sudo ln - s / usr / bin / usr / local / share / arduino / hardware / tools / arm / bin <nl> - - sudo ln - s / usr / lib / usr / local / share / arduino / hardware / tools / arm / lib <nl> before_script : <nl> # <nl> # Change current working directory to the build dir <nl> script : <nl> # <nl> # Build with the default configurations <nl> # <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test 2 extruders ( one MAX6675 ) and heated bed on basic RAMPS 1 . 4 <nl> # Test a " Fix Mounted " Probe with Safe Homing , some arc options , <nl> script : <nl> - opt_enable PIDTEMPBED FIX_MOUNTED_PROBE Z_SAFE_HOMING ARC_P_CIRCLES CNC_WORKSPACE_PLANES <nl> - opt_enable REPRAP_DISCOUNT_SMART_CONTROLLER SDSUPPORT EEPROM_SETTINGS <nl> - opt_enable BLINKM PCA9632 RGB_LED NEOPIXEL_RGBW_LED <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> + <nl> + # <nl> + # . . . with AUTO_BED_LEVELING_LINEAR , Z_MIN_PROBE_REPEATABILITY_TEST , and DEBUG_LEVELING_FEATURE <nl> + # <nl> - opt_enable AUTO_BED_LEVELING_LINEAR Z_MIN_PROBE_REPEATABILITY_TEST DEBUG_LEVELING_FEATURE <nl> - opt_enable_adv FWRETRACT MAX7219_DEBUG <nl> - opt_set ABL_GRID_POINTS_X 16 <nl> - opt_set ABL_GRID_POINTS_Y 16 <nl> - - opt_set_adv FANMUX0_PIN 53 <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test a simple build of AUTO_BED_LEVELING_UBL <nl> # <nl> - restore_configs <nl> - opt_enable AUTO_BED_LEVELING_UBL UBL_G26_MESH_EDITING ENABLE_LEVELING_FADE_HEIGHT FIX_MOUNTED_PROBE EEPROM_SETTINGS G3D_PANEL <nl> - opt_enable_adv CUSTOM_USER_MENUS I2C_POSITION_ENCODERS BABYSTEPPING <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test a Sled Z Probe <nl> # . . . with AUTO_BED_LEVELING_LINEAR , DEBUG_LEVELING_FEATURE , EEPROM_SETTINGS , and EEPROM_CHITCHAT <nl> # <nl> - restore_configs <nl> - opt_enable Z_PROBE_SLED AUTO_BED_LEVELING_LINEAR DEBUG_LEVELING_FEATURE EEPROM_SETTINGS EEPROM_CHITCHAT <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test a Servo Probe <nl> # . . . with AUTO_BED_LEVELING_3POINT , DEBUG_LEVELING_FEATURE , EEPROM_SETTINGS , EEPROM_CHITCHAT , EXTENDED_CAPABILITIES_REPORT , and AUTO_REPORT_TEMPERATURES <nl> script : <nl> - opt_set NUM_SERVOS 1 <nl> - opt_enable AUTO_BED_LEVELING_3POINT DEBUG_LEVELING_FEATURE EEPROM_SETTINGS EEPROM_CHITCHAT <nl> - opt_enable_adv EXTENDED_CAPABILITIES_REPORT AUTO_REPORT_TEMPERATURES AUTOTEMP G38_PROBE_TARGET <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test MESH_BED_LEVELING feature , with LCD <nl> # <nl> - restore_configs <nl> - opt_enable MESH_BED_LEVELING MESH_G28_REST_ORIGIN LCD_BED_LEVELING ULTIMAKERCONTROLLER <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test PROBE_MANUALLY feature , with LCD support , <nl> # EEPROM_SETTINGS , EEPROM_CHITCHAT , M100_FREE_MEMORY_WATCHER , <nl> script : <nl> - opt_set MOTHERBOARD BOARD_MINIRAMBO <nl> - opt_enable PROBE_MANUALLY AUTO_BED_LEVELING_BILINEAR LCD_BED_LEVELING ULTIMAKERCONTROLLER <nl> - opt_enable EEPROM_SETTINGS EEPROM_CHITCHAT M100_FREE_MEMORY_WATCHER M100_FREE_MEMORY_DUMPER M100_FREE_MEMORY_CORRUPTOR INCH_MODE_SUPPORT TEMPERATURE_UNITS_SUPPORT <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test 5 extruders on AZTEEG_X3_PRO ( can use any board with > = 5 extruders defined ) <nl> # Include a test for LIN_ADVANCE here also <nl> script : <nl> - opt_set TEMP_SENSOR_4 999 <nl> - opt_set TEMP_SENSOR_BED 1 <nl> - opt_enable_adv LIN_ADVANCE <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Mixing Extruder with 5 steppers <nl> # <nl> script : <nl> - opt_set MOTHERBOARD BOARD_AZTEEG_X3_PRO <nl> - opt_enable MIXING_EXTRUDER <nl> - opt_set MIXING_STEPPERS 5 <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test DUAL_X_CARRIAGE <nl> # <nl> script : <nl> - opt_set TEMP_SENSOR_1 1 <nl> - opt_enable USE_XMAX_PLUG <nl> - opt_enable_adv DUAL_X_CARRIAGE <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test SPEAKER with BOARD_BQ_ZUM_MEGA_3D and BQ_LCD_SMART_CONTROLLER <nl> # <nl> script : <nl> - opt_set NUM_SERVOS 1 <nl> - opt_set TEMP_SENSOR_1 1 <nl> - opt_enable SWITCHING_EXTRUDER ULTIMAKERCONTROLLER <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test MINIRAMBO for PWM_MOTOR_CURRENT <nl> # ULTIMAKERCONTROLLER , FILAMENT_LCD_DISPLAY , FILAMENT_WIDTH_SENSOR , <nl> script : <nl> - opt_enable_adv FILAMENT_CHANGE_FEATURE PARK_HEAD_ON_PAUSE LCD_INFO_MENU <nl> - pins_set RAMPS X_MAX_PIN - 1 <nl> - opt_set_adv Z2_MAX_PIN 2 <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable COREXY <nl> # <nl> - restore_configs <nl> - opt_enable COREXY <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable COREYX ( swapped ) <nl> # <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable ULTRA_LCD <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # DOGLCD <nl> # <nl> - restore_configs <nl> - opt_enable DOGLCD <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # MAKRPANEL <nl> # Needs to use Melzi and Sanguino hardware <nl> script : <nl> - restore_configs <nl> - opt_set MOTHERBOARD BOARD_RIGIDBOARD_V2 <nl> - opt_enable REPRAP_DISCOUNT_SMART_CONTROLLER SDSUPPORT BABYSTEPPING DAC_MOTOR_CURRENT_DEFAULT <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # G3D_PANEL with SDCARD_SORT_ALPHA and STATUS_MESSAGE_SCROLLING <nl> # <nl> script : <nl> - opt_set_adv SDSORT_USES_RAM true <nl> - opt_set_adv SDSORT_USES_STACK true <nl> - opt_set_adv SDSORT_CACHE_NAMES true <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER with SDCARD_SORT_ALPHA and STATUS_MESSAGE_SCROLLING <nl> # <nl> - restore_configs <nl> - opt_enable REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER SDSUPPORT <nl> - opt_enable_adv SDCARD_SORT_ALPHA STATUS_MESSAGE_SCROLLING <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # REPRAPWORLD_KEYPAD <nl> # <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable RA_CONTROL_PANEL PINS_DEBUGGING <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # # # # # # # # I2C LCD / PANELS # # # # # # # # # # # # # # <nl> # <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable LCM1602 <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # <nl> # # # # # # # # Example Configurations # # # # # # # # # # # # # # <nl> script : <nl> # Delta Config ( generic ) + ABL bilinear + PROBE_MANUALLY <nl> - use_example_configs delta / generic <nl> - opt_enable REPRAP_DISCOUNT_SMART_CONTROLLER DELTA_CALIBRATION_MENU AUTO_BED_LEVELING_BILINEAR PROBE_MANUALLY <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Delta Config ( generic ) + UBL + ALLEN_KEY + OLED_PANEL_TINYBOY2 + EEPROM_SETTINGS <nl> # <nl> - use_example_configs delta / generic <nl> - opt_disable DISABLE_MIN_ENDSTOPS <nl> - opt_enable AUTO_BED_LEVELING_UBL Z_PROBE_ALLEN_KEY EEPROM_SETTINGS EEPROM_CHITCHAT OLED_PANEL_TINYBOY2 <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Delta Config ( FLSUN AC because it ' s complex ) <nl> # <nl> - use_example_configs delta / FLSUN / auto_calibrate <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Makibox Config need to check board type for Teensy + + 2 . 0 <nl> # <nl> script : <nl> - opt_enable AUTO_BED_LEVELING_BILINEAR FIX_MOUNTED_PROBE USE_ZMIN_PLUG EEPROM_SETTINGS EEPROM_CHITCHAT ULTIMAKERCONTROLLER <nl> - opt_enable_adv HAVE_TMC2130 X_IS_TMC2130 Y_IS_TMC2130 Z_IS_TMC2130 <nl> - opt_enable_adv AUTOMATIC_CURRENT_CONTROL STEALTHCHOP HYBRID_THRESHOLD SENSORLESS_HOMING <nl> - - build_marlin <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # tvrrug Config need to check board type for sanguino atmega644p <nl> # <nl> script : <nl> # <nl> # To be added in nightly test branch <nl> # <nl> - # Backup Configuration . h , Configuration_adv . h , and pins_RAMPS . h <nl> - # <nl> + <nl> + - export TEST_PLATFORM = " - e teensy35 " <nl> - restore_configs <nl> - opt_set MOTHERBOARD BOARD_TEENSY35_36 <nl> - cp Marlin / Configuration . h Marlin / Configuration . h . backup <nl> script : <nl> # <nl> # Test Teensy3 . 5 with default config <nl> # <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test heated bed temperature sensor <nl> # <nl> - opt_set TEMP_SENSOR_BED 1 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test 2 extruders on basic RAMPS 1 . 4 <nl> # <nl> - opt_set EXTRUDERS 2 <nl> - opt_set TEMP_SENSOR_1 1 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test PIDTEMPBED <nl> # <nl> - restore_configs <nl> - opt_enable PIDTEMPBED <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test a " Fix Mounted " Probe along with Safe Homing <nl> # <nl> - restore_configs <nl> - opt_enable FIX_MOUNTED_PROBE Z_SAFE_HOMING <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # . . . with AUTO_BED_LEVELING_LINEAR , Z_MIN_PROBE_REPEATABILITY_TEST , and DEBUG_LEVELING_FEATURE <nl> # <nl> - opt_enable AUTO_BED_LEVELING_LINEAR Z_MIN_PROBE_REPEATABILITY_TEST DEBUG_LEVELING_FEATURE <nl> - opt_set ABL_GRID_POINTS_X 16 <nl> - opt_set ABL_GRID_POINTS_Y 16 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test a Sled Z Probe <nl> # <nl> - restore_configs <nl> - opt_enable Z_PROBE_SLED <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # . . . with AUTO_BED_LEVELING_LINEAR , DEBUG_LEVELING_FEATURE , EEPROM_SETTINGS , and EEPROM_CHITCHAT <nl> # <nl> - opt_enable AUTO_BED_LEVELING_LINEAR DEBUG_LEVELING_FEATURE EEPROM_SETTINGS EEPROM_CHITCHAT <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test a Servo Probe <nl> # <nl> - restore_configs <nl> - opt_enable NUM_SERVOS Z_ENDSTOP_SERVO_NR Z_SERVO_ANGLES DEACTIVATE_SERVOS_AFTER_MOVE <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # . . . with AUTO_BED_LEVELING_3POINT , DEBUG_LEVELING_FEATURE , EEPROM_SETTINGS , EEPROM_CHITCHAT , EXTENDED_CAPABILITIES_REPORT , and AUTO_REPORT_TEMPERATURES <nl> # <nl> - opt_enable AUTO_BED_LEVELING_3POINT DEBUG_LEVELING_FEATURE EEPROM_SETTINGS EEPROM_CHITCHAT <nl> - opt_enable_adv EXTENDED_CAPABILITIES_REPORT AUTO_REPORT_TEMPERATURES <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test MESH_BED_LEVELING feature , with LCD <nl> # <nl> - restore_configs <nl> - opt_enable MESH_BED_LEVELING MESH_G28_REST_ORIGIN MANUAL_BED_LEVELING ULTIMAKERCONTROLLER <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test EEPROM_SETTINGS , EEPROM_CHITCHAT , M100_FREE_MEMORY_WATCHER , <nl> # INCH_MODE_SUPPORT , TEMPERATURE_UNITS_SUPPORT <nl> script : <nl> - restore_configs <nl> # - opt_enable M100_FREE_MEMORY_WATCHER / / Compiler error ! <nl> - opt_enable EEPROM_SETTINGS EEPROM_CHITCHAT INCH_MODE_SUPPORT TEMPERATURE_UNITS_SUPPORT <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Mixing Extruder <nl> # <nl> - restore_configs <nl> - opt_enable MIXING_EXTRUDER <nl> - opt_set MIXING_STEPPERS 2 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test DUAL_X_CARRIAGE <nl> # <nl> script : <nl> - opt_set NUM_SERVOS 1 <nl> - opt_set TEMP_SENSOR_1 1 <nl> - opt_enable SWITCHING_EXTRUDER ULTIMAKERCONTROLLER <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test FILAMENT_CHANGE_FEATURE and LCD_INFO_MENU <nl> # <nl> - restore_configs <nl> - opt_enable ULTIMAKERCONTROLLER <nl> - opt_enable_adv FILAMENT_CHANGE_FEATURE LCD_INFO_MENU <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable filament sensor <nl> # <nl> - restore_configs <nl> - opt_enable FILAMENT_WIDTH_SENSOR <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable filament sensor with LCD display <nl> # <nl> - opt_enable ULTIMAKERCONTROLLER FILAMENT_LCD_DISPLAY <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable BEZIER_CURVE_SUPPORT , EXPERIMENTAL_I2CBUS , and I2C_SLAVE_ADDRESS <nl> # <nl> - restore_configs <nl> - opt_enable_adv BEZIER_CURVE_SUPPORT EXPERIMENTAL_I2CBUS <nl> - opt_set_adv I2C_SLAVE_ADDRESS 63 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable COREXY <nl> # <nl> - restore_configs <nl> - opt_enable COREXY <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable COREXZ <nl> # <nl> - restore_configs <nl> - opt_enable COREXZ <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Enable Z_DUAL_STEPPER_DRIVERS , Z_DUAL_ENDSTOPS <nl> # <nl> script : <nl> - opt_enable_adv Z_DUAL_STEPPER_DRIVERS Z_DUAL_ENDSTOPS <nl> - pins_set RAMPS X_MAX_PIN - 1 <nl> - opt_set_adv Z2_MAX_PIN 2 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test PRINTCOUNTER <nl> # <nl> - restore_configs <nl> - opt_enable PRINTCOUNTER <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test NOZZLE_PARK_FEATURE <nl> # <nl> - restore_configs <nl> - opt_enable NOZZLE_PARK_FEATURE <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # Test NOZZLE_CLEAN_FEATURE <nl> # <nl> - restore_configs <nl> - opt_enable NOZZLE_CLEAN_FEATURE <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # <nl> # # # # # # # # STANDARD LCD / PANELS # # # # # # # # # # # # # # <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable ULTRA_LCD <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # DOGLCD <nl> # <nl> - restore_configs <nl> - opt_enable DOGLCD <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # ULTIMAKERCONTROLLER <nl> # <nl> - restore_configs <nl> - opt_enable ULTIMAKERCONTROLLER <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # MAKRPANEL <nl> # Needs to use Melzi and Sanguino hardware <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable REPRAP_DISCOUNT_SMART_CONTROLLER SDSUPPORT BABYSTEPPING <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # G3D_PANEL <nl> # <nl> - restore_configs <nl> - opt_enable G3D_PANEL SDSUPPORT <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER <nl> # <nl> - restore_configs <nl> - opt_enable REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER SDSUPPORT <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # REPRAPWORLD_KEYPAD <nl> # <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable RA_CONTROL_PANEL <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> # <nl> # # # # # # # # I2C LCD / PANELS # # # # # # # # # # # # # # <nl> # <nl> script : <nl> # <nl> - restore_configs <nl> - opt_enable LCM1602 <nl> - - build_marlin_teensy35 <nl> + - build_marlin_pio $ { TRAVIS_BUILD_DIR } $ { TEST_PLATFORM } <nl> new file mode 100755 <nl> index 00000000000 . . b3c113c2f62 <nl> mmm / dev / null <nl> ppp b / buildroot / bin / build_marlin_pio <nl> <nl> + # ! / usr / bin / env bash <nl> + <nl> + platformio run - - project - dir $ @ - - silent <nl> mmm a / platformio . ini <nl> ppp b / platformio . ini <nl> lib_deps = <nl> LiquidCrystal_I2C @ 1 . 1 . 2 <nl> https : / / github . com / lincomatic / LiquidTWI2 . git <nl> https : / / github . com / teemuatlut / TMC2130Stepper . git <nl> + https : / / github . com / adafruit / Adafruit_NeoPixel . git <nl> default_src_filter = + < * > - < example_configurations > - < src / HAL / HAL_ * > <nl> <nl> [ env : megaatmega2560 ] <nl> lib_deps = $ { common . lib_deps } <nl> platform = atmelsam <nl> framework = arduino <nl> board = due <nl> - build_flags = - I $ BUILDSRC_DIR <nl> + build_flags = - I $ BUILDSRC_DIR - D MOTHERBOARD = BOARD_RAMPS4DUE_EFB <nl> lib_deps = $ { common . lib_deps } <nl> src_filter = $ { common . default_src_filter } + < src / HAL / HAL_DUE > <nl> <nl>
PlatformIO Travis test
MarlinFirmware/Marlin
d2fb3215da98cd799670b22d7ab133392a1f2408
2017-08-31T23:23:44Z
mmm a / contrib / devtools / github - merge . sh <nl> ppp b / contrib / devtools / github - merge . sh <nl> read - p " Press ' s ' to sign off on the merge . " - n 1 - r > & 2 <nl> echo <nl> if [ [ " d $ REPLY " = ~ ^ d [ Ss ] $ ] ] ; then <nl> if [ [ " $ ( git config - - get user . signingkey ) " = = " " ] ] ; then <nl> - echo " WARNING : No GPG signing key set , not signing . Set one using : " > & 2 <nl> + echo " ERROR : No GPG signing key set , not signing . Set one using : " > & 2 <nl> echo " git config - - global user . signingkey < key > " > & 2 <nl> - git commit - q - - signoff - - amend - - no - edit <nl> + cleanup <nl> + exit 1 <nl> else <nl> git commit - q - - gpg - sign - - amend - - no - edit <nl> fi <nl> + else <nl> + echo " Not signing off on merge , exiting . " <nl> + cleanup <nl> + exit 1 <nl> fi <nl> <nl> # Clean up temporary branches , and put the result in $ BRANCH . <nl>
Merge pull request
bitcoin/bitcoin
66ef824a9fb382871abb2db127fba9b53bb7b90f
2014-12-23T10:28:08Z
mmm a / modules / ocl / doc / image_filtering . rst <nl> ppp b / modules / ocl / doc / image_filtering . rst <nl> Returns void <nl> <nl> The function calculates the Laplacian of the source image by adding up the second x and y derivatives calculated using the Sobel operator . <nl> <nl> + ocl : : ConvolveBuf <nl> + mmmmmmmmmmmmmmm - <nl> + . . ocv : struct : : ocl : : ConvolveBuf <nl> + <nl> + Class providing a memory buffer for : ocv : func : ` ocl : : convolve ` function , plus it allows to adjust some specific parameters . : : <nl> + <nl> + struct CV_EXPORTS ConvolveBuf <nl> + { <nl> + Size result_size ; <nl> + Size block_size ; <nl> + Size user_block_size ; <nl> + Size dft_size ; <nl> + int spect_len ; <nl> + <nl> + oclMat image_spect , templ_spect , result_spect ; <nl> + oclMat image_block , templ_block , result_data ; <nl> + <nl> + void create ( Size image_size , Size templ_size ) ; <nl> + static Size estimateBlockSize ( Size result_size , Size templ_size ) ; <nl> + } ; <nl> + <nl> + You can use field ` user_block_size ` to set specific block size for : ocv : func : ` ocl : : convolve ` function . If you leave its default value ` Size ( 0 , 0 ) ` then automatic estimation of block size will be used ( which is optimized for speed ) . By varying ` user_block_size ` you can reduce memory requirements at the cost of speed . <nl> + <nl> + ocl : : ConvolveBuf : : create <nl> + mmmmmmmmmmmmmmmmmmmmmmmm <nl> + . . ocv : function : : ocl : : ConvolveBuf : : create ( Size image_size , Size templ_size ) <nl> + <nl> + Constructs a buffer for : ocv : func : ` ocl : : convolve ` function with respective arguments . <nl> + <nl> ocl : : convolve <nl> mmmmmmmmmmmmmmmmmm <nl> Returns void <nl> <nl> - . . ocv : function : : void ocl : : convolve ( const oclMat & image , const oclMat & temp1 , oclMat & result ) <nl> + . . ocv : function : : void ocl : : convolve ( const oclMat & image , const oclMat & temp1 , oclMat & result , bool ccorr = false ) <nl> + <nl> + . . ocv : function : : void ocl : : convolve ( const oclMat & image , const oclMat & temp1 , oclMat & result , bool ccorr , ConvolveBuf & buf ) <nl> <nl> - : param image : The source image <nl> + : param image : The source image . Only ` ` CV_32FC1 ` ` images are supported for now . <nl> <nl> - : param temp1 : Convolution kernel , a single - channel floating point matrix . <nl> + : param temp1 : Convolution kernel , a single - channel floating point matrix . The size is not greater than the ` ` image ` ` size . The type is the same as ` ` image ` ` . <nl> <nl> : param result : The destination image <nl> + <nl> + : param ccorr : Flags to evaluate cross - correlation instead of convolution . <nl> + <nl> + : param buf : Optional buffer to avoid extra memory allocations and to adjust some specific parameters . See : ocv : struct : ` ocl : : ConvolveBuf ` . <nl> <nl> Convolves an image with the kernel . Supports only CV_32FC1 data types and do not support ROI . <nl> <nl> mmm a / modules / ocl / include / opencv2 / ocl . hpp <nl> ppp b / modules / ocl / include / opencv2 / ocl . hpp <nl> namespace cv <nl> CV_EXPORTS oclMatExpr operator * ( const oclMat & src1 , const oclMat & src2 ) ; <nl> CV_EXPORTS oclMatExpr operator / ( const oclMat & src1 , const oclMat & src2 ) ; <nl> <nl> - / / ! computes convolution of two images <nl> + struct CV_EXPORTS ConvolveBuf <nl> + { <nl> + Size result_size ; <nl> + Size block_size ; <nl> + Size user_block_size ; <nl> + Size dft_size ; <nl> + <nl> + oclMat image_spect , templ_spect , result_spect ; <nl> + oclMat image_block , templ_block , result_data ; <nl> + <nl> + void create ( Size image_size , Size templ_size ) ; <nl> + static Size estimateBlockSize ( Size result_size , Size templ_size ) ; <nl> + } ; <nl> + <nl> + / / ! computes convolution of two images , may use discrete Fourier transform <nl> / / ! support only CV_32FC1 type <nl> - CV_EXPORTS void convolve ( const oclMat & image , const oclMat & temp1 , oclMat & result ) ; <nl> + CV_EXPORTS void convolve ( const oclMat & image , const oclMat & temp1 , oclMat & result , bool ccorr = false ) ; <nl> + CV_EXPORTS void convolve ( const oclMat & image , const oclMat & temp1 , oclMat & result , bool ccorr , ConvolveBuf & buf ) ; <nl> + <nl> + / / ! Performs a per - element multiplication of two Fourier spectrums . <nl> + / / ! Only full ( not packed ) CV_32FC2 complex spectrums in the interleaved format are supported for now . <nl> + / / ! support only CV_32FC2 type <nl> + CV_EXPORTS void mulSpectrums ( const oclMat & a , const oclMat & b , oclMat & c , int flags , float scale , bool conjB = false ) ; <nl> <nl> CV_EXPORTS void cvtColor ( const oclMat & src , oclMat & dst , int code , int dcn = 0 ) ; <nl> <nl> mmm a / modules / ocl / src / imgproc . cpp <nl> ppp b / modules / ocl / src / imgproc . cpp <nl> <nl> / / Xu Pang , pangxu010 @ 163 . com <nl> / / Wu Zailong , bullet @ yeah . net <nl> / / Wenju He , wenju @ multicorewareinc . com <nl> + / / Peng Xiao , pengxiao @ outlook . com <nl> / / <nl> / / Redistribution and use in source and binary forms , with or without modification , <nl> / / are permitted provided that the following conditions are met : <nl> namespace cv <nl> extern const char * imgproc_calcHarris ; <nl> extern const char * imgproc_calcMinEigenVal ; <nl> extern const char * imgproc_convolve ; <nl> + extern const char * imgproc_mulAndScaleSpectrums ; <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / OpenCL call wrappers / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> <nl> template < typename T > struct index_and_sizeof ; <nl> namespace cv <nl> <nl> } <nl> } <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / mulSpectrums / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + void cv : : ocl : : mulSpectrums ( const oclMat & a , const oclMat & b , oclMat & c , int / * flags * / , float scale , bool conjB ) <nl> + { <nl> + CV_Assert ( a . type ( ) = = CV_32FC2 ) ; <nl> + CV_Assert ( b . type ( ) = = CV_32FC2 ) ; <nl> + <nl> + c . create ( a . size ( ) , CV_32FC2 ) ; <nl> + <nl> + size_t lt [ 3 ] = { 16 , 16 , 1 } ; <nl> + size_t gt [ 3 ] = { a . cols , a . rows , 1 } ; <nl> + <nl> + String kernelName = conjB ? " mulAndScaleSpectrumsKernel_CONJ " : " mulAndScaleSpectrumsKernel " ; <nl> + <nl> + std : : vector < std : : pair < size_t , const void * > > args ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_mem ) , ( void * ) & a . data ) ) ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_mem ) , ( void * ) & b . data ) ) ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_float ) , ( void * ) & scale ) ) ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_mem ) , ( void * ) & c . data ) ) ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_int ) , ( void * ) & a . cols ) ) ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_int ) , ( void * ) & a . rows ) ) ; <nl> + args . push_back ( std : : make_pair ( sizeof ( cl_int ) , ( void * ) & a . step ) ) ; <nl> + <nl> + Context * clCxt = Context : : getContext ( ) ; <nl> + openCLExecuteKernel ( clCxt , & imgproc_mulAndScaleSpectrums , kernelName , gt , lt , args , - 1 , - 1 ) ; <nl> + } <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / convolve / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> inline int divUp ( int total , int grain ) <nl> { <nl> return ( total + grain - 1 ) / grain ; <nl> } <nl> + <nl> + / / ported from CUDA module <nl> + void cv : : ocl : : ConvolveBuf : : create ( Size image_size , Size templ_size ) <nl> + { <nl> + result_size = Size ( image_size . width - templ_size . width + 1 , <nl> + image_size . height - templ_size . height + 1 ) ; <nl> + <nl> + block_size = user_block_size ; <nl> + if ( user_block_size . width = = 0 | | user_block_size . height = = 0 ) <nl> + block_size = estimateBlockSize ( result_size , templ_size ) ; <nl> + <nl> + dft_size . width = 1 < < int ( ceil ( std : : log ( block_size . width + templ_size . width - 1 . ) / std : : log ( 2 . ) ) ) ; <nl> + dft_size . height = 1 < < int ( ceil ( std : : log ( block_size . height + templ_size . height - 1 . ) / std : : log ( 2 . ) ) ) ; <nl> + <nl> + / / CUFFT has hard - coded kernels for power - of - 2 sizes ( up to 8192 ) , <nl> + / / see CUDA Toolkit 4 . 1 CUFFT Library Programming Guide <nl> + / / if ( dft_size . width > 8192 ) <nl> + dft_size . width = getOptimalDFTSize ( block_size . width + templ_size . width - 1 . ) ; <nl> + / / if ( dft_size . height > 8192 ) <nl> + dft_size . height = getOptimalDFTSize ( block_size . height + templ_size . height - 1 . ) ; <nl> + <nl> + / / To avoid wasting time doing small DFTs <nl> + dft_size . width = std : : max ( dft_size . width , 512 ) ; <nl> + dft_size . height = std : : max ( dft_size . height , 512 ) ; <nl> + <nl> + image_block . create ( dft_size , CV_32F ) ; <nl> + templ_block . create ( dft_size , CV_32F ) ; <nl> + result_data . create ( dft_size , CV_32F ) ; <nl> + <nl> + / / spect_len = dft_size . height * ( dft_size . width / 2 + 1 ) ; <nl> + image_spect . create ( dft_size . height , dft_size . width / 2 + 1 , CV_32FC2 ) ; <nl> + templ_spect . create ( dft_size . height , dft_size . width / 2 + 1 , CV_32FC2 ) ; <nl> + result_spect . create ( dft_size . height , dft_size . width / 2 + 1 , CV_32FC2 ) ; <nl> + <nl> + / / Use maximum result matrix block size for the estimated DFT block size <nl> + block_size . width = std : : min ( dft_size . width - templ_size . width + 1 , result_size . width ) ; <nl> + block_size . height = std : : min ( dft_size . height - templ_size . height + 1 , result_size . height ) ; <nl> + } <nl> + <nl> + Size cv : : ocl : : ConvolveBuf : : estimateBlockSize ( Size result_size , Size / * templ_size * / ) <nl> + { <nl> + int width = ( result_size . width + 2 ) / 3 ; <nl> + int height = ( result_size . height + 2 ) / 3 ; <nl> + width = std : : min ( width , result_size . width ) ; <nl> + height = std : : min ( height , result_size . height ) ; <nl> + return Size ( width , height ) ; <nl> + } <nl> + <nl> + static void convolve_run_fft ( const oclMat & image , const oclMat & templ , oclMat & result , bool ccorr , ConvolveBuf & buf ) <nl> + { <nl> + # if defined HAVE_CLAMDFFT <nl> + CV_Assert ( image . type ( ) = = CV_32F ) ; <nl> + CV_Assert ( templ . type ( ) = = CV_32F ) ; <nl> + <nl> + buf . create ( image . size ( ) , templ . size ( ) ) ; <nl> + result . create ( buf . result_size , CV_32F ) ; <nl> + <nl> + Size & block_size = buf . block_size ; <nl> + Size & dft_size = buf . dft_size ; <nl> + <nl> + oclMat & image_block = buf . image_block ; <nl> + oclMat & templ_block = buf . templ_block ; <nl> + oclMat & result_data = buf . result_data ; <nl> + <nl> + oclMat & image_spect = buf . image_spect ; <nl> + oclMat & templ_spect = buf . templ_spect ; <nl> + oclMat & result_spect = buf . result_spect ; <nl> + <nl> + oclMat templ_roi = templ ; <nl> + copyMakeBorder ( templ_roi , templ_block , 0 , templ_block . rows - templ_roi . rows , 0 , <nl> + templ_block . cols - templ_roi . cols , 0 , Scalar ( ) ) ; <nl> + <nl> + cv : : ocl : : dft ( templ_block , templ_spect , dft_size ) ; <nl> + <nl> + / / Process all blocks of the result matrix <nl> + for ( int y = 0 ; y < result . rows ; y + = block_size . height ) <nl> + { <nl> + for ( int x = 0 ; x < result . cols ; x + = block_size . width ) <nl> + { <nl> + Size image_roi_size ( std : : min ( x + dft_size . width , image . cols ) - x , <nl> + std : : min ( y + dft_size . height , image . rows ) - y ) ; <nl> + Rect roi0 ( x , y , image_roi_size . width , image_roi_size . height ) ; <nl> + <nl> + oclMat image_roi ( image , roi0 ) ; <nl> + <nl> + copyMakeBorder ( image_roi , image_block , 0 , image_block . rows - image_roi . rows , <nl> + 0 , image_block . cols - image_roi . cols , 0 , Scalar ( ) ) ; <nl> + <nl> + cv : : ocl : : dft ( image_block , image_spect , dft_size ) ; <nl> + <nl> + mulSpectrums ( image_spect , templ_spect , result_spect , 0 , <nl> + 1 . f / dft_size . area ( ) , ccorr ) ; <nl> + <nl> + cv : : ocl : : dft ( result_spect , result_data , dft_size , cv : : DFT_INVERSE | cv : : DFT_REAL_OUTPUT ) ; <nl> + <nl> + Size result_roi_size ( std : : min ( x + block_size . width , result . cols ) - x , <nl> + std : : min ( y + block_size . height , result . rows ) - y ) ; <nl> + <nl> + Rect roi1 ( x , y , result_roi_size . width , result_roi_size . height ) ; <nl> + Rect roi2 ( 0 , 0 , result_roi_size . width , result_roi_size . height ) ; <nl> + <nl> + oclMat result_roi ( result , roi1 ) ; <nl> + oclMat result_block ( result_data , roi2 ) ; <nl> + <nl> + result_block . copyTo ( result_roi ) ; <nl> + } <nl> + } <nl> + <nl> + # else <nl> + CV_Error ( CV_StsNotImplemented , " OpenCL DFT is not implemented " ) ; <nl> + # define UNUSED ( x ) ( void ) ( x ) ; <nl> + UNUSED ( image ) UNUSED ( templ ) UNUSED ( result ) UNUSED ( ccorr ) UNUSED ( buf ) <nl> + # undef UNUSED <nl> + # endif <nl> + } <nl> static void convolve_run ( const oclMat & src , const oclMat & temp1 , oclMat & dst , String kernelName , const char * * kernelString ) <nl> { <nl> CV_Assert ( src . depth ( ) = = CV_32FC1 ) ; <nl> static void convolve_run ( const oclMat & src , const oclMat & temp1 , oclMat & dst , St <nl> <nl> openCLExecuteKernel ( clCxt , kernelString , kernelName , globalThreads , localThreads , args , - 1 , depth ) ; <nl> } <nl> - void cv : : ocl : : convolve ( const oclMat & x , const oclMat & t , oclMat & y ) <nl> + void cv : : ocl : : convolve ( const oclMat & x , const oclMat & t , oclMat & y , bool ccorr ) <nl> { <nl> CV_Assert ( x . depth ( ) = = CV_32F ) ; <nl> CV_Assert ( t . depth ( ) = = CV_32F ) ; <nl> - CV_Assert ( x . type ( ) = = y . type ( ) & & x . size ( ) = = y . size ( ) ) ; <nl> y . create ( x . size ( ) , x . type ( ) ) ; <nl> String kernelName = " convolve " ; <nl> - <nl> - convolve_run ( x , t , y , kernelName , & imgproc_convolve ) ; <nl> + if ( t . cols > 17 | | t . rows > 17 ) <nl> + { <nl> + ConvolveBuf buf ; <nl> + convolve_run_fft ( x , t , y , ccorr , buf ) ; <nl> + } <nl> + else <nl> + { <nl> + CV_Assert ( ccorr = = false ) ; <nl> + convolve_run ( x , t , y , kernelName , & imgproc_convolve ) ; <nl> + } <nl> + } <nl> + void cv : : ocl : : convolve ( const oclMat & image , const oclMat & templ , oclMat & result , bool ccorr , ConvolveBuf & buf ) <nl> + { <nl> + result . create ( image . size ( ) , image . type ( ) ) ; <nl> + convolve_run_fft ( image , templ , result , ccorr , buf ) ; <nl> } <nl> mmm a / modules / ocl / src / match_template . cpp <nl> ppp b / modules / ocl / src / match_template . cpp <nl> namespace cv <nl> / / Evaluates optimal template ' s area threshold . If <nl> / / template ' s area is less than the threshold , we use naive match <nl> / / template version , otherwise FFT - based ( if available ) <nl> - static bool useNaive ( int , int , Size ) <nl> + static bool useNaive ( int method , int depth , Size size ) <nl> { <nl> - / / FIXME ! <nl> - / / always use naive until convolve is imported <nl> + # ifdef HAVE_CLAMDFFT <nl> + if ( method = = CV_TM_SQDIFF & & ( depth = = CV_32F | | ! Context : : getContext ( ) - > supportsFeature ( Context : : CL_DOUBLE ) ) ) <nl> + { <nl> + return true ; <nl> + } <nl> + else if ( method = = CV_TM_CCORR | | ( method = = CV_TM_SQDIFF & & depth = = CV_8U ) ) <nl> + { <nl> + return size . height < 18 & & size . width < 18 ; <nl> + } <nl> + else <nl> + return false ; <nl> + # else <nl> + # define UNUSED ( x ) ( void ) ( x ) ; <nl> + UNUSED ( method ) UNUSED ( depth ) UNUSED ( size ) <nl> + # undef UNUSED <nl> return true ; <nl> + # endif <nl> } <nl> <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> namespace cv <nl> / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> / / CCORR <nl> void convolve_32F ( <nl> - const oclMat & , const oclMat & , oclMat & , MatchTemplateBuf & ) <nl> + const oclMat & image , const oclMat & templ , oclMat & result , MatchTemplateBuf & buf ) <nl> { <nl> - CV_Error ( - 1 , " convolve is not fully implemented yet " ) ; <nl> + ConvolveBuf convolve_buf ; <nl> + convolve_buf . user_block_size = buf . user_block_size ; <nl> + if ( image . oclchannels ( ) = = 1 ) <nl> + convolve ( image , templ , result , true , convolve_buf ) ; <nl> + else <nl> + { <nl> + oclMat result_ ; <nl> + convolve ( image . reshape ( 1 ) , templ . reshape ( 1 ) , result_ , true , convolve_buf ) ; <nl> + extractFirstChannel_32F ( result_ , result ) ; <nl> + } <nl> } <nl> <nl> void matchTemplate_CCORR ( <nl> new file mode 100644 <nl> index 00000000000 . . 86d4e5d5203 <nl> mmm / dev / null <nl> ppp b / modules / ocl / src / opencl / imgproc_mulAndScaleSpectrums . cl <nl> <nl> + / * M / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / <nl> + / / IMPORTANT : READ BEFORE DOWNLOADING , COPYING , INSTALLING OR USING . <nl> + / / <nl> + / / By downloading , copying , installing or using the software you agree to this license . <nl> + / / If you do not agree to this license , do not download , install , <nl> + / / copy or use the software . <nl> + / / <nl> + / / <nl> + / / License Agreement <nl> + / / For Open Source Computer Vision Library <nl> + / / <nl> + / / Copyright ( C ) 2010 - 2012 , Multicoreware , Inc . , all rights reserved . <nl> + / / Copyright ( C ) 2010 - 2012 , Advanced Micro Devices , Inc . , all rights reserved . <nl> + / / Third party copyrights are property of their respective owners . <nl> + / / <nl> + / / @ Authors <nl> + / / Peng Xiao , pengxiao @ multicorewareinc . com <nl> + / / <nl> + / / Redistribution and use in source and binary forms , with or without modification , <nl> + / / are permitted provided that the following conditions are met : <nl> + / / <nl> + / / * Redistribution ' s of source code must retain the above copyright notice , <nl> + / / this list of conditions and the following disclaimer . <nl> + / / <nl> + / / * Redistribution ' s in binary form must reproduce the above copyright notice , <nl> + / / this list of conditions and the following disclaimer in the documentation <nl> + / / and / or other oclMaterials provided with the distribution . <nl> + / / <nl> + / / * The name of the copyright holders may not be used to endorse or promote products <nl> + / / derived from this software without specific prior written permission . <nl> + / / <nl> + / / This software is provided by the copyright holders and contributors as is and <nl> + / / any express or implied warranties , including , but not limited to , the implied <nl> + / / warranties of merchantability and fitness for a particular purpose are disclaimed . <nl> + / / In no event shall the uintel Corporation or contributors be liable for any direct , <nl> + / / indirect , incidental , special , exemplary , or consequential damages <nl> + / / ( including , but not limited to , procurement of substitute goods or services ; <nl> + / / loss of use , data , or profits ; or business uinterruption ) however caused <nl> + / / and on any theory of liability , whether in contract , strict liability , <nl> + / / or tort ( including negligence or otherwise ) arising in any way out of <nl> + / / the use of this software , even if advised of the possibility of such damage . <nl> + / / <nl> + / / M * / <nl> + <nl> + typedef float2 cfloat ; <nl> + inline cfloat cmulf ( cfloat a , cfloat b ) <nl> + { <nl> + return ( cfloat ) ( a . x * b . x - a . y * b . y , a . x * b . y + a . y * b . x ) ; <nl> + } <nl> + <nl> + inline cfloat conjf ( cfloat a ) <nl> + { <nl> + return ( cfloat ) ( a . x , - a . y ) ; <nl> + } <nl> + <nl> + __kernel void <nl> + mulAndScaleSpectrumsKernel ( <nl> + __global const cfloat * a , <nl> + __global const cfloat * b , <nl> + float scale , <nl> + __global cfloat * dst , <nl> + uint cols , <nl> + uint rows , <nl> + uint mstep <nl> + ) <nl> + { <nl> + const uint x = get_global_id ( 0 ) ; <nl> + const uint y = get_global_id ( 1 ) ; <nl> + const uint idx = mad24 ( y , mstep / sizeof ( cfloat ) , x ) ; <nl> + if ( x < cols & & y < rows ) <nl> + { <nl> + cfloat v = cmulf ( a [ idx ] , b [ idx ] ) ; <nl> + dst [ idx ] = ( cfloat ) ( v . x * scale , v . y * scale ) ; <nl> + } <nl> + } <nl> + __kernel void <nl> + mulAndScaleSpectrumsKernel_CONJ ( <nl> + __global const cfloat * a , <nl> + __global const cfloat * b , <nl> + float scale , <nl> + __global cfloat * dst , <nl> + uint cols , <nl> + uint rows , <nl> + uint mstep <nl> + ) <nl> + { <nl> + const uint x = get_global_id ( 0 ) ; <nl> + const uint y = get_global_id ( 1 ) ; <nl> + const uint idx = mad24 ( y , mstep / sizeof ( cfloat ) , x ) ; <nl> + if ( x < cols & & y < rows ) <nl> + { <nl> + cfloat v = cmulf ( a [ idx ] , conjf ( b [ idx ] ) ) ; <nl> + dst [ idx ] = ( cfloat ) ( v . x * scale , v . y * scale ) ; <nl> + } <nl> + } <nl> mmm a / modules / ocl / test / test_fft . cpp <nl> ppp b / modules / ocl / test / test_fft . cpp <nl> INSTANTIATE_TEST_CASE_P ( OCL_ImgProc , Dft , testing : : Combine ( <nl> testing : : Values ( cv : : Size ( 2 , 3 ) , cv : : Size ( 5 , 4 ) , cv : : Size ( 25 , 20 ) , cv : : Size ( 512 , 1 ) , cv : : Size ( 1024 , 768 ) ) , <nl> testing : : Values ( 0 , ( int ) cv : : DFT_ROWS , ( int ) cv : : DFT_SCALE ) ) ) ; <nl> <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / MulSpectrums <nl> + <nl> + PARAM_TEST_CASE ( MulSpectrums , cv : : Size , DftFlags , bool ) <nl> + { <nl> + cv : : Size size ; <nl> + int flag ; <nl> + bool ccorr ; <nl> + cv : : Mat a , b ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + size = GET_PARAM ( 0 ) ; <nl> + flag = GET_PARAM ( 1 ) ; <nl> + ccorr = GET_PARAM ( 2 ) ; <nl> + <nl> + a = randomMat ( size , CV_32FC2 ) ; <nl> + b = randomMat ( size , CV_32FC2 ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( MulSpectrums , Simple ) <nl> + { <nl> + cv : : ocl : : oclMat c ; <nl> + cv : : ocl : : mulSpectrums ( cv : : ocl : : oclMat ( a ) , cv : : ocl : : oclMat ( b ) , c , flag , 1 . 0 , ccorr ) ; <nl> + <nl> + cv : : Mat c_gold ; <nl> + cv : : mulSpectrums ( a , b , c_gold , flag , ccorr ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( c_gold , c , 1e - 2 , " " ) ; <nl> + } <nl> + <nl> + TEST_P ( MulSpectrums , Scaled ) <nl> + { <nl> + float scale = 1 . f / size . area ( ) ; <nl> + <nl> + cv : : ocl : : oclMat c ; <nl> + cv : : ocl : : mulSpectrums ( cv : : ocl : : oclMat ( a ) , cv : : ocl : : oclMat ( b ) , c , flag , scale , ccorr ) ; <nl> + <nl> + cv : : Mat c_gold ; <nl> + cv : : mulSpectrums ( a , b , c_gold , flag , ccorr ) ; <nl> + c_gold . convertTo ( c_gold , c_gold . type ( ) , scale ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( c_gold , c , 1e - 2 , " " ) ; <nl> + } <nl> + <nl> + INSTANTIATE_TEST_CASE_P ( OCL_ImgProc , MulSpectrums , testing : : Combine ( <nl> + DIFFERENT_SIZES , <nl> + testing : : Values ( DftFlags ( 0 ) ) , <nl> + testing : : Values ( false , true ) ) ) ; <nl> + <nl> + <nl> + / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / <nl> + / / Convolve <nl> + <nl> + void static convolveDFT ( const cv : : Mat & A , const cv : : Mat & B , cv : : Mat & C , bool ccorr = false ) <nl> + { <nl> + / / reallocate the output array if needed <nl> + C . create ( std : : abs ( A . rows - B . rows ) + 1 , std : : abs ( A . cols - B . cols ) + 1 , A . type ( ) ) ; <nl> + cv : : Size dftSize ; <nl> + <nl> + / / compute the size of DFT transform <nl> + dftSize . width = cv : : getOptimalDFTSize ( A . cols + B . cols - 1 ) ; <nl> + dftSize . height = cv : : getOptimalDFTSize ( A . rows + B . rows - 1 ) ; <nl> + <nl> + / / allocate temporary buffers and initialize them with 0s <nl> + cv : : Mat tempA ( dftSize , A . type ( ) , cv : : Scalar : : all ( 0 ) ) ; <nl> + cv : : Mat tempB ( dftSize , B . type ( ) , cv : : Scalar : : all ( 0 ) ) ; <nl> + <nl> + / / copy A and B to the top - left corners of tempA and tempB , respectively <nl> + cv : : Mat roiA ( tempA , cv : : Rect ( 0 , 0 , A . cols , A . rows ) ) ; <nl> + A . copyTo ( roiA ) ; <nl> + cv : : Mat roiB ( tempB , cv : : Rect ( 0 , 0 , B . cols , B . rows ) ) ; <nl> + B . copyTo ( roiB ) ; <nl> + <nl> + / / now transform the padded A & B in - place ; <nl> + / / use " nonzeroRows " hint for faster processing <nl> + cv : : dft ( tempA , tempA , 0 , A . rows ) ; <nl> + cv : : dft ( tempB , tempB , 0 , B . rows ) ; <nl> + <nl> + / / multiply the spectrums ; <nl> + / / the function handles packed spectrum representations well <nl> + cv : : mulSpectrums ( tempA , tempB , tempA , 0 , ccorr ) ; <nl> + <nl> + / / transform the product back from the frequency domain . <nl> + / / Even though all the result rows will be non - zero , <nl> + / / you need only the first C . rows of them , and thus you <nl> + / / pass nonzeroRows = = C . rows <nl> + cv : : dft ( tempA , tempA , cv : : DFT_INVERSE + cv : : DFT_SCALE , C . rows ) ; <nl> + <nl> + / / now copy the result back to C . <nl> + tempA ( cv : : Rect ( 0 , 0 , C . cols , C . rows ) ) . copyTo ( C ) ; <nl> + } <nl> + <nl> + IMPLEMENT_PARAM_CLASS ( KSize , int ) ; <nl> + IMPLEMENT_PARAM_CLASS ( Ccorr , bool ) ; <nl> + <nl> + PARAM_TEST_CASE ( Convolve_DFT , cv : : Size , KSize , Ccorr ) <nl> + { <nl> + cv : : Size size ; <nl> + int ksize ; <nl> + bool ccorr ; <nl> + <nl> + cv : : Mat src ; <nl> + cv : : Mat kernel ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + <nl> + virtual void SetUp ( ) <nl> + { <nl> + size = GET_PARAM ( 0 ) ; <nl> + ksize = GET_PARAM ( 1 ) ; <nl> + ccorr = GET_PARAM ( 2 ) ; <nl> + } <nl> + } ; <nl> + <nl> + TEST_P ( Convolve_DFT , Accuracy ) <nl> + { <nl> + cv : : Mat src = randomMat ( size , CV_32FC1 , 0 . 0 , 100 . 0 ) ; <nl> + cv : : Mat kernel = randomMat ( cv : : Size ( ksize , ksize ) , CV_32FC1 , 0 . 0 , 1 . 0 ) ; <nl> + <nl> + cv : : ocl : : oclMat dst ; <nl> + cv : : ocl : : convolve ( cv : : ocl : : oclMat ( src ) , cv : : ocl : : oclMat ( kernel ) , dst , ccorr ) ; <nl> + <nl> + cv : : Mat dst_gold ; <nl> + convolveDFT ( src , kernel , dst_gold , ccorr ) ; <nl> + <nl> + EXPECT_MAT_NEAR ( dst , dst_gold , 1e - 1 , " " ) ; <nl> + } <nl> + # define DIFFERENT_CONVOLVE_SIZES testing : : Values ( cv : : Size ( 251 , 257 ) , cv : : Size ( 113 , 113 ) , cv : : Size ( 200 , 480 ) , cv : : Size ( 1300 , 1300 ) ) <nl> + INSTANTIATE_TEST_CASE_P ( OCL_ImgProc , Convolve_DFT , testing : : Combine ( <nl> + DIFFERENT_CONVOLVE_SIZES , <nl> + testing : : Values ( KSize ( 19 ) , KSize ( 23 ) , KSize ( 45 ) ) , <nl> + testing : : Values ( Ccorr ( true ) / * , Ccorr ( false ) * / ) ) ) ; / / false ccorr cannot pass for some instances <nl> # endif / / HAVE_CLAMDFFT <nl>
Merge pull request from pengx17 : master_matchTemplate_dft
opencv/opencv
f03c7521c69ae5dbe8f461479ff7d68420cefde0
2013-04-09T04:53:17Z
mmm a / code / bit - manipulation / convert_number_binary / README . md <nl> ppp b / code / bit - manipulation / convert_number_binary / README . md <nl> <nl> # cosmos <nl> Your personal library of every algorithm and data structure code that you will ever encounter <nl> <nl> - # # Convert number to binary <nl> + # # Package : Convert number to binary <nl> Programs in this folder are about converting numbers from ` base 10 ` ( decimal ) to ` base 2 ` ( binary ) <nl> <nl> # # # Examples : <nl> <nl> - | : Decimal : | : Binary : | <nl> mmmmmmmmmmmmmmmmmmmmmmmm - - <nl> + mmmmmmmmmmmmmmm - <nl> + | Decimal | Binary | <nl> + | : mmm : | : mmm : | <nl> | 0 | 0 | <nl> | 1 | 1 | <nl> | 2 | 10 | <nl> | 3 | 11 | <nl> | 4 | 100 | <nl> | 16 | 10000 | <nl> + mmmmmmmmmmmmmmm - <nl> <nl> # # # Main idea : <nl> Binary numbers have ` 2 ` permissible digits ` 0 ` * * and * * ` 1 ` . <nl> Let ` k ` denote the ` k ` number of bits in the binary number ` b ` . <nl> <nl> ` quot ` is the quotient function , divides left operand by right operand and provides just the quotient . <nl> <nl> mmm step 1 <nl> - ` ` ` <nl> - n ` mod ` 2 = b [ k - 1 ] <nl> - n ` quot ` 2 = n < sub > 1 < / sub > <nl> - ` ` ` <nl> + * step 1 <nl> <nl> mmm step 2 <nl> - ` ` ` <nl> - n < sub > 1 < / sub > ` mod ` 2 = b [ k - 2 ] <nl> - n < sub > 1 < / sub > ` quot ` 2 = n < sub > 2 < / sub > <nl> - ` ` ` <nl> + n ` mod ` 2 = b < sub > k - 1 < / sub > <nl> + <nl> + n ` quot ` 2 = n < sub > 1 < / sub > <nl> + <nl> + * step 2 <nl> + <nl> + n < sub > 1 < / sub > ` mod ` 2 = b < sub > k - 2 < / sub > <nl> + <nl> + n < sub > 1 < / sub > ` quot ` 2 = n < sub > 2 < / sub > <nl> <nl> . . . ( continue till final step ) <nl> <nl> mmm final step <nl> - ` ` ` <nl> - n < sub > k - 1 < / sub > ` mod ` 2 = b [ 0 ] <nl> - n < sub > k - 1 < / sub > ` quot ` 2 = 0 <nl> - ` ` ` <nl> + * final step <nl> + <nl> + n < sub > k - 1 < / sub > ` mod ` 2 = b < sub > 0 < / sub > <nl> + <nl> + n < sub > k - 1 < / sub > ` quot ` 2 = 0 <nl> + <nl> <nl> Lets walk with example of converting number ` 5 ` into a ` 8 - bit ` binary number : <nl> - ` ` ` <nl> + <nl> n = 5 , k = 8 <nl> <nl> - 5 ` mod ` 2 = 1 - - b [ 8 - 1 ] <nl> + mmm <nl> + <nl> + 5 ` mod ` 2 = 1 - - b < sub > 7 < / sub > <nl> + <nl> 5 ` quot ` 2 = 2 <nl> <nl> - 2 ` mod ` 2 = 0 - - b [ 8 - 2 ] <nl> + mmm <nl> + <nl> + 2 ` mod ` 2 = 0 - - b < sub > 6 < / sub > <nl> + <nl> 2 ` quot ` 2 = 1 <nl> <nl> - 1 ` mod ` 2 = 1 - - b [ 8 - 3 ] <nl> + mmm <nl> + <nl> + 1 ` mod ` 2 = 1 - - b < sub > 5 < / sub > <nl> + <nl> 1 ` quot ` 2 = 0 - - calc ends ( end ) , all 0s after this point <nl> <nl> - 0 ` mod ` 2 = 0 - - b [ 8 - 4 ] <nl> + mmm <nl> + <nl> + 0 ` mod ` 2 = 0 - - b < sub > 4 < / sub > <nl> + <nl> 0 ` quot ` 2 = 0 <nl> <nl> - 0 ` mod ` 2 = 0 - - b [ 8 - 5 ] <nl> + mmm <nl> + <nl> + 0 ` mod ` 2 = 0 - - b < sub > 3 < / sub > <nl> + <nl> 0 ` quot ` 2 = 0 <nl> <nl> - 0 ` mod ` 2 = 0 - - b [ 8 - 6 ] <nl> + mmm <nl> + <nl> + 0 ` mod ` 2 = 0 - - b < sub > 2 < / sub > <nl> + <nl> 0 ` quot ` 2 = 0 <nl> <nl> - 0 ` mod ` 2 = 0 - - b [ 8 - 7 ] <nl> + mmm <nl> + <nl> + 0 ` mod ` 2 = 0 - - b < sub > 1 < / sub > <nl> + <nl> 0 ` quot ` 2 = 0 <nl> <nl> - 0 ` mod ` 2 = 0 - - b [ 8 - 8 ] <nl> + mmm <nl> + <nl> + 0 ` mod ` 2 = 0 - - b < sub > 0 < / sub > <nl> + <nl> 0 ` quot ` 2 = 0 <nl> <nl> - b = [ 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 ] - - " 00000101 " <nl> - ` ` ` <nl> \ No newline at end of file <nl> + mmm <nl> + <nl> + b = [ 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 ] - - " 00000101 " <nl>
Updated Readme , improved design .
OpenGenus/cosmos
c643fdf184a7a847005eac8d9b6f57e49b2773f5
2017-10-13T02:32:16Z
mmm a / src / sqltextedit . cpp <nl> ppp b / src / sqltextedit . cpp <nl> void SqlTextEdit : : reloadSettings ( ) <nl> void SqlTextEdit : : toggleBlockComment ( ) <nl> { <nl> int lineFrom , indexFrom , lineTo , indexTo ; <nl> + <nl> / / If there is no selection , select the current line <nl> if ( ! hasSelectedText ( ) ) { <nl> getCursorPosition ( & lineFrom , & indexFrom ) ; <nl> - setSelection ( lineFrom , 0 , lineFrom , lineLength ( lineFrom ) ) ; <nl> + <nl> + / / Windows lines requires an adjustment , otherwise the selection would <nl> + / / end in the next line . <nl> + indexTo = text ( lineFrom ) . endsWith ( " \ r \ n " ) ? lineLength ( lineFrom ) - 1 : lineLength ( lineFrom ) ; <nl> + <nl> + setSelection ( lineFrom , 0 , lineFrom , indexTo ) ; <nl> } <nl> <nl> getSelection ( & lineFrom , & indexFrom , & lineTo , & indexTo ) ; <nl> <nl> bool uncomment = text ( lineFrom ) . contains ( QRegExp ( " ^ [ \ t ] * - - " ) ) ; <nl> <nl> + / / If the selection ends before the first character of a line , don ' t <nl> + / / take this line into account for un / commenting . <nl> + if ( indexTo = = 0 ) <nl> + lineTo - - ; <nl> + <nl> + beginUndoAction ( ) ; <nl> + <nl> / / Iterate over the selected lines , get line text , make <nl> / / replacement depending on whether the first line was commented <nl> - / / or uncommented , and replace the line text . <nl> - for ( int line = lineFrom ; line < lineTo ; line + + ) { <nl> + / / or uncommented , and replace the line text . All in a single undo action . <nl> + for ( int line = lineFrom ; line < = lineTo ; line + + ) { <nl> QString lineText = text ( line ) ; <nl> <nl> if ( uncomment ) <nl> void SqlTextEdit : : toggleBlockComment ( ) <nl> setSelection ( line , 0 , line , indexTo ) ; <nl> replaceSelectedText ( lineText ) ; <nl> } <nl> + endUndoAction ( ) ; <nl> } <nl>
Improvement and fixes to the un / comment block feature
sqlitebrowser/sqlitebrowser
33266b7707cc80bb077e6f4beac245d759fc48d5
2018-11-21T20:13:40Z
mmm a / x64_dbg_gui / Project / Src / Gui / CPUDisassembly . cpp <nl> ppp b / x64_dbg_gui / Project / Src / Gui / CPUDisassembly . cpp <nl> void CPUDisassembly : : setupRightClickContextMenu ( ) <nl> <nl> / / Binary - > Fill <nl> mBinaryFillAction = new QAction ( " & Fill . . . " , this ) ; <nl> + mBinaryFillAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryFillAction - > setShortcut ( QKeySequence ( " f " ) ) ; <nl> + this - > addAction ( mBinaryFillAction ) ; <nl> connect ( mBinaryFillAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryFillSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryFillAction ) ; <nl> <nl> / / Binary - > Copy <nl> mBinaryCopyAction = new QAction ( " & Copy " , this ) ; <nl> + mBinaryCopyAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryCopyAction - > setShortcut ( QKeySequence ( " c " ) ) ; <nl> + this - > addAction ( mBinaryCopyAction ) ; <nl> connect ( mBinaryCopyAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryCopySlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryCopyAction ) ; <nl> <nl> / / Binary - > Paste <nl> mBinaryPasteAction = new QAction ( " & Paste " , this ) ; <nl> + mBinaryPasteAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryPasteAction - > setShortcut ( QKeySequence ( " p " ) ) ; <nl> + this - > addAction ( mBinaryPasteAction ) ; <nl> connect ( mBinaryPasteAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryPasteAction ) ; <nl> <nl> + / / Binary - > Paste ( Ignore Size ) <nl> + mBinaryPasteIgnoreSizeAction = new QAction ( " Paste ( & Ignore Size ) " , this ) ; <nl> + mBinaryPasteIgnoreSizeAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryPasteIgnoreSizeAction - > setShortcut ( QKeySequence ( " shift + p " ) ) ; <nl> + this - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> + connect ( mBinaryPasteIgnoreSizeAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteIgnoreSizeSlot ( ) ) ) ; <nl> + mBinaryMenu - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> + <nl> / / Restore Selection <nl> mUndoSelection = new QAction ( " & Restore selection " , this ) ; <nl> mUndoSelection - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> mUndoSelection - > setShortcut ( QKeySequence ( " alt + backspace " ) ) ; <nl> this - > addAction ( mUndoSelection ) ; <nl> connect ( mUndoSelection , SIGNAL ( triggered ( ) ) , this , SLOT ( undoSelectionSlot ( ) ) ) ; <nl> - <nl> - / / Binary - > Paste ( Ignore Size ) <nl> - mBinaryPasteIgnoreSizeAction = new QAction ( " Paste ( & Ignore Size ) " , this ) ; <nl> - connect ( mBinaryPasteIgnoreSizeAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteIgnoreSizeSlot ( ) ) ) ; <nl> - mBinaryMenu - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> <nl> / / Labels <nl> mSetLabel = new QAction ( " Label " , this ) ; <nl> mmm a / x64_dbg_gui / Project / Src / Gui / CPUDump . cpp <nl> ppp b / x64_dbg_gui / Project / Src / Gui / CPUDump . cpp <nl> void CPUDump : : setupContextMenu ( ) <nl> <nl> / / Binary - > Fill <nl> mBinaryFillAction = new QAction ( " & Fill . . . " , this ) ; <nl> + mBinaryFillAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryFillAction - > setShortcut ( QKeySequence ( " f " ) ) ; <nl> + this - > addAction ( mBinaryFillAction ) ; <nl> connect ( mBinaryFillAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryFillSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryFillAction ) ; <nl> <nl> / / Binary - > Copy <nl> mBinaryCopyAction = new QAction ( " & Copy " , this ) ; <nl> + mBinaryCopyAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryCopyAction - > setShortcut ( QKeySequence ( " c " ) ) ; <nl> + this - > addAction ( mBinaryCopyAction ) ; <nl> connect ( mBinaryCopyAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryCopySlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryCopyAction ) ; <nl> <nl> / / Binary - > Paste <nl> mBinaryPasteAction = new QAction ( " & Paste " , this ) ; <nl> + mBinaryPasteAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryPasteAction - > setShortcut ( QKeySequence ( " p " ) ) ; <nl> + this - > addAction ( mBinaryPasteAction ) ; <nl> connect ( mBinaryPasteAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryPasteAction ) ; <nl> <nl> / / Binary - > Paste ( Ignore Size ) <nl> mBinaryPasteIgnoreSizeAction = new QAction ( " Paste ( & Ignore Size ) " , this ) ; <nl> + mBinaryPasteIgnoreSizeAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryPasteIgnoreSizeAction - > setShortcut ( QKeySequence ( " shift + p " ) ) ; <nl> + this - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> connect ( mBinaryPasteIgnoreSizeAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteIgnoreSizeSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> - <nl> + <nl> / / Restore Selection <nl> mUndoSelection = new QAction ( " & Restore selection " , this ) ; <nl> mUndoSelection - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> mmm a / x64_dbg_gui / Project / Src / Gui / CPUStack . cpp <nl> ppp b / x64_dbg_gui / Project / Src / Gui / CPUStack . cpp <nl> void CPUStack : : setupContextMenu ( ) <nl> <nl> / / Binary - > Fill <nl> mBinaryFillAction = new QAction ( " & Fill . . . " , this ) ; <nl> + mBinaryFillAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryFillAction - > setShortcut ( QKeySequence ( " f " ) ) ; <nl> + this - > addAction ( mBinaryFillAction ) ; <nl> connect ( mBinaryFillAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryFillSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryFillAction ) ; <nl> <nl> / / Binary - > Copy <nl> mBinaryCopyAction = new QAction ( " & Copy " , this ) ; <nl> + mBinaryCopyAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryCopyAction - > setShortcut ( QKeySequence ( " c " ) ) ; <nl> + this - > addAction ( mBinaryCopyAction ) ; <nl> connect ( mBinaryCopyAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryCopySlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryCopyAction ) ; <nl> <nl> / / Binary - > Paste <nl> mBinaryPasteAction = new QAction ( " & Paste " , this ) ; <nl> + mBinaryPasteAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryPasteAction - > setShortcut ( QKeySequence ( " p " ) ) ; <nl> + this - > addAction ( mBinaryPasteAction ) ; <nl> connect ( mBinaryPasteAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryPasteAction ) ; <nl> <nl> / / Binary - > Paste ( Ignore Size ) <nl> mBinaryPasteIgnoreSizeAction = new QAction ( " Paste ( & Ignore Size ) " , this ) ; <nl> + mBinaryPasteIgnoreSizeAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> + mBinaryPasteIgnoreSizeAction - > setShortcut ( QKeySequence ( " shift + p " ) ) ; <nl> + this - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> connect ( mBinaryPasteIgnoreSizeAction , SIGNAL ( triggered ( ) ) , this , SLOT ( binaryPasteIgnoreSizeSlot ( ) ) ) ; <nl> mBinaryMenu - > addAction ( mBinaryPasteIgnoreSizeAction ) ; <nl> <nl>
GUI : shortcuts for binary operations
x64dbg/x64dbg
c64d6766c20752a5036e5bad74b1a3c500cfd303
2014-07-06T17:58:28Z
mmm a / include / osquery / filesystem . h <nl> ppp b / include / osquery / filesystem . h <nl> Status resolveFilePattern ( const boost : : filesystem : : path & pattern , <nl> * / <nl> void replaceGlobWildcards ( std : : string & pattern ) ; <nl> <nl> - / * * <nl> - * @ brief Get directory portion of a path . <nl> - * <nl> - * @ param path input path , either a filename or directory . <nl> - * @ param dirpath output path set to the directory - only path . <nl> - * <nl> - * @ return If the input path was a directory this will indicate failure . One <nl> - * should use ` isDirectory ` before . <nl> - * / <nl> - Status getDirectory ( const boost : : filesystem : : path & path , <nl> - boost : : filesystem : : path & dirpath ) ; <nl> - <nl> / / / Attempt to remove a directory path . <nl> Status remove ( const boost : : filesystem : : path & path ) ; <nl> <nl> mmm a / osquery / events / linux / inotify . cpp <nl> ppp b / osquery / events / linux / inotify . cpp <nl> Status INotifyEventPublisher : : setUp ( ) { <nl> return Status ( 0 , " OK " ) ; <nl> } <nl> <nl> + bool INotifyEventPublisher : : monitorSubscription ( <nl> + INotifySubscriptionContextRef & sc , bool add_watch ) { <nl> + sc - > discovered_ = sc - > path ; <nl> + if ( sc - > path . find ( " * * " ) ! = std : : string : : npos ) { <nl> + sc - > recursive = true ; <nl> + sc - > discovered_ = sc - > path . substr ( 0 , sc - > path . find ( " * * " ) ) ; <nl> + sc - > path = sc - > discovered_ ; <nl> + } <nl> + <nl> + if ( sc - > path . find ( ' * ' ) ! = std : : string : : npos ) { <nl> + / / If the wildcard exists within the file ( leaf ) , remove and monitor the <nl> + / / directory instead . Apply a fnmatch on fired events to filter leafs . <nl> + auto fullpath = fs : : path ( sc - > path ) ; <nl> + if ( fullpath . filename ( ) . string ( ) . find ( ' * ' ) ! = std : : string : : npos ) { <nl> + sc - > discovered_ = fullpath . parent_path ( ) . string ( ) + ' / ' ; <nl> + } <nl> + <nl> + if ( sc - > discovered_ . find ( ' * ' ) ! = std : : string : : npos ) { <nl> + / / If a wildcard exists within the tree ( stem ) , resolve at configure <nl> + / / time and monitor each path . <nl> + std : : vector < std : : string > paths ; <nl> + resolveFilePattern ( sc - > discovered_ , paths ) ; <nl> + for ( const auto & _path : paths ) { <nl> + addMonitor ( _path , sc - > recursive , add_watch ) ; <nl> + } <nl> + sc - > recursive_match = sc - > recursive ; <nl> + return true ; <nl> + } <nl> + } <nl> + if ( isDirectory ( sc - > discovered_ ) & & sc - > discovered_ . back ( ) ! = ' / ' ) { <nl> + sc - > path + = ' / ' ; <nl> + sc - > discovered_ + = ' / ' ; <nl> + } <nl> + return addMonitor ( sc - > discovered_ , sc - > recursive , add_watch ) ; <nl> + } <nl> + <nl> void INotifyEventPublisher : : configure ( ) { <nl> for ( auto & sub : subscriptions_ ) { <nl> / / Anytime a configure is called , try to monitor all subscriptions . <nl> void INotifyEventPublisher : : configure ( ) { <nl> if ( sc - > discovered_ . size ( ) > 0 ) { <nl> continue ; <nl> } <nl> - <nl> - sc - > discovered_ = sc - > path ; <nl> - if ( sc - > path . find ( " * * " ) ! = std : : string : : npos ) { <nl> - sc - > recursive = true ; <nl> - sc - > discovered_ = sc - > path . substr ( 0 , sc - > path . find ( " * * " ) ) ; <nl> - sc - > path = sc - > discovered_ ; <nl> - } <nl> - <nl> - if ( sc - > path . find ( ' * ' ) ! = std : : string : : npos ) { <nl> - / / If the wildcard exists within the file ( leaf ) , remove and monitor the <nl> - / / directory instead . Apply a fnmatch on fired events to filter leafs . <nl> - auto fullpath = fs : : path ( sc - > path ) ; <nl> - if ( fullpath . filename ( ) . string ( ) . find ( ' * ' ) ! = std : : string : : npos ) { <nl> - sc - > discovered_ = fullpath . parent_path ( ) . string ( ) ; <nl> - } <nl> - <nl> - if ( sc - > discovered_ . find ( ' * ' ) ! = std : : string : : npos ) { <nl> - / / If a wildcard exists within the tree ( stem ) , resolve at configure <nl> - / / time and monitor each path . <nl> - std : : vector < std : : string > paths ; <nl> - resolveFilePattern ( sc - > discovered_ , paths ) ; <nl> - for ( const auto & _path : paths ) { <nl> - addMonitor ( _path , sc - > recursive ) ; <nl> - } <nl> - sc - > recursive_match = sc - > recursive ; <nl> - continue ; <nl> - } <nl> - } <nl> - addMonitor ( sc - > discovered_ , sc - > recursive ) ; <nl> + monitorSubscription ( sc ) ; <nl> } <nl> } <nl> <nl> bool INotifyEventPublisher : : shouldFire ( const INotifySubscriptionContextRef & sc , <nl> if ( found ! = 0 ) { <nl> return false ; <nl> } <nl> + } else if ( ec - > path = = sc - > path ) { <nl> + return true ; <nl> } else if ( fnmatch ( ( sc - > path + " * " ) . c_str ( ) , <nl> ec - > path . c_str ( ) , <nl> FNM_PATHNAME | FNM_CASEFOLD | <nl> bool INotifyEventPublisher : : shouldFire ( const INotifySubscriptionContextRef & sc , <nl> } <nl> <nl> bool INotifyEventPublisher : : addMonitor ( const std : : string & path , <nl> - bool recursive ) { <nl> + bool recursive , <nl> + bool add_watch ) { <nl> if ( ! isPathMonitored ( path ) ) { <nl> int watch = <nl> : : inotify_add_watch ( getHandle ( ) , <nl> path . c_str ( ) , <nl> ( IN_MODIFY | IN_ATTRIB | IN_MOVE | IN_CREATE | <nl> IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF ) ) ; <nl> - if ( watch = = - 1 ) { <nl> + if ( add_watch & & watch = = - 1 ) { <nl> LOG ( WARNING ) < < " Could not add inotify watch on : " < < path ; <nl> return false ; <nl> } <nl> bool INotifyEventPublisher : : removeMonitor ( int watch , bool force ) { <nl> } <nl> <nl> bool INotifyEventPublisher : : isPathMonitored ( const std : : string & path ) { <nl> - boost : : filesystem : : path parent_path ; <nl> + std : : string parent_path ; <nl> if ( ! isDirectory ( path ) . ok ( ) ) { <nl> if ( path_descriptors_ . find ( path ) ! = path_descriptors_ . end ( ) ) { <nl> / / Path is a file , and is directly monitored . <nl> return true ; <nl> } <nl> - if ( ! getDirectory ( path , parent_path ) . ok ( ) ) { <nl> - / / Could not get parent of unmonitored file . <nl> - return false ; <nl> - } <nl> + / / Important to add a trailing " / " for inotify . <nl> + parent_path = fs : : path ( path ) . parent_path ( ) . string ( ) + ' / ' ; <nl> } else { <nl> parent_path = path ; <nl> } <nl> - <nl> / / Directory or parent of file monitoring <nl> - auto path_iterator = path_descriptors_ . find ( parent_path . string ( ) ) ; <nl> + auto path_iterator = path_descriptors_ . find ( parent_path ) ; <nl> return ( path_iterator ! = path_descriptors_ . end ( ) ) ; <nl> } <nl> } <nl> mmm a / osquery / events / linux / inotify . h <nl> ppp b / osquery / events / linux / inotify . h <nl> class INotifyEventPublisher <nl> / / / Check all added Subscription % s for a path . <nl> bool isPathMonitored ( const std : : string & path ) ; <nl> <nl> - / / / Add an INotify watch ( monitor ) on this path . <nl> - bool addMonitor ( const std : : string & path , bool recursive ) ; <nl> + / * * <nl> + * @ brief Add an INotify watch ( monitor ) on this path . <nl> + * <nl> + * Check if a given path is already monitored ( perhaps the parent path ) has <nl> + * and existing monitor and this is a non - directory leaf ? On success the <nl> + * file descriptor is stored for lookup when events fire . <nl> + * <nl> + * A recursive flag will tell addMonitor to enumerate all subdirectories <nl> + * recursively and add monitors to them . <nl> + * <nl> + * @ param path complete ( non - glob ) canonical path to monitor . <nl> + * @ param recursive perform a single recursive search of subdirectories . <nl> + * @ param add_watch ( testing only ) should an inotify watch be created . <nl> + * @ return success if the inotify watch was created . <nl> + * / <nl> + bool addMonitor ( const std : : string & path , <nl> + bool recursive , <nl> + bool add_watch = true ) ; <nl> + <nl> + / / / Helper method to parse a subscription and add an equivalent monitor . <nl> + bool monitorSubscription ( INotifySubscriptionContextRef & sc , <nl> + bool add_watch = true ) ; <nl> <nl> / / / Remove an INotify watch ( monitor ) from our tracking . <nl> bool removeMonitor ( const std : : string & path , bool force = false ) ; <nl> class INotifyEventPublisher <nl> int getHandle ( ) { return inotify_handle_ ; } <nl> <nl> / / / Get the number of actual INotify active descriptors . <nl> - int numDescriptors ( ) { return descriptors_ . size ( ) ; } <nl> + size_t numDescriptors ( ) { return descriptors_ . size ( ) ; } <nl> <nl> / / / If we overflow , try and restart the monitor <nl> Status restartMonitoring ( ) ; <nl> class INotifyEventPublisher <nl> friend class INotifyTests ; <nl> FRIEND_TEST ( INotifyTests , test_inotify_optimization ) ; <nl> FRIEND_TEST ( INotifyTests , test_inotify_recursion ) ; <nl> + FRIEND_TEST ( INotifyTests , test_inotify_match_subscription ) ; <nl> } ; <nl> } <nl> mmm a / osquery / events / linux / tests / inotify_tests . cpp <nl> ppp b / osquery / events / linux / tests / inotify_tests . cpp <nl> TEST_F ( INotifyTests , test_inotify_add_subscription_success ) { <nl> EventFactory : : deregisterEventPublisher ( " inotify " ) ; <nl> } <nl> <nl> + TEST_F ( INotifyTests , test_inotify_match_subscription ) { <nl> + auto pub = std : : make_shared < INotifyEventPublisher > ( ) ; <nl> + pub - > addMonitor ( " / etc " , false , false ) ; <nl> + EXPECT_EQ ( pub - > path_descriptors_ . count ( " / etc " ) , 1U ) ; <nl> + / / This will fail because there is no trailing " / " at the end . <nl> + / / The configure component should take care of these paths . <nl> + EXPECT_FALSE ( pub - > isPathMonitored ( " / etc / passwd " ) ) ; <nl> + pub - > path_descriptors_ . clear ( ) ; <nl> + <nl> + / / Calling addMonitor the correct way . <nl> + pub - > addMonitor ( " / etc / " , false , false ) ; <nl> + EXPECT_TRUE ( pub - > isPathMonitored ( " / etc / passwd " ) ) ; <nl> + pub - > path_descriptors_ . clear ( ) ; <nl> + <nl> + / / Test the matching capability . <nl> + { <nl> + auto sc = pub - > createSubscriptionContext ( ) ; <nl> + sc - > path = " / etc " ; <nl> + pub - > monitorSubscription ( sc , false ) ; <nl> + EXPECT_EQ ( sc - > path , " / etc / " ) ; <nl> + EXPECT_TRUE ( pub - > isPathMonitored ( " / etc / " ) ) ; <nl> + EXPECT_TRUE ( pub - > isPathMonitored ( " / etc / passwd " ) ) ; <nl> + } <nl> + <nl> + std : : vector < std : : string > valid_dirs = { " / etc " , " / etc / " , " / etc / * " } ; <nl> + for ( const auto & dir : valid_dirs ) { <nl> + pub - > path_descriptors_ . clear ( ) ; <nl> + auto sc = pub - > createSubscriptionContext ( ) ; <nl> + sc - > path = dir ; <nl> + pub - > monitorSubscription ( sc , false ) ; <nl> + auto ec = pub - > createEventContext ( ) ; <nl> + ec - > path = " / etc / " ; <nl> + EXPECT_TRUE ( pub - > shouldFire ( sc , ec ) ) ; <nl> + ec - > path = " / etc / passwd " ; <nl> + EXPECT_TRUE ( pub - > shouldFire ( sc , ec ) ) ; <nl> + } <nl> + } <nl> + <nl> class TestINotifyEventSubscriber <nl> : public EventSubscriber < INotifyEventPublisher > { <nl> public : <nl> TEST_F ( INotifyTests , test_inotify_event_action ) { <nl> sub - > subscribe ( & TestINotifyEventSubscriber : : Callback , sc , nullptr ) ; <nl> <nl> TriggerEvent ( real_test_path ) ; <nl> - sub - > WaitForEvents ( kMaxEventLatency , 3 ) ; <nl> + sub - > WaitForEvents ( kMaxEventLatency , 2 ) ; <nl> <nl> / / Make sure the inotify action was expected . <nl> EXPECT_GT ( sub - > actions ( ) . size ( ) , 0U ) ; <nl> TEST_F ( INotifyTests , test_inotify_optimization ) { <nl> / / Adding a subscription to a file within a monitored directory is fine <nl> / / but this will NOT cause an additional INotify watch . <nl> SubscriptionAction ( real_test_dir_path ) ; <nl> - EXPECT_EQ ( event_pub_ - > numDescriptors ( ) , 1 ) ; <nl> + EXPECT_EQ ( event_pub_ - > numDescriptors ( ) , 1U ) ; <nl> StopEventLoop ( ) ; <nl> } <nl> <nl> TEST_F ( INotifyTests , test_inotify_recursion ) { <nl> pub - > configure ( ) ; <nl> / / Expect a single monitor on the root of the fake tree . <nl> EXPECT_EQ ( pub - > path_descriptors_ . size ( ) , 1U ) ; <nl> - EXPECT_EQ ( pub - > path_descriptors_ . count ( kFakeDirectory ) , 1U ) ; <nl> + EXPECT_EQ ( pub - > path_descriptors_ . count ( kFakeDirectory + " / " ) , 1U ) ; <nl> RemoveAll ( pub ) ; <nl> <nl> / / Make sure monitors are empty . <nl> - EXPECT_EQ ( pub - > numDescriptors ( ) , 0 ) ; <nl> + EXPECT_EQ ( pub - > numDescriptors ( ) , 0U ) ; <nl> <nl> auto sc2 = sub - > createSubscriptionContext ( ) ; <nl> sc2 - > path = kFakeDirectory + " / * * " ; <nl> mmm a / osquery / filesystem / filesystem . cpp <nl> ppp b / osquery / filesystem / filesystem . cpp <nl> Status listDirectoriesInDirectory ( const fs : : path & path , <nl> ( path / ( ( recursive ) ? " * * " : " * " ) ) , results , GLOB_FOLDERS ) ; <nl> } <nl> <nl> - Status getDirectory ( const fs : : path & path , fs : : path & dirpath ) { <nl> - if ( ! isDirectory ( path ) . ok ( ) ) { <nl> - dirpath = fs : : path ( path ) . parent_path ( ) . string ( ) ; <nl> - return Status ( 0 , " OK " ) ; <nl> - } <nl> - dirpath = path ; <nl> - return Status ( 1 , " Path is a directory : " + path . string ( ) ) ; <nl> - } <nl> - <nl> Status isDirectory ( const fs : : path & path ) { <nl> boost : : system : : error_code ec ; <nl> if ( fs : : is_directory ( path , ec ) ) { <nl>
Merge pull request from theopolis / inotify_more
osquery/osquery
d1d8ab7829d52d01c2689de03a177c66cb3f8ef3
2015-11-04T22:05:58Z
mmm a / externals / httplib / httplib . h <nl> ppp b / externals / httplib / httplib . h <nl> <nl> / / <nl> / / httplib . h <nl> / / <nl> - / / Copyright ( c ) 2017 Yuji Hirose . All rights reserved . <nl> + / / Copyright ( c ) 2019 Yuji Hirose . All rights reserved . <nl> / / MIT License <nl> / / <nl> <nl> - # ifndef _CPPHTTPLIB_HTTPLIB_H_ <nl> - # define _CPPHTTPLIB_HTTPLIB_H_ <nl> + # ifndef CPPHTTPLIB_HTTPLIB_H <nl> + # define CPPHTTPLIB_HTTPLIB_H <nl> + <nl> + / * <nl> + * Configuration <nl> + * / <nl> + # ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND <nl> + # define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND <nl> + # define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT <nl> + # define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND <nl> + # define CPPHTTPLIB_READ_TIMEOUT_SECOND 5 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND <nl> + # define CPPHTTPLIB_READ_TIMEOUT_USECOND 0 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH <nl> + # define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT <nl> + # define CPPHTTPLIB_REDIRECT_MAX_COUNT 20 <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH <nl> + # define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ( std : : numeric_limits < size_t > : : max ) ( ) <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_RECV_BUFSIZ <nl> + # define CPPHTTPLIB_RECV_BUFSIZ size_t ( 4096u ) <nl> + # endif <nl> + <nl> + # ifndef CPPHTTPLIB_THREAD_POOL_COUNT <nl> + # define CPPHTTPLIB_THREAD_POOL_COUNT 8 <nl> + # endif <nl> <nl> # ifdef _WIN32 <nl> # ifndef _CRT_SECURE_NO_WARNINGS <nl> # define _CRT_SECURE_NO_WARNINGS <nl> - # endif <nl> + # endif / / _CRT_SECURE_NO_WARNINGS <nl> + <nl> # ifndef _CRT_NONSTDC_NO_DEPRECATE <nl> # define _CRT_NONSTDC_NO_DEPRECATE <nl> + # endif / / _CRT_NONSTDC_NO_DEPRECATE <nl> + <nl> + # if defined ( _MSC_VER ) <nl> + # ifdef _WIN64 <nl> + typedef __int64 ssize_t ; <nl> + # else <nl> + typedef int ssize_t ; <nl> # endif <nl> <nl> - # if defined ( _MSC_VER ) & & _MSC_VER < 1900 <nl> + # if _MSC_VER < 1900 <nl> # define snprintf _snprintf_s <nl> # endif <nl> + # endif / / _MSC_VER <nl> <nl> # ifndef S_ISREG <nl> - # define S_ISREG ( m ) ( ( ( m ) & S_IFREG ) = = S_IFREG ) <nl> - # endif <nl> + # define S_ISREG ( m ) ( ( ( m ) & S_IFREG ) = = S_IFREG ) <nl> + # endif / / S_ISREG <nl> + <nl> # ifndef S_ISDIR <nl> - # define S_ISDIR ( m ) ( ( ( m ) & S_IFDIR ) = = S_IFDIR ) <nl> - # endif <nl> + # define S_ISDIR ( m ) ( ( ( m ) & S_IFDIR ) = = S_IFDIR ) <nl> + # endif / / S_ISDIR <nl> + <nl> + # ifndef NOMINMAX <nl> + # define NOMINMAX <nl> + # endif / / NOMINMAX <nl> <nl> # include < io . h > <nl> # include < winsock2 . h > <nl> # include < ws2tcpip . h > <nl> <nl> - # undef min <nl> - # undef max <nl> + # ifndef WSA_FLAG_NO_HANDLE_INHERIT <nl> + # define WSA_FLAG_NO_HANDLE_INHERIT 0x80 <nl> + # endif <nl> + <nl> + # ifdef _MSC_VER <nl> + # pragma comment ( lib , " ws2_32 . lib " ) <nl> + # endif <nl> <nl> # ifndef strcasecmp <nl> # define strcasecmp _stricmp <nl> - # endif <nl> + # endif / / strcasecmp <nl> <nl> typedef SOCKET socket_t ; <nl> - # else <nl> - # include < pthread . h > <nl> - # include < unistd . h > <nl> - # include < netdb . h > <nl> + # ifdef CPPHTTPLIB_USE_POLL <nl> + # define poll ( fds , nfds , timeout ) WSAPoll ( fds , nfds , timeout ) <nl> + # endif <nl> + <nl> + # else / / not _WIN32 <nl> + <nl> + # include < arpa / inet . h > <nl> # include < cstring > <nl> + # include < netdb . h > <nl> # include < netinet / in . h > <nl> - # include < arpa / inet . h > <nl> + # ifdef CPPHTTPLIB_USE_POLL <nl> + # include < poll . h > <nl> + # endif <nl> + # include < pthread . h > <nl> # include < signal . h > <nl> - # include < sys / socket . h > <nl> # include < sys / select . h > <nl> + # include < sys / socket . h > <nl> + # include < unistd . h > <nl> <nl> typedef int socket_t ; <nl> # define INVALID_SOCKET ( - 1 ) <nl> - # endif <nl> + # endif / / _WIN32 <nl> <nl> + # include < assert . h > <nl> + # include < atomic > <nl> + # include < condition_variable > <nl> + # include < errno . h > <nl> + # include < fcntl . h > <nl> # include < fstream > <nl> # include < functional > <nl> + # include < list > <nl> # include < map > <nl> # include < memory > <nl> # include < mutex > <nl> + # include < random > <nl> # include < regex > <nl> # include < string > <nl> - # include < thread > <nl> # include < sys / stat . h > <nl> - # include < fcntl . h > <nl> - # include < assert . h > <nl> + # include < thread > <nl> <nl> # ifdef CPPHTTPLIB_OPENSSL_SUPPORT <nl> + # include < openssl / err . h > <nl> # include < openssl / ssl . h > <nl> + # include < openssl / x509v3 . h > <nl> + <nl> + / / # if OPENSSL_VERSION_NUMBER < 0x1010100fL <nl> + / / # error Sorry , OpenSSL versions prior to 1 . 1 . 1 are not supported <nl> + / / # endif <nl> + <nl> + # if OPENSSL_VERSION_NUMBER < 0x10100000L <nl> + # include < openssl / crypto . h > <nl> + inline const unsigned char * ASN1_STRING_get0_data ( const ASN1_STRING * asn1 ) { <nl> + return M_ASN1_STRING_data ( asn1 ) ; <nl> + } <nl> + # endif <nl> # endif <nl> <nl> # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> # include < zlib . h > <nl> # endif <nl> <nl> - / * <nl> - * Configuration <nl> - * / <nl> - # define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 <nl> - # define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0 <nl> - <nl> - namespace httplib <nl> - { <nl> + namespace httplib { <nl> <nl> namespace detail { <nl> <nl> struct ci { <nl> - bool operator ( ) ( const std : : string & s1 , const std : : string & s2 ) const { <nl> - return std : : lexicographical_compare ( <nl> - s1 . begin ( ) , s1 . end ( ) , <nl> - s2 . begin ( ) , s2 . end ( ) , <nl> - [ ] ( char c1 , char c2 ) { <nl> - return : : tolower ( c1 ) < : : tolower ( c2 ) ; <nl> - } ) ; <nl> - } <nl> + bool operator ( ) ( const std : : string & s1 , const std : : string & s2 ) const { <nl> + return std : : lexicographical_compare ( <nl> + s1 . begin ( ) , s1 . end ( ) , s2 . begin ( ) , s2 . end ( ) , <nl> + [ ] ( char c1 , char c2 ) { return : : tolower ( c1 ) < : : tolower ( c2 ) ; } ) ; <nl> + } <nl> } ; <nl> <nl> } / / namespace detail <nl> <nl> enum class HttpVersion { v1_0 = 0 , v1_1 } ; <nl> <nl> - typedef std : : multimap < std : : string , std : : string , detail : : ci > Headers ; <nl> + typedef std : : multimap < std : : string , std : : string , detail : : ci > Headers ; <nl> + <nl> + typedef std : : multimap < std : : string , std : : string > Params ; <nl> + typedef std : : smatch Match ; <nl> + <nl> + typedef std : : function < void ( const char * data , size_t data_len ) > DataSink ; <nl> <nl> - template < typename uint64_t , typename . . . Args > <nl> - std : : pair < std : : string , std : : string > make_range_header ( uint64_t value , Args . . . args ) ; <nl> + typedef std : : function < void ( ) > Done ; <nl> <nl> - typedef std : : multimap < std : : string , std : : string > Params ; <nl> - typedef std : : smatch Match ; <nl> - typedef std : : function < void ( uint64_t current , uint64_t total ) > Progress ; <nl> + typedef std : : function < void ( size_t offset , size_t length , DataSink sink , <nl> + Done done ) > <nl> + ContentProvider ; <nl> + <nl> + typedef std : : function < bool ( const char * data , size_t data_length , size_t offset , <nl> + uint64_t content_length ) > <nl> + ContentReceiver ; <nl> + <nl> + typedef std : : function < bool ( uint64_t current , uint64_t total ) > Progress ; <nl> + <nl> + struct Response ; <nl> + typedef std : : function < bool ( const Response & response ) > ResponseHandler ; <nl> <nl> struct MultipartFile { <nl> - std : : string filename ; <nl> - std : : string content_type ; <nl> - size_t offset = 0 ; <nl> - size_t length = 0 ; <nl> + std : : string filename ; <nl> + std : : string content_type ; <nl> + size_t offset = 0 ; <nl> + size_t length = 0 ; <nl> } ; <nl> typedef std : : multimap < std : : string , MultipartFile > MultipartFiles ; <nl> <nl> + struct MultipartFormData { <nl> + std : : string name ; <nl> + std : : string content ; <nl> + std : : string filename ; <nl> + std : : string content_type ; <nl> + } ; <nl> + typedef std : : vector < MultipartFormData > MultipartFormDataItems ; <nl> + <nl> + typedef std : : pair < ssize_t , ssize_t > Range ; <nl> + typedef std : : vector < Range > Ranges ; <nl> + <nl> struct Request { <nl> - std : : string version ; <nl> - std : : string method ; <nl> - std : : string target ; <nl> - std : : string path ; <nl> - Headers headers ; <nl> - std : : string body ; <nl> - Params params ; <nl> - MultipartFiles files ; <nl> - Match matches ; <nl> - <nl> - Progress progress ; <nl> - <nl> - bool has_header ( const char * key ) const ; <nl> - std : : string get_header_value ( const char * key ) const ; <nl> - void set_header ( const char * key , const char * val ) ; <nl> - <nl> - bool has_param ( const char * key ) const ; <nl> - std : : string get_param_value ( const char * key ) const ; <nl> - <nl> - bool has_file ( const char * key ) const ; <nl> - MultipartFile get_file_value ( const char * key ) const ; <nl> + std : : string method ; <nl> + std : : string path ; <nl> + Headers headers ; <nl> + std : : string body ; <nl> + <nl> + / / for server <nl> + std : : string version ; <nl> + std : : string target ; <nl> + Params params ; <nl> + MultipartFiles files ; <nl> + Ranges ranges ; <nl> + Match matches ; <nl> + <nl> + / / for client <nl> + size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT ; <nl> + ResponseHandler response_handler ; <nl> + ContentReceiver content_receiver ; <nl> + Progress progress ; <nl> + <nl> + # ifdef CPPHTTPLIB_OPENSSL_SUPPORT <nl> + const SSL * ssl ; <nl> + # endif <nl> + <nl> + bool has_header ( const char * key ) const ; <nl> + std : : string get_header_value ( const char * key , size_t id = 0 ) const ; <nl> + size_t get_header_value_count ( const char * key ) const ; <nl> + void set_header ( const char * key , const char * val ) ; <nl> + void set_header ( const char * key , const std : : string & val ) ; <nl> + <nl> + bool has_param ( const char * key ) const ; <nl> + std : : string get_param_value ( const char * key , size_t id = 0 ) const ; <nl> + size_t get_param_value_count ( const char * key ) const ; <nl> + <nl> + bool has_file ( const char * key ) const ; <nl> + MultipartFile get_file_value ( const char * key ) const ; <nl> } ; <nl> <nl> struct Response { <nl> - std : : string version ; <nl> - int status ; <nl> - Headers headers ; <nl> - std : : string body ; <nl> + std : : string version ; <nl> + int status ; <nl> + Headers headers ; <nl> + std : : string body ; <nl> + <nl> + bool has_header ( const char * key ) const ; <nl> + std : : string get_header_value ( const char * key , size_t id = 0 ) const ; <nl> + size_t get_header_value_count ( const char * key ) const ; <nl> + void set_header ( const char * key , const char * val ) ; <nl> + void set_header ( const char * key , const std : : string & val ) ; <nl> + <nl> + void set_redirect ( const char * uri ) ; <nl> + void set_content ( const char * s , size_t n , const char * content_type ) ; <nl> + void set_content ( const std : : string & s , const char * content_type ) ; <nl> + <nl> + void set_content_provider ( <nl> + size_t length , <nl> + std : : function < void ( size_t offset , size_t length , DataSink sink ) > provider , <nl> + std : : function < void ( ) > resource_releaser = [ ] { } ) ; <nl> <nl> - bool has_header ( const char * key ) const ; <nl> - std : : string get_header_value ( const char * key ) const ; <nl> - void set_header ( const char * key , const char * val ) ; <nl> + void set_chunked_content_provider ( <nl> + std : : function < void ( size_t offset , DataSink sink , Done done ) > provider , <nl> + std : : function < void ( ) > resource_releaser = [ ] { } ) ; <nl> <nl> - void set_redirect ( const char * uri ) ; <nl> - void set_content ( const char * s , size_t n , const char * content_type ) ; <nl> - void set_content ( const std : : string & s , const char * content_type ) ; <nl> + Response ( ) : status ( - 1 ) , content_provider_resource_length ( 0 ) { } <nl> <nl> - Response ( ) : status ( - 1 ) { } <nl> + ~ Response ( ) { <nl> + if ( content_provider_resource_releaser ) { <nl> + content_provider_resource_releaser ( ) ; <nl> + } <nl> + } <nl> + <nl> + size_t content_provider_resource_length ; <nl> + ContentProvider content_provider ; <nl> + std : : function < void ( ) > content_provider_resource_releaser ; <nl> } ; <nl> <nl> class Stream { <nl> public : <nl> - virtual ~ Stream ( ) { } <nl> - virtual int read ( char * ptr , size_t size ) = 0 ; <nl> - virtual int write ( const char * ptr , size_t size1 ) = 0 ; <nl> - virtual int write ( const char * ptr ) = 0 ; <nl> - virtual std : : string get_remote_addr ( ) = 0 ; <nl> - <nl> - template < typename . . . Args > <nl> - void write_format ( const char * fmt , const Args & . . . args ) ; <nl> + virtual ~ Stream ( ) { } <nl> + virtual int read ( char * ptr , size_t size ) = 0 ; <nl> + virtual int write ( const char * ptr , size_t size1 ) = 0 ; <nl> + virtual int write ( const char * ptr ) = 0 ; <nl> + virtual int write ( const std : : string & s ) = 0 ; <nl> + virtual std : : string get_remote_addr ( ) const = 0 ; <nl> + <nl> + template < typename . . . Args > <nl> + int write_format ( const char * fmt , const Args & . . . args ) ; <nl> } ; <nl> <nl> class SocketStream : public Stream { <nl> public : <nl> - SocketStream ( socket_t sock ) ; <nl> - virtual ~ SocketStream ( ) ; <nl> + SocketStream ( socket_t sock ) ; <nl> + virtual ~ SocketStream ( ) ; <nl> + <nl> + virtual int read ( char * ptr , size_t size ) ; <nl> + virtual int write ( const char * ptr , size_t size ) ; <nl> + virtual int write ( const char * ptr ) ; <nl> + virtual int write ( const std : : string & s ) ; <nl> + virtual std : : string get_remote_addr ( ) const ; <nl> + <nl> + private : <nl> + socket_t sock_ ; <nl> + } ; <nl> + <nl> + class BufferStream : public Stream { <nl> + public : <nl> + BufferStream ( ) { } <nl> + virtual ~ BufferStream ( ) { } <nl> + <nl> + virtual int read ( char * ptr , size_t size ) ; <nl> + virtual int write ( const char * ptr , size_t size ) ; <nl> + virtual int write ( const char * ptr ) ; <nl> + virtual int write ( const std : : string & s ) ; <nl> + virtual std : : string get_remote_addr ( ) const ; <nl> + <nl> + const std : : string & get_buffer ( ) const ; <nl> + <nl> + private : <nl> + std : : string buffer ; <nl> + } ; <nl> + <nl> + class TaskQueue { <nl> + public : <nl> + TaskQueue ( ) { } <nl> + virtual ~ TaskQueue ( ) { } <nl> + virtual void enqueue ( std : : function < void ( ) > fn ) = 0 ; <nl> + virtual void shutdown ( ) = 0 ; <nl> + } ; <nl> + <nl> + # if CPPHTTPLIB_THREAD_POOL_COUNT > 0 <nl> + class ThreadPool : public TaskQueue { <nl> + public : <nl> + ThreadPool ( size_t n ) : shutdown_ ( false ) { <nl> + while ( n ) { <nl> + auto t = std : : make_shared < std : : thread > ( worker ( * this ) ) ; <nl> + threads_ . push_back ( t ) ; <nl> + n - - ; <nl> + } <nl> + } <nl> + <nl> + ThreadPool ( const ThreadPool & ) = delete ; <nl> + virtual ~ ThreadPool ( ) { } <nl> + <nl> + virtual void enqueue ( std : : function < void ( ) > fn ) override { <nl> + std : : unique_lock < std : : mutex > lock ( mutex_ ) ; <nl> + jobs_ . push_back ( fn ) ; <nl> + cond_ . notify_one ( ) ; <nl> + } <nl> + <nl> + virtual void shutdown ( ) override { <nl> + / / Stop all worker threads . . . <nl> + { <nl> + std : : unique_lock < std : : mutex > lock ( mutex_ ) ; <nl> + shutdown_ = true ; <nl> + } <nl> + <nl> + cond_ . notify_all ( ) ; <nl> + <nl> + / / Join . . . <nl> + for ( auto t : threads_ ) { <nl> + t - > join ( ) ; <nl> + } <nl> + } <nl> + <nl> + private : <nl> + struct worker { <nl> + worker ( ThreadPool & pool ) : pool_ ( pool ) { } <nl> + <nl> + void operator ( ) ( ) { <nl> + for ( ; ; ) { <nl> + std : : function < void ( ) > fn ; <nl> + { <nl> + std : : unique_lock < std : : mutex > lock ( pool_ . mutex_ ) ; <nl> + <nl> + pool_ . cond_ . wait ( <nl> + lock , [ & ] { return ! pool_ . jobs_ . empty ( ) | | pool_ . shutdown_ ; } ) ; <nl> + <nl> + if ( pool_ . shutdown_ & & pool_ . jobs_ . empty ( ) ) { break ; } <nl> + <nl> + fn = pool_ . jobs_ . front ( ) ; <nl> + pool_ . jobs_ . pop_front ( ) ; <nl> + } <nl> + <nl> + assert ( true = = static_cast < bool > ( fn ) ) ; <nl> + fn ( ) ; <nl> + } <nl> + } <nl> + <nl> + ThreadPool & pool_ ; <nl> + } ; <nl> + friend struct worker ; <nl> + <nl> + std : : vector < std : : shared_ptr < std : : thread > > threads_ ; <nl> + std : : list < std : : function < void ( ) > > jobs_ ; <nl> + <nl> + bool shutdown_ ; <nl> + <nl> + std : : condition_variable cond_ ; <nl> + std : : mutex mutex_ ; <nl> + } ; <nl> + # else <nl> + class Threads : public TaskQueue { <nl> + public : <nl> + Threads ( ) : running_threads_ ( 0 ) { } <nl> + virtual ~ Threads ( ) { } <nl> + <nl> + virtual void enqueue ( std : : function < void ( ) > fn ) override { <nl> + std : : thread ( [ = ] ( ) { <nl> + { <nl> + std : : lock_guard < std : : mutex > guard ( running_threads_mutex_ ) ; <nl> + running_threads_ + + ; <nl> + } <nl> + <nl> + fn ( ) ; <nl> <nl> - virtual int read ( char * ptr , size_t size ) ; <nl> - virtual int write ( const char * ptr , size_t size ) ; <nl> - virtual int write ( const char * ptr ) ; <nl> - virtual std : : string get_remote_addr ( ) ; <nl> + { <nl> + std : : lock_guard < std : : mutex > guard ( running_threads_mutex_ ) ; <nl> + running_threads_ - - ; <nl> + } <nl> + } ) . detach ( ) ; <nl> + } <nl> + <nl> + virtual void shutdown ( ) override { <nl> + for ( ; ; ) { <nl> + std : : this_thread : : sleep_for ( std : : chrono : : milliseconds ( 10 ) ) ; <nl> + std : : lock_guard < std : : mutex > guard ( running_threads_mutex_ ) ; <nl> + if ( ! running_threads_ ) { break ; } <nl> + } <nl> + } <nl> <nl> private : <nl> - socket_t sock_ ; <nl> + std : : mutex running_threads_mutex_ ; <nl> + int running_threads_ ; <nl> } ; <nl> + # endif <nl> <nl> class Server { <nl> public : <nl> - typedef std : : function < void ( const Request & , Response & ) > Handler ; <nl> - typedef std : : function < void ( const Request & , const Response & ) > Logger ; <nl> + typedef std : : function < void ( const Request & , Response & ) > Handler ; <nl> + typedef std : : function < void ( const Request & , const Response & ) > Logger ; <nl> + <nl> + Server ( ) ; <nl> <nl> - Server ( ) ; <nl> + virtual ~ Server ( ) ; <nl> <nl> - virtual ~ Server ( ) ; <nl> + virtual bool is_valid ( ) const ; <nl> <nl> - virtual bool is_valid ( ) const ; <nl> + Server & Get ( const char * pattern , Handler handler ) ; <nl> + Server & Post ( const char * pattern , Handler handler ) ; <nl> <nl> - Server & Get ( const char * pattern , Handler handler ) ; <nl> - Server & Post ( const char * pattern , Handler handler ) ; <nl> + Server & Put ( const char * pattern , Handler handler ) ; <nl> + Server & Patch ( const char * pattern , Handler handler ) ; <nl> + Server & Delete ( const char * pattern , Handler handler ) ; <nl> + Server & Options ( const char * pattern , Handler handler ) ; <nl> <nl> - Server & Put ( const char * pattern , Handler handler ) ; <nl> - Server & Delete ( const char * pattern , Handler handler ) ; <nl> - Server & Options ( const char * pattern , Handler handler ) ; <nl> + bool set_base_dir ( const char * path ) ; <nl> + void set_file_request_handler ( Handler handler ) ; <nl> <nl> - bool set_base_dir ( const char * path ) ; <nl> + void set_error_handler ( Handler handler ) ; <nl> + void set_logger ( Logger logger ) ; <nl> <nl> - void set_error_handler ( Handler handler ) ; <nl> - void set_logger ( Logger logger ) ; <nl> + void set_keep_alive_max_count ( size_t count ) ; <nl> + void set_payload_max_length ( size_t length ) ; <nl> <nl> - void set_keep_alive_max_count ( size_t count ) ; <nl> + int bind_to_any_port ( const char * host , int socket_flags = 0 ) ; <nl> + bool listen_after_bind ( ) ; <nl> <nl> - int bind_to_any_port ( const char * host , int socket_flags = 0 ) ; <nl> - bool listen_after_bind ( ) ; <nl> + bool listen ( const char * host , int port , int socket_flags = 0 ) ; <nl> <nl> - bool listen ( const char * host , int port , int socket_flags = 0 ) ; <nl> + bool is_running ( ) const ; <nl> + void stop ( ) ; <nl> <nl> - bool is_running ( ) const ; <nl> - void stop ( ) ; <nl> + std : : function < TaskQueue * ( void ) > new_task_queue ; <nl> <nl> protected : <nl> - bool process_request ( Stream & strm , bool last_connection , bool & connection_close ) ; <nl> + bool process_request ( Stream & strm , bool last_connection , <nl> + bool & connection_close , <nl> + std : : function < void ( Request & ) > setup_request ) ; <nl> <nl> - size_t keep_alive_max_count_ ; <nl> + size_t keep_alive_max_count_ ; <nl> + size_t payload_max_length_ ; <nl> <nl> private : <nl> - typedef std : : vector < std : : pair < std : : regex , Handler > > Handlers ; <nl> - <nl> - socket_t create_server_socket ( const char * host , int port , int socket_flags ) const ; <nl> - int bind_internal ( const char * host , int port , int socket_flags ) ; <nl> - bool listen_internal ( ) ; <nl> - <nl> - bool routing ( Request & req , Response & res ) ; <nl> - bool handle_file_request ( Request & req , Response & res ) ; <nl> - bool dispatch_request ( Request & req , Response & res , Handlers & handlers ) ; <nl> - <nl> - bool parse_request_line ( const char * s , Request & req ) ; <nl> - void write_response ( Stream & strm , bool last_connection , const Request & req , Response & res ) ; <nl> - <nl> - virtual bool read_and_close_socket ( socket_t sock ) ; <nl> - <nl> - bool is_running_ ; <nl> - socket_t svr_sock_ ; <nl> - std : : string base_dir_ ; <nl> - Handlers get_handlers_ ; <nl> - Handlers post_handlers_ ; <nl> - Handlers put_handlers_ ; <nl> - Handlers delete_handlers_ ; <nl> - Handlers options_handlers_ ; <nl> - Handler error_handler_ ; <nl> - Logger logger_ ; <nl> - <nl> - / / TODO : Use thread pool . . . <nl> - std : : mutex running_threads_mutex_ ; <nl> - int running_threads_ ; <nl> + typedef std : : vector < std : : pair < std : : regex , Handler > > Handlers ; <nl> + <nl> + socket_t create_server_socket ( const char * host , int port , <nl> + int socket_flags ) const ; <nl> + int bind_internal ( const char * host , int port , int socket_flags ) ; <nl> + bool listen_internal ( ) ; <nl> + <nl> + bool routing ( Request & req , Response & res ) ; <nl> + bool handle_file_request ( Request & req , Response & res ) ; <nl> + bool dispatch_request ( Request & req , Response & res , Handlers & handlers ) ; <nl> + <nl> + bool parse_request_line ( const char * s , Request & req ) ; <nl> + bool write_response ( Stream & strm , bool last_connection , const Request & req , <nl> + Response & res ) ; <nl> + bool write_content_with_provider ( Stream & strm , const Request & req , <nl> + Response & res , const std : : string & boundary , <nl> + const std : : string & content_type ) ; <nl> + <nl> + virtual bool process_and_close_socket ( socket_t sock ) ; <nl> + <nl> + std : : atomic < bool > is_running_ ; <nl> + std : : atomic < socket_t > svr_sock_ ; <nl> + std : : string base_dir_ ; <nl> + Handler file_request_handler_ ; <nl> + Handlers get_handlers_ ; <nl> + Handlers post_handlers_ ; <nl> + Handlers put_handlers_ ; <nl> + Handlers patch_handlers_ ; <nl> + Handlers delete_handlers_ ; <nl> + Handlers options_handlers_ ; <nl> + Handler error_handler_ ; <nl> + Logger logger_ ; <nl> } ; <nl> <nl> class Client { <nl> public : <nl> - Client ( <nl> - const char * host , <nl> - int port = 80 , <nl> - size_t timeout_sec = 300 ) ; <nl> + Client ( const char * host , int port = 80 , time_t timeout_sec = 300 ) ; <nl> + <nl> + virtual ~ Client ( ) ; <nl> + <nl> + virtual bool is_valid ( ) const ; <nl> + <nl> + std : : shared_ptr < Response > Get ( const char * path ) ; <nl> + <nl> + std : : shared_ptr < Response > Get ( const char * path , const Headers & headers ) ; <nl> + <nl> + std : : shared_ptr < Response > Get ( const char * path , Progress progress ) ; <nl> + <nl> + std : : shared_ptr < Response > Get ( const char * path , const Headers & headers , <nl> + Progress progress ) ; <nl> + <nl> + std : : shared_ptr < Response > Get ( const char * path , <nl> + ContentReceiver content_receiver ) ; <nl> <nl> - virtual ~ Client ( ) ; <nl> + std : : shared_ptr < Response > Get ( const char * path , const Headers & headers , <nl> + ContentReceiver content_receiver ) ; <nl> <nl> - virtual bool is_valid ( ) const ; <nl> + std : : shared_ptr < Response > <nl> + Get ( const char * path , ContentReceiver content_receiver , Progress progress ) ; <nl> <nl> - std : : shared_ptr < Response > Get ( const char * path , Progress progress = nullptr ) ; <nl> - std : : shared_ptr < Response > Get ( const char * path , const Headers & headers , Progress progress = nullptr ) ; <nl> + std : : shared_ptr < Response > Get ( const char * path , const Headers & headers , <nl> + ContentReceiver content_receiver , <nl> + Progress progress ) ; <nl> <nl> - std : : shared_ptr < Response > Head ( const char * path ) ; <nl> - std : : shared_ptr < Response > Head ( const char * path , const Headers & headers ) ; <nl> + std : : shared_ptr < Response > Get ( const char * path , const Headers & headers , <nl> + ResponseHandler response_handler , <nl> + ContentReceiver content_receiver ) ; <nl> <nl> - std : : shared_ptr < Response > Post ( const char * path , const std : : string & body , const char * content_type ) ; <nl> - std : : shared_ptr < Response > Post ( const char * path , const Headers & headers , const std : : string & body , const char * content_type ) ; <nl> + std : : shared_ptr < Response > Get ( const char * path , const Headers & headers , <nl> + ResponseHandler response_handler , <nl> + ContentReceiver content_receiver , <nl> + Progress progress ) ; <nl> <nl> - std : : shared_ptr < Response > Post ( const char * path , const Params & params ) ; <nl> - std : : shared_ptr < Response > Post ( const char * path , const Headers & headers , const Params & params ) ; <nl> + std : : shared_ptr < Response > Head ( const char * path ) ; <nl> <nl> - std : : shared_ptr < Response > Put ( const char * path , const std : : string & body , const char * content_type ) ; <nl> - std : : shared_ptr < Response > Put ( const char * path , const Headers & headers , const std : : string & body , const char * content_type ) ; <nl> + std : : shared_ptr < Response > Head ( const char * path , const Headers & headers ) ; <nl> <nl> - std : : shared_ptr < Response > Delete ( const char * path ) ; <nl> - std : : shared_ptr < Response > Delete ( const char * path , const Headers & headers ) ; <nl> + std : : shared_ptr < Response > Post ( const char * path , const std : : string & body , <nl> + const char * content_type ) ; <nl> <nl> - std : : shared_ptr < Response > Options ( const char * path ) ; <nl> - std : : shared_ptr < Response > Options ( const char * path , const Headers & headers ) ; <nl> + std : : shared_ptr < Response > Post ( const char * path , const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) ; <nl> <nl> - bool send ( Request & req , Response & res ) ; <nl> + std : : shared_ptr < Response > Post ( const char * path , const Params & params ) ; <nl> + <nl> + std : : shared_ptr < Response > Post ( const char * path , const Headers & headers , <nl> + const Params & params ) ; <nl> + <nl> + std : : shared_ptr < Response > Post ( const char * path , <nl> + const MultipartFormDataItems & items ) ; <nl> + <nl> + std : : shared_ptr < Response > Post ( const char * path , const Headers & headers , <nl> + const MultipartFormDataItems & items ) ; <nl> + <nl> + std : : shared_ptr < Response > Put ( const char * path , const std : : string & body , <nl> + const char * content_type ) ; <nl> + <nl> + std : : shared_ptr < Response > Put ( const char * path , const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) ; <nl> + <nl> + std : : shared_ptr < Response > Patch ( const char * path , const std : : string & body , <nl> + const char * content_type ) ; <nl> + <nl> + std : : shared_ptr < Response > Patch ( const char * path , const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) ; <nl> + <nl> + std : : shared_ptr < Response > Delete ( const char * path ) ; <nl> + <nl> + std : : shared_ptr < Response > Delete ( const char * path , const std : : string & body , <nl> + const char * content_type ) ; <nl> + <nl> + std : : shared_ptr < Response > Delete ( const char * path , const Headers & headers ) ; <nl> + <nl> + std : : shared_ptr < Response > Delete ( const char * path , const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) ; <nl> + <nl> + std : : shared_ptr < Response > Options ( const char * path ) ; <nl> + <nl> + std : : shared_ptr < Response > Options ( const char * path , const Headers & headers ) ; <nl> + <nl> + bool send ( const Request & req , Response & res ) ; <nl> + <nl> + bool send ( const std : : vector < Request > & requests , <nl> + std : : vector < Response > & responses ) ; <nl> + <nl> + void set_keep_alive_max_count ( size_t count ) ; <nl> + <nl> + void follow_location ( bool on ) ; <nl> <nl> protected : <nl> - bool process_request ( Stream & strm , Request & req , Response & res , bool & connection_close ) ; <nl> + bool process_request ( Stream & strm , const Request & req , Response & res , <nl> + bool last_connection , bool & connection_close ) ; <nl> <nl> - const std : : string host_ ; <nl> - const int port_ ; <nl> - size_t timeout_sec_ ; <nl> - const std : : string host_and_port_ ; <nl> + const std : : string host_ ; <nl> + const int port_ ; <nl> + time_t timeout_sec_ ; <nl> + const std : : string host_and_port_ ; <nl> + size_t keep_alive_max_count_ ; <nl> + size_t follow_location_ ; <nl> <nl> private : <nl> - socket_t create_client_socket ( ) const ; <nl> - bool read_response_line ( Stream & strm , Response & res ) ; <nl> - void write_request ( Stream & strm , Request & req ) ; <nl> - <nl> - virtual bool read_and_close_socket ( socket_t sock , Request & req , Response & res ) ; <nl> + socket_t create_client_socket ( ) const ; <nl> + bool read_response_line ( Stream & strm , Response & res ) ; <nl> + void write_request ( Stream & strm , const Request & req , bool last_connection ) ; <nl> + bool redirect ( const Request & req , Response & res ) ; <nl> + <nl> + virtual bool process_and_close_socket ( <nl> + socket_t sock , size_t request_count , <nl> + std : : function < bool ( Stream & strm , bool last_connection , <nl> + bool & connection_close ) > <nl> + callback ) ; <nl> + <nl> + virtual bool is_ssl ( ) const ; <nl> } ; <nl> <nl> + inline void Get ( std : : vector < Request > & requests , const char * path , <nl> + const Headers & headers ) { <nl> + Request req ; <nl> + req . method = " GET " ; <nl> + req . path = path ; <nl> + req . headers = headers ; <nl> + requests . emplace_back ( std : : move ( req ) ) ; <nl> + } <nl> + <nl> + inline void Get ( std : : vector < Request > & requests , const char * path ) { <nl> + Get ( requests , path , Headers ( ) ) ; <nl> + } <nl> + <nl> + inline void Post ( std : : vector < Request > & requests , const char * path , <nl> + const Headers & headers , const std : : string & body , <nl> + const char * content_type ) { <nl> + Request req ; <nl> + req . method = " POST " ; <nl> + req . path = path ; <nl> + req . headers = headers ; <nl> + req . headers . emplace ( " Content - Type " , content_type ) ; <nl> + req . body = body ; <nl> + requests . emplace_back ( std : : move ( req ) ) ; <nl> + } <nl> + <nl> + inline void Post ( std : : vector < Request > & requests , const char * path , <nl> + const std : : string & body , const char * content_type ) { <nl> + Post ( requests , path , Headers ( ) , body , content_type ) ; <nl> + } <nl> + <nl> # ifdef CPPHTTPLIB_OPENSSL_SUPPORT <nl> class SSLSocketStream : public Stream { <nl> public : <nl> - SSLSocketStream ( socket_t sock , SSL * ssl ) ; <nl> - virtual ~ SSLSocketStream ( ) ; <nl> + SSLSocketStream ( socket_t sock , SSL * ssl ) ; <nl> + virtual ~ SSLSocketStream ( ) ; <nl> <nl> - virtual int read ( char * ptr , size_t size ) ; <nl> - virtual int write ( const char * ptr , size_t size ) ; <nl> - virtual int write ( const char * ptr ) ; <nl> - virtual std : : string get_remote_addr ( ) ; <nl> + virtual int read ( char * ptr , size_t size ) ; <nl> + virtual int write ( const char * ptr , size_t size ) ; <nl> + virtual int write ( const char * ptr ) ; <nl> + virtual int write ( const std : : string & s ) ; <nl> + virtual std : : string get_remote_addr ( ) const ; <nl> <nl> private : <nl> - socket_t sock_ ; <nl> - SSL * ssl_ ; <nl> + socket_t sock_ ; <nl> + SSL * ssl_ ; <nl> } ; <nl> <nl> class SSLServer : public Server { <nl> public : <nl> - SSLServer ( <nl> - const char * cert_path , const char * private_key_path ) ; <nl> + SSLServer ( const char * cert_path , const char * private_key_path , <nl> + const char * client_ca_cert_file_path = nullptr , <nl> + const char * client_ca_cert_dir_path = nullptr ) ; <nl> <nl> - virtual ~ SSLServer ( ) ; <nl> + virtual ~ SSLServer ( ) ; <nl> <nl> - virtual bool is_valid ( ) const ; <nl> + virtual bool is_valid ( ) const ; <nl> <nl> private : <nl> - virtual bool read_and_close_socket ( socket_t sock ) ; <nl> + virtual bool process_and_close_socket ( socket_t sock ) ; <nl> <nl> - SSL_CTX * ctx_ ; <nl> - std : : mutex ctx_mutex_ ; <nl> + SSL_CTX * ctx_ ; <nl> + std : : mutex ctx_mutex_ ; <nl> } ; <nl> <nl> class SSLClient : public Client { <nl> public : <nl> - SSLClient ( <nl> - const char * host , <nl> - int port = 80 , <nl> - size_t timeout_sec = 300 ) ; <nl> + SSLClient ( const char * host , int port = 443 , time_t timeout_sec = 300 , <nl> + const char * client_cert_path = nullptr , <nl> + const char * client_key_path = nullptr ) ; <nl> <nl> - virtual ~ SSLClient ( ) ; <nl> + virtual ~ SSLClient ( ) ; <nl> <nl> - virtual bool is_valid ( ) const ; <nl> + virtual bool is_valid ( ) const ; <nl> <nl> - private : <nl> - virtual bool read_and_close_socket ( socket_t sock , Request & req , Response & res ) ; <nl> + void set_ca_cert_path ( const char * ca_ceert_file_path , <nl> + const char * ca_cert_dir_path = nullptr ) ; <nl> + void enable_server_certificate_verification ( bool enabled ) ; <nl> + <nl> + long get_openssl_verify_result ( ) const ; <nl> <nl> - SSL_CTX * ctx_ ; <nl> - std : : mutex ctx_mutex_ ; <nl> + SSL_CTX * ssl_context ( ) const noexcept ; <nl> + <nl> + private : <nl> + virtual bool process_and_close_socket ( <nl> + socket_t sock , size_t request_count , <nl> + std : : function < bool ( Stream & strm , bool last_connection , <nl> + bool & connection_close ) > <nl> + callback ) ; <nl> + virtual bool is_ssl ( ) const ; <nl> + <nl> + bool verify_host ( X509 * server_cert ) const ; <nl> + bool verify_host_with_subject_alt_name ( X509 * server_cert ) const ; <nl> + bool verify_host_with_common_name ( X509 * server_cert ) const ; <nl> + bool check_host_name ( const char * pattern , size_t pattern_len ) const ; <nl> + <nl> + SSL_CTX * ctx_ ; <nl> + std : : mutex ctx_mutex_ ; <nl> + std : : vector < std : : string > host_components_ ; <nl> + std : : string ca_cert_file_path_ ; <nl> + std : : string ca_cert_dir_path_ ; <nl> + bool server_certificate_verification_ = false ; <nl> + long verify_result_ = 0 ; <nl> } ; <nl> # endif <nl> <nl> class SSLClient : public Client { <nl> * / <nl> namespace detail { <nl> <nl> - template < class Fn > <nl> - void split ( const char * b , const char * e , char d , Fn fn ) <nl> - { <nl> - int i = 0 ; <nl> - int beg = 0 ; <nl> + inline bool is_hex ( char c , int & v ) { <nl> + if ( 0x20 < = c & & isdigit ( c ) ) { <nl> + v = c - ' 0 ' ; <nl> + return true ; <nl> + } else if ( ' A ' < = c & & c < = ' F ' ) { <nl> + v = c - ' A ' + 10 ; <nl> + return true ; <nl> + } else if ( ' a ' < = c & & c < = ' f ' ) { <nl> + v = c - ' a ' + 10 ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> <nl> - while ( e ? ( b + i ! = e ) : ( b [ i ] ! = ' \ 0 ' ) ) { <nl> - if ( b [ i ] = = d ) { <nl> - fn ( & b [ beg ] , & b [ i ] ) ; <nl> - beg = i + 1 ; <nl> - } <nl> - i + + ; <nl> + inline bool from_hex_to_i ( const std : : string & s , size_t i , size_t cnt , <nl> + int & val ) { <nl> + if ( i > = s . size ( ) ) { return false ; } <nl> + <nl> + val = 0 ; <nl> + for ( ; cnt ; i + + , cnt - - ) { <nl> + if ( ! s [ i ] ) { return false ; } <nl> + int v = 0 ; <nl> + if ( is_hex ( s [ i ] , v ) ) { <nl> + val = val * 16 + v ; <nl> + } else { <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + inline std : : string from_i_to_hex ( size_t n ) { <nl> + const char * charset = " 0123456789abcdef " ; <nl> + std : : string ret ; <nl> + do { <nl> + ret = charset [ n & 15 ] + ret ; <nl> + n > > = 4 ; <nl> + } while ( n > 0 ) ; <nl> + return ret ; <nl> + } <nl> + <nl> + inline size_t to_utf8 ( int code , char * buff ) { <nl> + if ( code < 0x0080 ) { <nl> + buff [ 0 ] = ( code & 0x7F ) ; <nl> + return 1 ; <nl> + } else if ( code < 0x0800 ) { <nl> + buff [ 0 ] = ( 0xC0 | ( ( code > > 6 ) & 0x1F ) ) ; <nl> + buff [ 1 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> + return 2 ; <nl> + } else if ( code < 0xD800 ) { <nl> + buff [ 0 ] = ( 0xE0 | ( ( code > > 12 ) & 0xF ) ) ; <nl> + buff [ 1 ] = ( 0x80 | ( ( code > > 6 ) & 0x3F ) ) ; <nl> + buff [ 2 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> + return 3 ; <nl> + } else if ( code < 0xE000 ) { / / D800 - DFFF is invalid . . . <nl> + return 0 ; <nl> + } else if ( code < 0x10000 ) { <nl> + buff [ 0 ] = ( 0xE0 | ( ( code > > 12 ) & 0xF ) ) ; <nl> + buff [ 1 ] = ( 0x80 | ( ( code > > 6 ) & 0x3F ) ) ; <nl> + buff [ 2 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> + return 3 ; <nl> + } else if ( code < 0x110000 ) { <nl> + buff [ 0 ] = ( 0xF0 | ( ( code > > 18 ) & 0x7 ) ) ; <nl> + buff [ 1 ] = ( 0x80 | ( ( code > > 12 ) & 0x3F ) ) ; <nl> + buff [ 2 ] = ( 0x80 | ( ( code > > 6 ) & 0x3F ) ) ; <nl> + buff [ 3 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> + return 4 ; <nl> + } <nl> + <nl> + / / NOTREACHED <nl> + return 0 ; <nl> + } <nl> + <nl> + / / NOTE : This code came up with the following stackoverflow post : <nl> + / / https : / / stackoverflow . com / questions / 180947 / base64 - decode - snippet - in - c <nl> + inline std : : string base64_encode ( const std : : string & in ) { <nl> + static const auto lookup = <nl> + " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + / " ; <nl> + <nl> + std : : string out ; <nl> + out . reserve ( in . size ( ) ) ; <nl> + <nl> + int val = 0 ; <nl> + int valb = - 6 ; <nl> + <nl> + for ( uint8_t c : in ) { <nl> + val = ( val < < 8 ) + c ; <nl> + valb + = 8 ; <nl> + while ( valb > = 0 ) { <nl> + out . push_back ( lookup [ ( val > > valb ) & 0x3F ] ) ; <nl> + valb - = 6 ; <nl> } <nl> + } <nl> + <nl> + if ( valb > - 6 ) { out . push_back ( lookup [ ( ( val < < 8 ) > > ( valb + 8 ) ) & 0x3F ] ) ; } <nl> <nl> - if ( i ) { <nl> - fn ( & b [ beg ] , & b [ i ] ) ; <nl> + while ( out . size ( ) % 4 ) { <nl> + out . push_back ( ' = ' ) ; <nl> + } <nl> + <nl> + return out ; <nl> + } <nl> + <nl> + inline bool is_file ( const std : : string & path ) { <nl> + struct stat st ; <nl> + return stat ( path . c_str ( ) , & st ) > = 0 & & S_ISREG ( st . st_mode ) ; <nl> + } <nl> + <nl> + inline bool is_dir ( const std : : string & path ) { <nl> + struct stat st ; <nl> + return stat ( path . c_str ( ) , & st ) > = 0 & & S_ISDIR ( st . st_mode ) ; <nl> + } <nl> + <nl> + inline bool is_valid_path ( const std : : string & path ) { <nl> + size_t level = 0 ; <nl> + size_t i = 0 ; <nl> + <nl> + / / Skip slash <nl> + while ( i < path . size ( ) & & path [ i ] = = ' / ' ) { <nl> + i + + ; <nl> + } <nl> + <nl> + while ( i < path . size ( ) ) { <nl> + / / Read component <nl> + auto beg = i ; <nl> + while ( i < path . size ( ) & & path [ i ] ! = ' / ' ) { <nl> + i + + ; <nl> } <nl> + <nl> + auto len = i - beg ; <nl> + assert ( len > 0 ) ; <nl> + <nl> + if ( ! path . compare ( beg , len , " . " ) ) { <nl> + ; <nl> + } else if ( ! path . compare ( beg , len , " . . " ) ) { <nl> + if ( level = = 0 ) { return false ; } <nl> + level - - ; <nl> + } else { <nl> + level + + ; <nl> + } <nl> + <nl> + / / Skip slash <nl> + while ( i < path . size ( ) & & path [ i ] = = ' / ' ) { <nl> + i + + ; <nl> + } <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + inline void read_file ( const std : : string & path , std : : string & out ) { <nl> + std : : ifstream fs ( path , std : : ios_base : : binary ) ; <nl> + fs . seekg ( 0 , std : : ios_base : : end ) ; <nl> + auto size = fs . tellg ( ) ; <nl> + fs . seekg ( 0 ) ; <nl> + out . resize ( static_cast < size_t > ( size ) ) ; <nl> + fs . read ( & out [ 0 ] , size ) ; <nl> + } <nl> + <nl> + inline std : : string file_extension ( const std : : string & path ) { <nl> + std : : smatch m ; <nl> + auto pat = std : : regex ( " \ \ . ( [ a - zA - Z0 - 9 ] + ) $ " ) ; <nl> + if ( std : : regex_search ( path , m , pat ) ) { return m [ 1 ] . str ( ) ; } <nl> + return std : : string ( ) ; <nl> + } <nl> + <nl> + template < class Fn > void split ( const char * b , const char * e , char d , Fn fn ) { <nl> + int i = 0 ; <nl> + int beg = 0 ; <nl> + <nl> + while ( e ? ( b + i ! = e ) : ( b [ i ] ! = ' \ 0 ' ) ) { <nl> + if ( b [ i ] = = d ) { <nl> + fn ( & b [ beg ] , & b [ i ] ) ; <nl> + beg = i + 1 ; <nl> + } <nl> + i + + ; <nl> + } <nl> + <nl> + if ( i ) { fn ( & b [ beg ] , & b [ i ] ) ; } <nl> } <nl> <nl> / / NOTE : until the read size reaches ` fixed_buffer_size ` , use ` fixed_buffer ` <nl> / / to store data . The call can set memory on stack for performance . <nl> class stream_line_reader { <nl> public : <nl> - stream_line_reader ( Stream & strm , char * fixed_buffer , size_t fixed_buffer_size ) <nl> - : strm_ ( strm ) <nl> - , fixed_buffer_ ( fixed_buffer ) <nl> - , fixed_buffer_size_ ( fixed_buffer_size ) { <nl> + stream_line_reader ( Stream & strm , char * fixed_buffer , size_t fixed_buffer_size ) <nl> + : strm_ ( strm ) , fixed_buffer_ ( fixed_buffer ) , <nl> + fixed_buffer_size_ ( fixed_buffer_size ) { } <nl> + <nl> + const char * ptr ( ) const { <nl> + if ( glowable_buffer_ . empty ( ) ) { <nl> + return fixed_buffer_ ; <nl> + } else { <nl> + return glowable_buffer_ . data ( ) ; <nl> } <nl> + } <nl> <nl> - const char * ptr ( ) const { <nl> - if ( glowable_buffer_ . empty ( ) ) { <nl> - return fixed_buffer_ ; <nl> - } else { <nl> - return glowable_buffer_ . data ( ) ; <nl> - } <nl> + size_t size ( ) const { <nl> + if ( glowable_buffer_ . empty ( ) ) { <nl> + return fixed_buffer_used_size_ ; <nl> + } else { <nl> + return glowable_buffer_ . size ( ) ; <nl> } <nl> + } <nl> <nl> - bool getline ( ) { <nl> - fixed_buffer_used_size_ = 0 ; <nl> - glowable_buffer_ . clear ( ) ; <nl> - <nl> - for ( size_t i = 0 ; ; i + + ) { <nl> - char byte ; <nl> - auto n = strm_ . read ( & byte , 1 ) ; <nl> - <nl> - if ( n < 0 ) { <nl> - return false ; <nl> - } else if ( n = = 0 ) { <nl> - if ( i = = 0 ) { <nl> - return false ; <nl> - } else { <nl> - break ; <nl> - } <nl> - } <nl> + bool getline ( ) { <nl> + fixed_buffer_used_size_ = 0 ; <nl> + glowable_buffer_ . clear ( ) ; <nl> <nl> - append ( byte ) ; <nl> + for ( size_t i = 0 ; ; i + + ) { <nl> + char byte ; <nl> + auto n = strm_ . read ( & byte , 1 ) ; <nl> <nl> - if ( byte = = ' \ n ' ) { <nl> - break ; <nl> - } <nl> + if ( n < 0 ) { <nl> + return false ; <nl> + } else if ( n = = 0 ) { <nl> + if ( i = = 0 ) { <nl> + return false ; <nl> + } else { <nl> + break ; <nl> } <nl> + } <nl> <nl> - return true ; <nl> - } <nl> + append ( byte ) ; <nl> <nl> - private : <nl> - void append ( char c ) { <nl> - if ( fixed_buffer_used_size_ < fixed_buffer_size_ - 1 ) { <nl> - fixed_buffer_ [ fixed_buffer_used_size_ + + ] = c ; <nl> - fixed_buffer_ [ fixed_buffer_used_size_ ] = ' \ 0 ' ; <nl> - } else { <nl> - if ( glowable_buffer_ . empty ( ) ) { <nl> - assert ( fixed_buffer_ [ fixed_buffer_used_size_ ] = = ' \ 0 ' ) ; <nl> - glowable_buffer_ . assign ( fixed_buffer_ , fixed_buffer_used_size_ ) ; <nl> - } <nl> - glowable_buffer_ + = c ; <nl> - } <nl> + if ( byte = = ' \ n ' ) { break ; } <nl> } <nl> <nl> - Stream & strm_ ; <nl> - char * fixed_buffer_ ; <nl> - const size_t fixed_buffer_size_ ; <nl> - size_t fixed_buffer_used_size_ ; <nl> - std : : string glowable_buffer_ ; <nl> + return true ; <nl> + } <nl> + <nl> + private : <nl> + void append ( char c ) { <nl> + if ( fixed_buffer_used_size_ < fixed_buffer_size_ - 1 ) { <nl> + fixed_buffer_ [ fixed_buffer_used_size_ + + ] = c ; <nl> + fixed_buffer_ [ fixed_buffer_used_size_ ] = ' \ 0 ' ; <nl> + } else { <nl> + if ( glowable_buffer_ . empty ( ) ) { <nl> + assert ( fixed_buffer_ [ fixed_buffer_used_size_ ] = = ' \ 0 ' ) ; <nl> + glowable_buffer_ . assign ( fixed_buffer_ , fixed_buffer_used_size_ ) ; <nl> + } <nl> + glowable_buffer_ + = c ; <nl> + } <nl> + } <nl> + <nl> + Stream & strm_ ; <nl> + char * fixed_buffer_ ; <nl> + const size_t fixed_buffer_size_ ; <nl> + size_t fixed_buffer_used_size_ ; <nl> + std : : string glowable_buffer_ ; <nl> } ; <nl> <nl> - inline int close_socket ( socket_t sock ) <nl> - { <nl> + inline int close_socket ( socket_t sock ) { <nl> # ifdef _WIN32 <nl> - return closesocket ( sock ) ; <nl> + return closesocket ( sock ) ; <nl> # else <nl> - return close ( sock ) ; <nl> + return close ( sock ) ; <nl> # endif <nl> } <nl> <nl> - inline int select_read ( socket_t sock , size_t sec , size_t usec ) <nl> - { <nl> - fd_set fds ; <nl> - FD_ZERO ( & fds ) ; <nl> - FD_SET ( sock , & fds ) ; <nl> + inline int select_read ( socket_t sock , time_t sec , time_t usec ) { <nl> + # ifdef CPPHTTPLIB_USE_POLL <nl> + struct pollfd pfd_read ; <nl> + pfd_read . fd = sock ; <nl> + pfd_read . events = POLLIN ; <nl> <nl> - timeval tv ; <nl> - tv . tv_sec = sec ; <nl> - tv . tv_usec = usec ; <nl> + auto timeout = static_cast < int > ( sec * 1000 + usec / 1000 ) ; <nl> <nl> - return select ( sock + 1 , & fds , NULL , NULL , & tv ) ; <nl> - } <nl> + return poll ( & pfd_read , 1 , timeout ) ; <nl> + # else <nl> + fd_set fds ; <nl> + FD_ZERO ( & fds ) ; <nl> + FD_SET ( sock , & fds ) ; <nl> <nl> - inline bool wait_until_socket_is_ready ( socket_t sock , size_t sec , size_t usec ) <nl> - { <nl> - fd_set fdsr ; <nl> - FD_ZERO ( & fdsr ) ; <nl> - FD_SET ( sock , & fdsr ) ; <nl> + timeval tv ; <nl> + tv . tv_sec = static_cast < long > ( sec ) ; <nl> + tv . tv_usec = static_cast < long > ( usec ) ; <nl> <nl> - auto fdsw = fdsr ; <nl> - auto fdse = fdsr ; <nl> + return select ( static_cast < int > ( sock + 1 ) , & fds , nullptr , nullptr , & tv ) ; <nl> + # endif <nl> + } <nl> <nl> - timeval tv ; <nl> - tv . tv_sec = sec ; <nl> - tv . tv_usec = usec ; <nl> + inline bool wait_until_socket_is_ready ( socket_t sock , time_t sec , time_t usec ) { <nl> + # ifdef CPPHTTPLIB_USE_POLL <nl> + struct pollfd pfd_read ; <nl> + pfd_read . fd = sock ; <nl> + pfd_read . events = POLLIN | POLLOUT ; <nl> <nl> - if ( select ( sock + 1 , & fdsr , & fdsw , & fdse , & tv ) < 0 ) { <nl> - return false ; <nl> - } else if ( FD_ISSET ( sock , & fdsr ) | | FD_ISSET ( sock , & fdsw ) ) { <nl> - int error = 0 ; <nl> - socklen_t len = sizeof ( error ) ; <nl> - if ( getsockopt ( sock , SOL_SOCKET , SO_ERROR , ( char * ) & error , & len ) < 0 | | error ) { <nl> - return false ; <nl> - } <nl> - } else { <nl> - return false ; <nl> - } <nl> + auto timeout = static_cast < int > ( sec * 1000 + usec / 1000 ) ; <nl> <nl> - return true ; <nl> + if ( poll ( & pfd_read , 1 , timeout ) > 0 & & <nl> + pfd_read . revents & ( POLLIN | POLLOUT ) ) { <nl> + int error = 0 ; <nl> + socklen_t len = sizeof ( error ) ; <nl> + return getsockopt ( sock , SOL_SOCKET , SO_ERROR , reinterpret_cast < char * > ( & error ) , & len ) > = 0 & & <nl> + ! error ; <nl> + } <nl> + return false ; <nl> + # else <nl> + fd_set fdsr ; <nl> + FD_ZERO ( & fdsr ) ; <nl> + FD_SET ( sock , & fdsr ) ; <nl> + <nl> + auto fdsw = fdsr ; <nl> + auto fdse = fdsr ; <nl> + <nl> + timeval tv ; <nl> + tv . tv_sec = static_cast < long > ( sec ) ; <nl> + tv . tv_usec = static_cast < long > ( usec ) ; <nl> + <nl> + if ( select ( static_cast < int > ( sock + 1 ) , & fdsr , & fdsw , & fdse , & tv ) > 0 & & <nl> + ( FD_ISSET ( sock , & fdsr ) | | FD_ISSET ( sock , & fdsw ) ) ) { <nl> + int error = 0 ; <nl> + socklen_t len = sizeof ( error ) ; <nl> + return getsockopt ( sock , SOL_SOCKET , SO_ERROR , ( char * ) & error , & len ) > = 0 & & <nl> + ! error ; <nl> + } <nl> + return false ; <nl> + # endif <nl> } <nl> <nl> template < typename T > <nl> - inline bool read_and_close_socket ( socket_t sock , size_t keep_alive_max_count , T callback ) <nl> - { <nl> - bool ret = false ; <nl> - <nl> - if ( keep_alive_max_count > 0 ) { <nl> - auto count = keep_alive_max_count ; <nl> - while ( count > 0 & & <nl> - detail : : select_read ( sock , <nl> - CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND , <nl> - CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND ) > 0 ) { <nl> - SocketStream strm ( sock ) ; <nl> - auto last_connection = count = = 1 ; <nl> - auto connection_close = false ; <nl> - <nl> - ret = callback ( strm , last_connection , connection_close ) ; <nl> - if ( ! ret | | connection_close ) { <nl> - break ; <nl> - } <nl> + inline bool process_and_close_socket ( bool is_client_request , socket_t sock , <nl> + size_t keep_alive_max_count , T callback ) { <nl> + assert ( keep_alive_max_count > 0 ) ; <nl> <nl> - count - - ; <nl> - } <nl> - } else { <nl> - SocketStream strm ( sock ) ; <nl> - auto dummy_connection_close = false ; <nl> - ret = callback ( strm , true , dummy_connection_close ) ; <nl> + bool ret = false ; <nl> + <nl> + if ( keep_alive_max_count > 1 ) { <nl> + auto count = keep_alive_max_count ; <nl> + while ( count > 0 & & <nl> + ( is_client_request | | <nl> + detail : : select_read ( sock , CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND , <nl> + CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND ) > 0 ) ) { <nl> + SocketStream strm ( sock ) ; <nl> + auto last_connection = count = = 1 ; <nl> + auto connection_close = false ; <nl> + <nl> + ret = callback ( strm , last_connection , connection_close ) ; <nl> + if ( ! ret | | connection_close ) { break ; } <nl> + <nl> + count - - ; <nl> } <nl> + } else { <nl> + SocketStream strm ( sock ) ; <nl> + auto dummy_connection_close = false ; <nl> + ret = callback ( strm , true , dummy_connection_close ) ; <nl> + } <nl> <nl> - close_socket ( sock ) ; <nl> - return ret ; <nl> + close_socket ( sock ) ; <nl> + return ret ; <nl> } <nl> <nl> - inline int shutdown_socket ( socket_t sock ) <nl> - { <nl> + inline int shutdown_socket ( socket_t sock ) { <nl> # ifdef _WIN32 <nl> - return shutdown ( sock , SD_BOTH ) ; <nl> + return shutdown ( sock , SD_BOTH ) ; <nl> # else <nl> - return shutdown ( sock , SHUT_RDWR ) ; <nl> + return shutdown ( sock , SHUT_RDWR ) ; <nl> # endif <nl> } <nl> <nl> template < typename Fn > <nl> - socket_t create_socket ( const char * host , int port , Fn fn , int socket_flags = 0 ) <nl> - { <nl> + socket_t create_socket ( const char * host , int port , Fn fn , <nl> + int socket_flags = 0 ) { <nl> # ifdef _WIN32 <nl> # define SO_SYNCHRONOUS_NONALERT 0x20 <nl> # define SO_OPENTYPE 0x7008 <nl> <nl> - int opt = SO_SYNCHRONOUS_NONALERT ; <nl> - setsockopt ( INVALID_SOCKET , SOL_SOCKET , SO_OPENTYPE , ( char * ) & opt , sizeof ( opt ) ) ; <nl> + int opt = SO_SYNCHRONOUS_NONALERT ; <nl> + setsockopt ( INVALID_SOCKET , SOL_SOCKET , SO_OPENTYPE , ( char * ) & opt , <nl> + sizeof ( opt ) ) ; <nl> # endif <nl> <nl> - / / Get address info <nl> - struct addrinfo hints ; <nl> - struct addrinfo * result ; <nl> + / / Get address info <nl> + struct addrinfo hints ; <nl> + struct addrinfo * result ; <nl> <nl> - memset ( & hints , 0 , sizeof ( struct addrinfo ) ) ; <nl> - hints . ai_family = AF_UNSPEC ; <nl> - hints . ai_socktype = SOCK_STREAM ; <nl> - hints . ai_flags = socket_flags ; <nl> - hints . ai_protocol = 0 ; <nl> + memset ( & hints , 0 , sizeof ( struct addrinfo ) ) ; <nl> + hints . ai_family = AF_UNSPEC ; <nl> + hints . ai_socktype = SOCK_STREAM ; <nl> + hints . ai_flags = socket_flags ; <nl> + hints . ai_protocol = 0 ; <nl> <nl> - auto service = std : : to_string ( port ) ; <nl> + auto service = std : : to_string ( port ) ; <nl> <nl> - if ( getaddrinfo ( host , service . c_str ( ) , & hints , & result ) ) { <nl> - return INVALID_SOCKET ; <nl> - } <nl> + if ( getaddrinfo ( host , service . c_str ( ) , & hints , & result ) ) { <nl> + return INVALID_SOCKET ; <nl> + } <nl> <nl> - for ( auto rp = result ; rp ; rp = rp - > ai_next ) { <nl> - / / Create a socket <nl> - auto sock = socket ( rp - > ai_family , rp - > ai_socktype , rp - > ai_protocol ) ; <nl> - if ( sock = = INVALID_SOCKET ) { <nl> - continue ; <nl> - } <nl> + for ( auto rp = result ; rp ; rp = rp - > ai_next ) { <nl> + / / Create a socket <nl> + # ifdef _WIN32 <nl> + auto sock = WSASocketW ( rp - > ai_family , rp - > ai_socktype , rp - > ai_protocol , <nl> + nullptr , 0 , WSA_FLAG_NO_HANDLE_INHERIT ) ; <nl> + # else <nl> + auto sock = socket ( rp - > ai_family , rp - > ai_socktype , rp - > ai_protocol ) ; <nl> + # endif <nl> + if ( sock = = INVALID_SOCKET ) { continue ; } <nl> <nl> - / / Make ' reuse address ' option available <nl> - int yes = 1 ; <nl> - setsockopt ( sock , SOL_SOCKET , SO_REUSEADDR , ( char * ) & yes , sizeof ( yes ) ) ; <nl> + # ifndef _WIN32 <nl> + if ( fcntl ( sock , F_SETFD , FD_CLOEXEC ) = = - 1 ) { continue ; } <nl> + # endif <nl> <nl> - / / bind or connect <nl> - if ( fn ( sock , * rp ) ) { <nl> - freeaddrinfo ( result ) ; <nl> - return sock ; <nl> - } <nl> + / / Make ' reuse address ' option available <nl> + int yes = 1 ; <nl> + setsockopt ( sock , SOL_SOCKET , SO_REUSEADDR , reinterpret_cast < char * > ( & yes ) , sizeof ( yes ) ) ; <nl> + # ifdef SO_REUSEPORT <nl> + setsockopt ( sock , SOL_SOCKET , SO_REUSEPORT , reinterpret_cast < char * > ( & yes ) , sizeof ( yes ) ) ; <nl> + # endif <nl> <nl> - close_socket ( sock ) ; <nl> + / / bind or connect <nl> + if ( fn ( sock , * rp ) ) { <nl> + freeaddrinfo ( result ) ; <nl> + return sock ; <nl> } <nl> <nl> - freeaddrinfo ( result ) ; <nl> - return INVALID_SOCKET ; <nl> + close_socket ( sock ) ; <nl> + } <nl> + <nl> + freeaddrinfo ( result ) ; <nl> + return INVALID_SOCKET ; <nl> } <nl> <nl> - inline void set_nonblocking ( socket_t sock , bool nonblocking ) <nl> - { <nl> + inline void set_nonblocking ( socket_t sock , bool nonblocking ) { <nl> # ifdef _WIN32 <nl> - auto flags = nonblocking ? 1UL : 0UL ; <nl> - ioctlsocket ( sock , FIONBIO , & flags ) ; <nl> + auto flags = nonblocking ? 1UL : 0UL ; <nl> + ioctlsocket ( sock , FIONBIO , & flags ) ; <nl> # else <nl> - auto flags = fcntl ( sock , F_GETFL , 0 ) ; <nl> - fcntl ( sock , F_SETFL , nonblocking ? ( flags | O_NONBLOCK ) : ( flags & ( ~ O_NONBLOCK ) ) ) ; <nl> + auto flags = fcntl ( sock , F_GETFL , 0 ) ; <nl> + fcntl ( sock , F_SETFL , <nl> + nonblocking ? ( flags | O_NONBLOCK ) : ( flags & ( ~ O_NONBLOCK ) ) ) ; <nl> # endif <nl> } <nl> <nl> - inline bool is_connection_error ( ) <nl> - { <nl> + inline bool is_connection_error ( ) { <nl> # ifdef _WIN32 <nl> - return WSAGetLastError ( ) ! = WSAEWOULDBLOCK ; <nl> + return WSAGetLastError ( ) ! = WSAEWOULDBLOCK ; <nl> # else <nl> - return errno ! = EINPROGRESS ; <nl> + return errno ! = EINPROGRESS ; <nl> # endif <nl> } <nl> <nl> inline std : : string get_remote_addr ( socket_t sock ) { <nl> - struct sockaddr_storage addr ; <nl> - socklen_t len = sizeof ( addr ) ; <nl> + struct sockaddr_storage addr ; <nl> + socklen_t len = sizeof ( addr ) ; <nl> + <nl> + if ( ! getpeername ( sock , reinterpret_cast < struct sockaddr * > ( & addr ) , & len ) ) { <nl> + char ipstr [ NI_MAXHOST ] ; <nl> + <nl> + if ( ! getnameinfo ( reinterpret_cast < struct sockaddr * > ( & addr ) , len , ipstr , sizeof ( ipstr ) , <nl> + nullptr , 0 , NI_NUMERICHOST ) ) { <nl> + return ipstr ; <nl> + } <nl> + } <nl> + <nl> + return std : : string ( ) ; <nl> + } <nl> + <nl> + inline const char * find_content_type ( const std : : string & path ) { <nl> + auto ext = file_extension ( path ) ; <nl> + if ( ext = = " txt " ) { <nl> + return " text / plain " ; <nl> + } else if ( ext = = " html " ) { <nl> + return " text / html " ; <nl> + } else if ( ext = = " css " ) { <nl> + return " text / css " ; <nl> + } else if ( ext = = " jpeg " | | ext = = " jpg " ) { <nl> + return " image / jpg " ; <nl> + } else if ( ext = = " png " ) { <nl> + return " image / png " ; <nl> + } else if ( ext = = " gif " ) { <nl> + return " image / gif " ; <nl> + } else if ( ext = = " svg " ) { <nl> + return " image / svg + xml " ; <nl> + } else if ( ext = = " ico " ) { <nl> + return " image / x - icon " ; <nl> + } else if ( ext = = " json " ) { <nl> + return " application / json " ; <nl> + } else if ( ext = = " pdf " ) { <nl> + return " application / pdf " ; <nl> + } else if ( ext = = " js " ) { <nl> + return " application / javascript " ; <nl> + } else if ( ext = = " xml " ) { <nl> + return " application / xml " ; <nl> + } else if ( ext = = " xhtml " ) { <nl> + return " application / xhtml + xml " ; <nl> + } <nl> + return nullptr ; <nl> + } <nl> + <nl> + inline const char * status_message ( int status ) { <nl> + switch ( status ) { <nl> + case 200 : return " OK " ; <nl> + case 206 : return " Partial Content " ; <nl> + case 301 : return " Moved Permanently " ; <nl> + case 302 : return " Found " ; <nl> + case 303 : return " See Other " ; <nl> + case 304 : return " Not Modified " ; <nl> + case 400 : return " Bad Request " ; <nl> + case 403 : return " Forbidden " ; <nl> + case 404 : return " Not Found " ; <nl> + case 413 : return " Payload Too Large " ; <nl> + case 414 : return " Request - URI Too Long " ; <nl> + case 415 : return " Unsupported Media Type " ; <nl> + case 416 : return " Range Not Satisfiable " ; <nl> + <nl> + default : <nl> + case 500 : return " Internal Server Error " ; <nl> + } <nl> + } <nl> <nl> - if ( ! getpeername ( sock , ( struct sockaddr * ) & addr , & len ) ) { <nl> - char ipstr [ NI_MAXHOST ] ; <nl> + # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> + inline bool can_compress ( const std : : string & content_type ) { <nl> + return ! content_type . find ( " text / " ) | | content_type = = " image / svg + xml " | | <nl> + content_type = = " application / javascript " | | <nl> + content_type = = " application / json " | | <nl> + content_type = = " application / xml " | | <nl> + content_type = = " application / xhtml + xml " ; <nl> + } <nl> <nl> - if ( ! getnameinfo ( ( struct sockaddr * ) & addr , len , <nl> - ipstr , sizeof ( ipstr ) , nullptr , 0 , NI_NUMERICHOST ) ) { <nl> - return ipstr ; <nl> - } <nl> - } <nl> + inline bool compress ( std : : string & content ) { <nl> + z_stream strm ; <nl> + strm . zalloc = Z_NULL ; <nl> + strm . zfree = Z_NULL ; <nl> + strm . opaque = Z_NULL ; <nl> <nl> - return std : : string ( ) ; <nl> - } <nl> + auto ret = deflateInit2 ( & strm , Z_DEFAULT_COMPRESSION , Z_DEFLATED , 31 , 8 , <nl> + Z_DEFAULT_STRATEGY ) ; <nl> + if ( ret ! = Z_OK ) { return false ; } <nl> <nl> - inline bool is_file ( const std : : string & path ) <nl> - { <nl> - struct stat st ; <nl> - return stat ( path . c_str ( ) , & st ) > = 0 & & S_ISREG ( st . st_mode ) ; <nl> - } <nl> + strm . avail_in = content . size ( ) ; <nl> + strm . next_in = const_cast < Bytef * > ( reinterpret_cast < const Bytef * > ( content . data ( ) ) ) ; <nl> <nl> - inline bool is_dir ( const std : : string & path ) <nl> - { <nl> - struct stat st ; <nl> - return stat ( path . c_str ( ) , & st ) > = 0 & & S_ISDIR ( st . st_mode ) ; <nl> - } <nl> + std : : string compressed ; <nl> <nl> - inline bool is_valid_path ( const std : : string & path ) { <nl> - size_t level = 0 ; <nl> - size_t i = 0 ; <nl> + const auto bufsiz = 16384 ; <nl> + char buff [ bufsiz ] ; <nl> + do { <nl> + strm . avail_out = bufsiz ; <nl> + strm . next_out = reinterpret_cast < Bytef * > ( buff ) ; <nl> + ret = deflate ( & strm , Z_FINISH ) ; <nl> + assert ( ret ! = Z_STREAM_ERROR ) ; <nl> + compressed . append ( buff , bufsiz - strm . avail_out ) ; <nl> + } while ( strm . avail_out = = 0 ) ; <nl> <nl> - / / Skip slash <nl> - while ( i < path . size ( ) & & path [ i ] = = ' / ' ) { <nl> - i + + ; <nl> - } <nl> + assert ( ret = = Z_STREAM_END ) ; <nl> + assert ( strm . avail_in = = 0 ) ; <nl> <nl> - while ( i < path . size ( ) ) { <nl> - / / Read component <nl> - auto beg = i ; <nl> - while ( i < path . size ( ) & & path [ i ] ! = ' / ' ) { <nl> - i + + ; <nl> - } <nl> + content . swap ( compressed ) ; <nl> <nl> - auto len = i - beg ; <nl> - assert ( len > 0 ) ; <nl> + deflateEnd ( & strm ) ; <nl> + return true ; <nl> + } <nl> <nl> - if ( ! path . compare ( beg , len , " . " ) ) { <nl> - ; <nl> - } else if ( ! path . compare ( beg , len , " . . " ) ) { <nl> - if ( level = = 0 ) { <nl> - return false ; <nl> - } <nl> - level - - ; <nl> - } else { <nl> - level + + ; <nl> - } <nl> + class decompressor { <nl> + public : <nl> + decompressor ( ) { <nl> + strm . zalloc = Z_NULL ; <nl> + strm . zfree = Z_NULL ; <nl> + strm . opaque = Z_NULL ; <nl> + <nl> + / / 15 is the value of wbits , which should be at the maximum possible value <nl> + / / to ensure that any gzip stream can be decoded . The offset of 16 specifies <nl> + / / that the stream to decompress will be formatted with a gzip wrapper . <nl> + is_valid_ = inflateInit2 ( & strm , 16 + 15 ) = = Z_OK ; <nl> + } <nl> + <nl> + ~ decompressor ( ) { inflateEnd ( & strm ) ; } <nl> + <nl> + bool is_valid ( ) const { return is_valid_ ; } <nl> <nl> - / / Skip slash <nl> - while ( i < path . size ( ) & & path [ i ] = = ' / ' ) { <nl> - i + + ; <nl> - } <nl> - } <nl> + template < typename T > <nl> + bool decompress ( const char * data , size_t data_length , T callback ) { <nl> + int ret = Z_OK ; <nl> <nl> - return true ; <nl> - } <nl> + strm . avail_in = data_length ; <nl> + strm . next_in = const_cast < Bytef * > ( reinterpret_cast < const Bytef * > ( data ) ) ; <nl> <nl> - inline void read_file ( const std : : string & path , std : : string & out ) <nl> - { <nl> - std : : ifstream fs ( path , std : : ios_base : : binary ) ; <nl> - fs . seekg ( 0 , std : : ios_base : : end ) ; <nl> - auto size = fs . tellg ( ) ; <nl> - fs . seekg ( 0 ) ; <nl> - out . resize ( static_cast < size_t > ( size ) ) ; <nl> - fs . read ( & out [ 0 ] , size ) ; <nl> - } <nl> + const auto bufsiz = 16384 ; <nl> + char buff [ bufsiz ] ; <nl> + do { <nl> + strm . avail_out = bufsiz ; <nl> + strm . next_out = reinterpret_cast < Bytef * > ( buff ) ; <nl> + <nl> + ret = inflate ( & strm , Z_NO_FLUSH ) ; <nl> + assert ( ret ! = Z_STREAM_ERROR ) ; <nl> + switch ( ret ) { <nl> + case Z_NEED_DICT : <nl> + case Z_DATA_ERROR : <nl> + case Z_MEM_ERROR : inflateEnd ( & strm ) ; return false ; <nl> + } <nl> + <nl> + if ( ! callback ( buff , bufsiz - strm . avail_out ) ) { return false ; } <nl> + } while ( strm . avail_out = = 0 ) ; <nl> <nl> - inline std : : string file_extension ( const std : : string & path ) <nl> - { <nl> - std : : smatch m ; <nl> - auto pat = std : : regex ( " \ \ . ( [ a - zA - Z0 - 9 ] + ) $ " ) ; <nl> - if ( std : : regex_search ( path , m , pat ) ) { <nl> - return m [ 1 ] . str ( ) ; <nl> - } <nl> - return std : : string ( ) ; <nl> - } <nl> - <nl> - inline const char * find_content_type ( const std : : string & path ) <nl> - { <nl> - auto ext = file_extension ( path ) ; <nl> - if ( ext = = " txt " ) { <nl> - return " text / plain " ; <nl> - } else if ( ext = = " html " ) { <nl> - return " text / html " ; <nl> - } else if ( ext = = " css " ) { <nl> - return " text / css " ; <nl> - } else if ( ext = = " jpeg " | | ext = = " jpg " ) { <nl> - return " image / jpg " ; <nl> - } else if ( ext = = " png " ) { <nl> - return " image / png " ; <nl> - } else if ( ext = = " gif " ) { <nl> - return " image / gif " ; <nl> - } else if ( ext = = " svg " ) { <nl> - return " image / svg + xml " ; <nl> - } else if ( ext = = " ico " ) { <nl> - return " image / x - icon " ; <nl> - } else if ( ext = = " json " ) { <nl> - return " application / json " ; <nl> - } else if ( ext = = " pdf " ) { <nl> - return " application / pdf " ; <nl> - } else if ( ext = = " js " ) { <nl> - return " application / javascript " ; <nl> - } else if ( ext = = " xml " ) { <nl> - return " application / xml " ; <nl> - } else if ( ext = = " xhtml " ) { <nl> - return " application / xhtml + xml " ; <nl> - } <nl> - return nullptr ; <nl> - } <nl> - <nl> - inline const char * status_message ( int status ) <nl> - { <nl> - switch ( status ) { <nl> - case 200 : return " OK " ; <nl> - case 301 : return " Moved Permanently " ; <nl> - case 302 : return " Found " ; <nl> - case 303 : return " See Other " ; <nl> - case 304 : return " Not Modified " ; <nl> - case 400 : return " Bad Request " ; <nl> - case 403 : return " Forbidden " ; <nl> - case 404 : return " Not Found " ; <nl> - case 415 : return " Unsupported Media Type " ; <nl> - default : <nl> - case 500 : return " Internal Server Error " ; <nl> - } <nl> + return ret = = Z_STREAM_END ; <nl> + } <nl> + <nl> + private : <nl> + bool is_valid_ ; <nl> + z_stream strm ; <nl> + } ; <nl> + # endif <nl> + <nl> + inline bool has_header ( const Headers & headers , const char * key ) { <nl> + return headers . find ( key ) ! = headers . end ( ) ; <nl> } <nl> <nl> - inline const char * get_header_value ( const Headers & headers , const char * key , const char * def ) <nl> - { <nl> - auto it = headers . find ( key ) ; <nl> - if ( it ! = headers . end ( ) ) { <nl> - return it - > second . c_str ( ) ; <nl> - } <nl> - return def ; <nl> + inline const char * get_header_value ( const Headers & headers , const char * key , <nl> + size_t id = 0 , const char * def = nullptr ) { <nl> + auto it = headers . find ( key ) ; <nl> + std : : advance ( it , id ) ; <nl> + if ( it ! = headers . end ( ) ) { return it - > second . c_str ( ) ; } <nl> + return def ; <nl> } <nl> <nl> - inline int get_header_value_int ( const Headers & headers , const char * key , int def ) <nl> - { <nl> - auto it = headers . find ( key ) ; <nl> - if ( it ! = headers . end ( ) ) { <nl> - return std : : stoi ( it - > second ) ; <nl> - } <nl> - return def ; <nl> + inline uint64_t get_header_value_uint64 ( const Headers & headers , const char * key , <nl> + int def = 0 ) { <nl> + auto it = headers . find ( key ) ; <nl> + if ( it ! = headers . end ( ) ) { <nl> + return std : : strtoull ( it - > second . data ( ) , nullptr , 10 ) ; <nl> + } <nl> + return def ; <nl> } <nl> <nl> - inline bool read_headers ( Stream & strm , Headers & headers ) <nl> - { <nl> - static std : : regex re ( R " ( ( . + ? ) : \ s * ( . + ? ) \ s * \ r \ n ) " ) ; <nl> + inline bool read_headers ( Stream & strm , Headers & headers ) { <nl> + static std : : regex re ( R " ( ( . + ? ) : \ s * ( . + ? ) \ s * \ r \ n ) " ) ; <nl> <nl> - const auto bufsiz = 2048 ; <nl> - char buf [ bufsiz ] ; <nl> + const auto bufsiz = 2048 ; <nl> + char buf [ bufsiz ] ; <nl> <nl> - stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> + stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> <nl> - for ( ; ; ) { <nl> - if ( ! reader . getline ( ) ) { <nl> - return false ; <nl> - } <nl> - if ( ! strcmp ( reader . ptr ( ) , " \ r \ n " ) ) { <nl> - break ; <nl> - } <nl> - std : : cmatch m ; <nl> - if ( std : : regex_match ( reader . ptr ( ) , m , re ) ) { <nl> - auto key = std : : string ( m [ 1 ] ) ; <nl> - auto val = std : : string ( m [ 2 ] ) ; <nl> - headers . emplace ( key , val ) ; <nl> - } <nl> + for ( ; ; ) { <nl> + if ( ! reader . getline ( ) ) { return false ; } <nl> + if ( ! strcmp ( reader . ptr ( ) , " \ r \ n " ) ) { break ; } <nl> + std : : cmatch m ; <nl> + if ( std : : regex_match ( reader . ptr ( ) , m , re ) ) { <nl> + auto key = std : : string ( m [ 1 ] ) ; <nl> + auto val = std : : string ( m [ 2 ] ) ; <nl> + headers . emplace ( key , val ) ; <nl> } <nl> + } <nl> <nl> - return true ; <nl> + return true ; <nl> } <nl> <nl> - inline bool read_content_with_length ( Stream & strm , std : : string & out , size_t len , Progress progress ) <nl> - { <nl> - out . assign ( len , 0 ) ; <nl> - size_t r = 0 ; <nl> - while ( r < len ) { <nl> - auto n = strm . read ( & out [ r ] , len - r ) ; <nl> - if ( n < = 0 ) { <nl> - return false ; <nl> - } <nl> + typedef std : : function < bool ( const char * data , size_t data_length ) > <nl> + ContentReceiverCore ; <nl> <nl> - r + = n ; <nl> + inline bool read_content_with_length ( Stream & strm , uint64_t len , <nl> + Progress progress , <nl> + ContentReceiverCore out ) { <nl> + char buf [ CPPHTTPLIB_RECV_BUFSIZ ] ; <nl> <nl> - if ( progress ) { <nl> - progress ( r , len ) ; <nl> - } <nl> - } <nl> + uint64_t r = 0 ; <nl> + while ( r < len ) { <nl> + auto read_len = static_cast < size_t > ( len - r ) ; <nl> + auto n = strm . read ( buf , std : : min ( read_len , CPPHTTPLIB_RECV_BUFSIZ ) ) ; <nl> + if ( n < = 0 ) { return false ; } <nl> <nl> - return true ; <nl> - } <nl> + if ( ! out ( buf , n ) ) { return false ; } <nl> <nl> - inline bool read_content_without_length ( Stream & strm , std : : string & out ) <nl> - { <nl> - for ( ; ; ) { <nl> - char byte ; <nl> - auto n = strm . read ( & byte , 1 ) ; <nl> - if ( n < 0 ) { <nl> - return false ; <nl> - } else if ( n = = 0 ) { <nl> - return true ; <nl> - } <nl> - out + = byte ; <nl> + r + = n ; <nl> + <nl> + if ( progress ) { <nl> + if ( ! progress ( r , len ) ) { return false ; } <nl> } <nl> + } <nl> <nl> - return true ; <nl> + return true ; <nl> } <nl> <nl> - inline bool read_content_chunked ( Stream & strm , std : : string & out ) <nl> - { <nl> - const auto bufsiz = 16 ; <nl> - char buf [ bufsiz ] ; <nl> - <nl> - stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> + inline void skip_content_with_length ( Stream & strm , uint64_t len ) { <nl> + char buf [ CPPHTTPLIB_RECV_BUFSIZ ] ; <nl> + uint64_t r = 0 ; <nl> + while ( r < len ) { <nl> + auto read_len = static_cast < size_t > ( len - r ) ; <nl> + auto n = strm . read ( buf , std : : min ( read_len , CPPHTTPLIB_RECV_BUFSIZ ) ) ; <nl> + if ( n < = 0 ) { return ; } <nl> + r + = n ; <nl> + } <nl> + } <nl> <nl> - if ( ! reader . getline ( ) ) { <nl> - return false ; <nl> + inline bool read_content_without_length ( Stream & strm , ContentReceiverCore out ) { <nl> + char buf [ CPPHTTPLIB_RECV_BUFSIZ ] ; <nl> + for ( ; ; ) { <nl> + auto n = strm . read ( buf , CPPHTTPLIB_RECV_BUFSIZ ) ; <nl> + if ( n < 0 ) { <nl> + return false ; <nl> + } else if ( n = = 0 ) { <nl> + return true ; <nl> } <nl> + if ( ! out ( buf , n ) ) { return false ; } <nl> + } <nl> <nl> - auto chunk_len = std : : stoi ( reader . ptr ( ) , 0 , 16 ) ; <nl> - <nl> - while ( chunk_len > 0 ) { <nl> - std : : string chunk ; <nl> - if ( ! read_content_with_length ( strm , chunk , chunk_len , nullptr ) ) { <nl> - return false ; <nl> - } <nl> + return true ; <nl> + } <nl> <nl> - if ( ! reader . getline ( ) ) { <nl> - return false ; <nl> - } <nl> + inline bool read_content_chunked ( Stream & strm , ContentReceiverCore out ) { <nl> + const auto bufsiz = 16 ; <nl> + char buf [ bufsiz ] ; <nl> <nl> - if ( strcmp ( reader . ptr ( ) , " \ r \ n " ) ) { <nl> - break ; <nl> - } <nl> + stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> <nl> - out + = chunk ; <nl> + if ( ! reader . getline ( ) ) { return false ; } <nl> <nl> - if ( ! reader . getline ( ) ) { <nl> - return false ; <nl> - } <nl> + auto chunk_len = std : : stoi ( reader . ptr ( ) , 0 , 16 ) ; <nl> <nl> - chunk_len = std : : stoi ( reader . ptr ( ) , 0 , 16 ) ; <nl> + while ( chunk_len > 0 ) { <nl> + if ( ! read_content_with_length ( strm , chunk_len , nullptr , out ) ) { <nl> + return false ; <nl> } <nl> <nl> - if ( chunk_len = = 0 ) { <nl> - / / Reader terminator after chunks <nl> - if ( ! reader . getline ( ) | | strcmp ( reader . ptr ( ) , " \ r \ n " ) ) <nl> - return false ; <nl> - } <nl> + if ( ! reader . getline ( ) ) { return false ; } <nl> <nl> - return true ; <nl> - } <nl> + if ( strcmp ( reader . ptr ( ) , " \ r \ n " ) ) { break ; } <nl> <nl> - template < typename T > <nl> - bool read_content ( Stream & strm , T & x , Progress progress = Progress ( ) ) <nl> - { <nl> - auto len = get_header_value_int ( x . headers , " Content - Length " , 0 ) ; <nl> + if ( ! reader . getline ( ) ) { return false ; } <nl> <nl> - if ( len ) { <nl> - return read_content_with_length ( strm , x . body , len , progress ) ; <nl> - } else { <nl> - const auto & encoding = get_header_value ( x . headers , " Transfer - Encoding " , " " ) ; <nl> + chunk_len = std : : stoi ( reader . ptr ( ) , 0 , 16 ) ; <nl> + } <nl> <nl> - if ( ! strcasecmp ( encoding , " chunked " ) ) { <nl> - return read_content_chunked ( strm , x . body ) ; <nl> - } else { <nl> - return read_content_without_length ( strm , x . body ) ; <nl> - } <nl> - } <nl> + if ( chunk_len = = 0 ) { <nl> + / / Reader terminator after chunks <nl> + if ( ! reader . getline ( ) | | strcmp ( reader . ptr ( ) , " \ r \ n " ) ) return false ; <nl> + } <nl> <nl> - return true ; <nl> + return true ; <nl> + } <nl> + <nl> + inline bool is_chunked_transfer_encoding ( const Headers & headers ) { <nl> + return ! strcasecmp ( get_header_value ( headers , " Transfer - Encoding " , 0 , " " ) , <nl> + " chunked " ) ; <nl> } <nl> <nl> template < typename T > <nl> - inline void write_headers ( Stream & strm , const T & info ) <nl> - { <nl> - for ( const auto & x : info . headers ) { <nl> - strm . write_format ( " % s : % s \ r \ n " , x . first . c_str ( ) , x . second . c_str ( ) ) ; <nl> - } <nl> - strm . write ( " \ r \ n " ) ; <nl> - } <nl> - <nl> - inline std : : string encode_url ( const std : : string & s ) <nl> - { <nl> - std : : string result ; <nl> - <nl> - for ( auto i = 0 ; s [ i ] ; i + + ) { <nl> - switch ( s [ i ] ) { <nl> - case ' ' : result + = " + " ; break ; <nl> - case ' \ ' ' : result + = " % 27 " ; break ; <nl> - case ' , ' : result + = " % 2C " ; break ; <nl> - case ' : ' : result + = " % 3A " ; break ; <nl> - case ' ; ' : result + = " % 3B " ; break ; <nl> - default : <nl> - if ( s [ i ] < 0 ) { <nl> - result + = ' % ' ; <nl> - char hex [ 4 ] ; <nl> - size_t len = snprintf ( hex , sizeof ( hex ) - 1 , " % 02X " , ( unsigned char ) s [ i ] ) ; <nl> - assert ( len = = 2 ) ; <nl> - result . append ( hex , len ) ; <nl> - } else { <nl> - result + = s [ i ] ; <nl> - } <nl> - break ; <nl> - } <nl> - } <nl> + bool read_content ( Stream & strm , T & x , size_t payload_max_length , int & status , <nl> + Progress progress , ContentReceiverCore receiver ) { <nl> <nl> - return result ; <nl> - } <nl> + ContentReceiverCore out = [ & ] ( const char * buf , size_t n ) { <nl> + return receiver ( buf , n ) ; <nl> + } ; <nl> <nl> - inline bool is_hex ( char c , int & v ) <nl> - { <nl> - if ( 0x20 < = c & & isdigit ( c ) ) { <nl> - v = c - ' 0 ' ; <nl> - return true ; <nl> - } else if ( ' A ' < = c & & c < = ' F ' ) { <nl> - v = c - ' A ' + 10 ; <nl> - return true ; <nl> - } else if ( ' a ' < = c & & c < = ' f ' ) { <nl> - v = c - ' a ' + 10 ; <nl> - return true ; <nl> - } <nl> + # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> + detail : : decompressor decompressor ; <nl> + <nl> + if ( ! decompressor . is_valid ( ) ) { <nl> + status = 500 ; <nl> return false ; <nl> - } <nl> + } <nl> + <nl> + if ( x . get_header_value ( " Content - Encoding " ) = = " gzip " ) { <nl> + out = [ & ] ( const char * buf , size_t n ) { <nl> + return decompressor . decompress ( <nl> + buf , n , [ & ] ( const char * buf , size_t n ) { return receiver ( buf , n ) ; } ) ; <nl> + } ; <nl> + } <nl> + # else <nl> + if ( x . get_header_value ( " Content - Encoding " ) = = " gzip " ) { <nl> + status = 415 ; <nl> + return false ; <nl> + } <nl> + # endif <nl> <nl> - inline bool from_hex_to_i ( const std : : string & s , size_t i , size_t cnt , int & val ) <nl> - { <nl> - if ( i > = s . size ( ) ) { <nl> - return false ; <nl> - } <nl> + auto ret = true ; <nl> + auto exceed_payload_max_length = false ; <nl> <nl> - val = 0 ; <nl> - for ( ; cnt ; i + + , cnt - - ) { <nl> - if ( ! s [ i ] ) { <nl> - return false ; <nl> - } <nl> - int v = 0 ; <nl> - if ( is_hex ( s [ i ] , v ) ) { <nl> - val = val * 16 + v ; <nl> - } else { <nl> - return false ; <nl> - } <nl> + if ( is_chunked_transfer_encoding ( x . headers ) ) { <nl> + ret = read_content_chunked ( strm , out ) ; <nl> + } else if ( ! has_header ( x . headers , " Content - Length " ) ) { <nl> + ret = read_content_without_length ( strm , out ) ; <nl> + } else { <nl> + auto len = get_header_value_uint64 ( x . headers , " Content - Length " , 0 ) ; <nl> + if ( len > payload_max_length ) { <nl> + exceed_payload_max_length = true ; <nl> + skip_content_with_length ( strm , len ) ; <nl> + ret = false ; <nl> + } else if ( len > 0 ) { <nl> + ret = read_content_with_length ( strm , len , progress , out ) ; <nl> } <nl> - return true ; <nl> + } <nl> + <nl> + if ( ! ret ) { status = exceed_payload_max_length ? 413 : 400 ; } <nl> + <nl> + return ret ; <nl> } <nl> <nl> - inline size_t to_utf8 ( int code , char * buff ) <nl> - { <nl> - if ( code < 0x0080 ) { <nl> - buff [ 0 ] = ( code & 0x7F ) ; <nl> - return 1 ; <nl> - } else if ( code < 0x0800 ) { <nl> - buff [ 0 ] = ( 0xC0 | ( ( code > > 6 ) & 0x1F ) ) ; <nl> - buff [ 1 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> - return 2 ; <nl> - } else if ( code < 0xD800 ) { <nl> - buff [ 0 ] = ( 0xE0 | ( ( code > > 12 ) & 0xF ) ) ; <nl> - buff [ 1 ] = ( 0x80 | ( ( code > > 6 ) & 0x3F ) ) ; <nl> - buff [ 2 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> - return 3 ; <nl> - } else if ( code < 0xE000 ) { / / D800 - DFFF is invalid . . . <nl> - return 0 ; <nl> - } else if ( code < 0x10000 ) { <nl> - buff [ 0 ] = ( 0xE0 | ( ( code > > 12 ) & 0xF ) ) ; <nl> - buff [ 1 ] = ( 0x80 | ( ( code > > 6 ) & 0x3F ) ) ; <nl> - buff [ 2 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> - return 3 ; <nl> - } else if ( code < 0x110000 ) { <nl> - buff [ 0 ] = ( 0xF0 | ( ( code > > 18 ) & 0x7 ) ) ; <nl> - buff [ 1 ] = ( 0x80 | ( ( code > > 12 ) & 0x3F ) ) ; <nl> - buff [ 2 ] = ( 0x80 | ( ( code > > 6 ) & 0x3F ) ) ; <nl> - buff [ 3 ] = ( 0x80 | ( code & 0x3F ) ) ; <nl> - return 4 ; <nl> - } <nl> + template < typename T > <nl> + inline int write_headers ( Stream & strm , const T & info , const Headers & headers ) { <nl> + auto write_len = 0 ; <nl> + for ( const auto & x : info . headers ) { <nl> + auto len = <nl> + strm . write_format ( " % s : % s \ r \ n " , x . first . c_str ( ) , x . second . c_str ( ) ) ; <nl> + if ( len < 0 ) { return len ; } <nl> + write_len + = len ; <nl> + } <nl> + for ( const auto & x : headers ) { <nl> + auto len = <nl> + strm . write_format ( " % s : % s \ r \ n " , x . first . c_str ( ) , x . second . c_str ( ) ) ; <nl> + if ( len < 0 ) { return len ; } <nl> + write_len + = len ; <nl> + } <nl> + auto len = strm . write ( " \ r \ n " ) ; <nl> + if ( len < 0 ) { return len ; } <nl> + write_len + = len ; <nl> + return write_len ; <nl> + } <nl> + <nl> + inline ssize_t write_content ( Stream & strm , ContentProvider content_provider , <nl> + size_t offset , size_t length ) { <nl> + size_t begin_offset = offset ; <nl> + size_t end_offset = offset + length ; <nl> + while ( offset < end_offset ) { <nl> + ssize_t written_length = 0 ; <nl> + content_provider ( <nl> + offset , end_offset - offset , <nl> + [ & ] ( const char * d , size_t l ) { <nl> + offset + = l ; <nl> + written_length = strm . write ( d , l ) ; <nl> + } , <nl> + [ & ] ( void ) { written_length = - 1 ; } ) ; <nl> + if ( written_length < 0 ) { return written_length ; } <nl> + } <nl> + return static_cast < ssize_t > ( offset - begin_offset ) ; <nl> + } <nl> + <nl> + inline ssize_t write_content_chunked ( Stream & strm , <nl> + ContentProvider content_provider ) { <nl> + size_t offset = 0 ; <nl> + auto data_available = true ; <nl> + ssize_t total_written_length = 0 ; <nl> + while ( data_available ) { <nl> + ssize_t written_length = 0 ; <nl> + content_provider ( <nl> + offset , 0 , <nl> + [ & ] ( const char * d , size_t l ) { <nl> + data_available = l > 0 ; <nl> + offset + = l ; <nl> + <nl> + / / Emit chunked response header and footer for each chunk <nl> + auto chunk = from_i_to_hex ( l ) + " \ r \ n " + std : : string ( d , l ) + " \ r \ n " ; <nl> + written_length = strm . write ( chunk ) ; <nl> + } , <nl> + [ & ] ( void ) { <nl> + data_available = false ; <nl> + written_length = strm . write ( " 0 \ r \ n \ r \ n " ) ; <nl> + } ) ; <nl> <nl> - / / NOTREACHED <nl> - return 0 ; <nl> + if ( written_length < 0 ) { return written_length ; } <nl> + total_written_length + = written_length ; <nl> + } <nl> + return total_written_length ; <nl> } <nl> <nl> - inline std : : string decode_url ( const std : : string & s ) <nl> - { <nl> - std : : string result ; <nl> - <nl> - for ( size_t i = 0 ; i < s . size ( ) ; i + + ) { <nl> - if ( s [ i ] = = ' % ' & & i + 1 < s . size ( ) ) { <nl> - if ( s [ i + 1 ] = = ' u ' ) { <nl> - int val = 0 ; <nl> - if ( from_hex_to_i ( s , i + 2 , 4 , val ) ) { <nl> - / / 4 digits Unicode codes <nl> - char buff [ 4 ] ; <nl> - size_t len = to_utf8 ( val , buff ) ; <nl> - if ( len > 0 ) { <nl> - result . append ( buff , len ) ; <nl> - } <nl> - i + = 5 ; / / ' u0000 ' <nl> - } else { <nl> - result + = s [ i ] ; <nl> - } <nl> - } else { <nl> - int val = 0 ; <nl> - if ( from_hex_to_i ( s , i + 1 , 2 , val ) ) { <nl> - / / 2 digits hex codes <nl> - result + = val ; <nl> - i + = 2 ; / / ' 00 ' <nl> - } else { <nl> - result + = s [ i ] ; <nl> - } <nl> - } <nl> - } else if ( s [ i ] = = ' + ' ) { <nl> - result + = ' ' ; <nl> + template < typename T > <nl> + inline bool redirect ( T & cli , const Request & req , Response & res , <nl> + const std : : string & path ) { <nl> + Request new_req ; <nl> + new_req . method = req . method ; <nl> + new_req . path = path ; <nl> + new_req . headers = req . headers ; <nl> + new_req . body = req . body ; <nl> + new_req . redirect_count = req . redirect_count - 1 ; <nl> + new_req . response_handler = req . response_handler ; <nl> + new_req . content_receiver = req . content_receiver ; <nl> + new_req . progress = req . progress ; <nl> + <nl> + Response new_res ; <nl> + auto ret = cli . send ( new_req , new_res ) ; <nl> + if ( ret ) { res = new_res ; } <nl> + return ret ; <nl> + } <nl> + <nl> + inline std : : string encode_url ( const std : : string & s ) { <nl> + std : : string result ; <nl> + <nl> + for ( auto i = 0 ; s [ i ] ; i + + ) { <nl> + switch ( s [ i ] ) { <nl> + case ' ' : result + = " % 20 " ; break ; <nl> + case ' + ' : result + = " % 2B " ; break ; <nl> + case ' \ r ' : result + = " % 0D " ; break ; <nl> + case ' \ n ' : result + = " % 0A " ; break ; <nl> + case ' \ ' ' : result + = " % 27 " ; break ; <nl> + case ' , ' : result + = " % 2C " ; break ; <nl> + case ' : ' : result + = " % 3A " ; break ; <nl> + case ' ; ' : result + = " % 3B " ; break ; <nl> + default : <nl> + auto c = static_cast < uint8_t > ( s [ i ] ) ; <nl> + if ( c > = 0x80 ) { <nl> + result + = ' % ' ; <nl> + char hex [ 4 ] ; <nl> + size_t len = snprintf ( hex , sizeof ( hex ) - 1 , " % 02X " , c ) ; <nl> + assert ( len = = 2 ) ; <nl> + result . append ( hex , len ) ; <nl> + } else { <nl> + result + = s [ i ] ; <nl> + } <nl> + break ; <nl> + } <nl> + } <nl> + <nl> + return result ; <nl> + } <nl> + <nl> + inline std : : string decode_url ( const std : : string & s ) { <nl> + std : : string result ; <nl> + <nl> + for ( size_t i = 0 ; i < s . size ( ) ; i + + ) { <nl> + if ( s [ i ] = = ' % ' & & i + 1 < s . size ( ) ) { <nl> + if ( s [ i + 1 ] = = ' u ' ) { <nl> + int val = 0 ; <nl> + if ( from_hex_to_i ( s , i + 2 , 4 , val ) ) { <nl> + / / 4 digits Unicode codes <nl> + char buff [ 4 ] ; <nl> + size_t len = to_utf8 ( val , buff ) ; <nl> + if ( len > 0 ) { result . append ( buff , len ) ; } <nl> + i + = 5 ; / / ' u0000 ' <nl> + } else { <nl> + result + = s [ i ] ; <nl> + } <nl> + } else { <nl> + int val = 0 ; <nl> + if ( from_hex_to_i ( s , i + 1 , 2 , val ) ) { <nl> + / / 2 digits hex codes <nl> + result + = static_cast < char > ( val ) ; <nl> + i + = 2 ; / / ' 00 ' <nl> } else { <nl> - result + = s [ i ] ; <nl> + result + = s [ i ] ; <nl> } <nl> + } <nl> + } else if ( s [ i ] = = ' + ' ) { <nl> + result + = ' ' ; <nl> + } else { <nl> + result + = s [ i ] ; <nl> } <nl> + } <nl> <nl> - return result ; <nl> + return result ; <nl> } <nl> <nl> - inline void parse_query_text ( const std : : string & s , Params & params ) <nl> - { <nl> - split ( & s [ 0 ] , & s [ s . size ( ) ] , ' & ' , [ & ] ( const char * b , const char * e ) { <nl> - std : : string key ; <nl> - std : : string val ; <nl> - split ( b , e , ' = ' , [ & ] ( const char * b , const char * e ) { <nl> - if ( key . empty ( ) ) { <nl> - key . assign ( b , e ) ; <nl> - } else { <nl> - val . assign ( b , e ) ; <nl> - } <nl> - } ) ; <nl> - params . emplace ( key , decode_url ( val ) ) ; <nl> + inline void parse_query_text ( const std : : string & s , Params & params ) { <nl> + split ( & s [ 0 ] , & s [ s . size ( ) ] , ' & ' , [ & ] ( const char * b , const char * e ) { <nl> + std : : string key ; <nl> + std : : string val ; <nl> + split ( b , e , ' = ' , [ & ] ( const char * b , const char * e ) { <nl> + if ( key . empty ( ) ) { <nl> + key . assign ( b , e ) ; <nl> + } else { <nl> + val . assign ( b , e ) ; <nl> + } <nl> } ) ; <nl> + params . emplace ( key , decode_url ( val ) ) ; <nl> + } ) ; <nl> } <nl> <nl> - inline bool parse_multipart_boundary ( const std : : string & content_type , std : : string & boundary ) <nl> - { <nl> - auto pos = content_type . find ( " boundary = " ) ; <nl> - if ( pos = = std : : string : : npos ) { <nl> - return false ; <nl> - } <nl> + inline bool parse_multipart_boundary ( const std : : string & content_type , <nl> + std : : string & boundary ) { <nl> + auto pos = content_type . find ( " boundary = " ) ; <nl> + if ( pos = = std : : string : : npos ) { return false ; } <nl> <nl> - boundary = content_type . substr ( pos + 9 ) ; <nl> - return true ; <nl> + boundary = content_type . substr ( pos + 9 ) ; <nl> + return true ; <nl> } <nl> <nl> - inline bool parse_multipart_formdata ( <nl> - const std : : string & boundary , const std : : string & body , MultipartFiles & files ) <nl> - { <nl> - static std : : string dash = " - - " ; <nl> - static std : : string crlf = " \ r \ n " ; <nl> + inline bool parse_multipart_formdata ( const std : : string & boundary , <nl> + const std : : string & body , <nl> + MultipartFiles & files ) { <nl> + static std : : string dash = " - - " ; <nl> + static std : : string crlf = " \ r \ n " ; <nl> <nl> - static std : : regex re_content_type ( <nl> - " Content - Type : ( . * ? ) " , std : : regex_constants : : icase ) ; <nl> + static std : : regex re_content_type ( " Content - Type : ( . * ? ) " , <nl> + std : : regex_constants : : icase ) ; <nl> <nl> - static std : : regex re_content_disposition ( <nl> - " Content - Disposition : form - data ; name = \ " ( . * ? ) \ " ( ? : ; filename = \ " ( . * ? ) \ " ) ? " , <nl> - std : : regex_constants : : icase ) ; <nl> + static std : : regex re_content_disposition ( <nl> + " Content - Disposition : form - data ; name = \ " ( . * ? ) \ " ( ? : ; filename = \ " ( . * ? ) \ " ) ? " , <nl> + std : : regex_constants : : icase ) ; <nl> <nl> - auto dash_boundary = dash + boundary ; <nl> + auto dash_boundary = dash + boundary ; <nl> <nl> - auto pos = body . find ( dash_boundary ) ; <nl> - if ( pos ! = 0 ) { <nl> - return false ; <nl> - } <nl> + auto pos = body . find ( dash_boundary ) ; <nl> + if ( pos ! = 0 ) { return false ; } <nl> <nl> - pos + = dash_boundary . size ( ) ; <nl> + pos + = dash_boundary . size ( ) ; <nl> <nl> - auto next_pos = body . find ( crlf , pos ) ; <nl> - if ( next_pos = = std : : string : : npos ) { <nl> - return false ; <nl> - } <nl> + auto next_pos = body . find ( crlf , pos ) ; <nl> + if ( next_pos = = std : : string : : npos ) { return false ; } <nl> <nl> - pos = next_pos + crlf . size ( ) ; <nl> + pos = next_pos + crlf . size ( ) ; <nl> <nl> - while ( pos < body . size ( ) ) { <nl> - next_pos = body . find ( crlf , pos ) ; <nl> - if ( next_pos = = std : : string : : npos ) { <nl> - return false ; <nl> - } <nl> + while ( pos < body . size ( ) ) { <nl> + next_pos = body . find ( crlf , pos ) ; <nl> + if ( next_pos = = std : : string : : npos ) { return false ; } <nl> <nl> - std : : string name ; <nl> - MultipartFile file ; <nl> + std : : string name ; <nl> + MultipartFile file ; <nl> <nl> - auto header = body . substr ( pos , ( next_pos - pos ) ) ; <nl> + auto header = body . substr ( pos , ( next_pos - pos ) ) ; <nl> <nl> - while ( pos ! = next_pos ) { <nl> - std : : smatch m ; <nl> - if ( std : : regex_match ( header , m , re_content_type ) ) { <nl> - file . content_type = m [ 1 ] ; <nl> - } else if ( std : : regex_match ( header , m , re_content_disposition ) ) { <nl> - name = m [ 1 ] ; <nl> - file . filename = m [ 2 ] ; <nl> - } <nl> + while ( pos ! = next_pos ) { <nl> + std : : smatch m ; <nl> + if ( std : : regex_match ( header , m , re_content_type ) ) { <nl> + file . content_type = m [ 1 ] ; <nl> + } else if ( std : : regex_match ( header , m , re_content_disposition ) ) { <nl> + name = m [ 1 ] ; <nl> + file . filename = m [ 2 ] ; <nl> + } <nl> <nl> - pos = next_pos + crlf . size ( ) ; <nl> + pos = next_pos + crlf . size ( ) ; <nl> <nl> - next_pos = body . find ( crlf , pos ) ; <nl> - if ( next_pos = = std : : string : : npos ) { <nl> - return false ; <nl> - } <nl> + next_pos = body . find ( crlf , pos ) ; <nl> + if ( next_pos = = std : : string : : npos ) { return false ; } <nl> <nl> - header = body . substr ( pos , ( next_pos - pos ) ) ; <nl> - } <nl> + header = body . substr ( pos , ( next_pos - pos ) ) ; <nl> + } <nl> <nl> - pos = next_pos + crlf . size ( ) ; <nl> + pos = next_pos + crlf . size ( ) ; <nl> <nl> - next_pos = body . find ( crlf + dash_boundary , pos ) ; <nl> + next_pos = body . find ( crlf + dash_boundary , pos ) ; <nl> <nl> - if ( next_pos = = std : : string : : npos ) { <nl> - return false ; <nl> - } <nl> + if ( next_pos = = std : : string : : npos ) { return false ; } <nl> <nl> - file . offset = pos ; <nl> - file . length = next_pos - pos ; <nl> + file . offset = pos ; <nl> + file . length = next_pos - pos ; <nl> <nl> - pos = next_pos + crlf . size ( ) + dash_boundary . size ( ) ; <nl> + pos = next_pos + crlf . size ( ) + dash_boundary . size ( ) ; <nl> <nl> - next_pos = body . find ( crlf , pos ) ; <nl> - if ( next_pos = = std : : string : : npos ) { <nl> - return false ; <nl> - } <nl> + next_pos = body . find ( crlf , pos ) ; <nl> + if ( next_pos = = std : : string : : npos ) { return false ; } <nl> <nl> - files . emplace ( name , file ) ; <nl> + files . emplace ( name , file ) ; <nl> <nl> - pos = next_pos + crlf . size ( ) ; <nl> - } <nl> + pos = next_pos + crlf . size ( ) ; <nl> + } <nl> <nl> - return true ; <nl> + return true ; <nl> } <nl> <nl> - inline std : : string to_lower ( const char * beg , const char * end ) <nl> - { <nl> - std : : string out ; <nl> - auto it = beg ; <nl> - while ( it ! = end ) { <nl> - out + = : : tolower ( * it ) ; <nl> - it + + ; <nl> + inline bool parse_range_header ( const std : : string & s , Ranges & ranges ) { <nl> + try { <nl> + static auto re = std : : regex ( R " ( bytes = ( \ d * - \ d * ( ? : , \ s * \ d * - \ d * ) * ) ) " ) ; <nl> + std : : smatch m ; <nl> + if ( std : : regex_match ( s , m , re ) ) { <nl> + auto pos = m . position ( 1 ) ; <nl> + auto len = m . length ( 1 ) ; <nl> + detail : : split ( & s [ pos ] , & s [ pos + len ] , ' , ' , <nl> + [ & ] ( const char * b , const char * e ) { <nl> + static auto re = std : : regex ( R " ( \ s * ( \ d * ) - ( \ d * ) ) " ) ; <nl> + std : : cmatch m ; <nl> + if ( std : : regex_match ( b , e , m , re ) ) { <nl> + ssize_t first = - 1 ; <nl> + if ( ! m . str ( 1 ) . empty ( ) ) { <nl> + first = static_cast < ssize_t > ( std : : stoll ( m . str ( 1 ) ) ) ; <nl> + } <nl> + <nl> + ssize_t last = - 1 ; <nl> + if ( ! m . str ( 2 ) . empty ( ) ) { <nl> + last = static_cast < ssize_t > ( std : : stoll ( m . str ( 2 ) ) ) ; <nl> + } <nl> + <nl> + if ( first ! = - 1 & & last ! = - 1 & & first > last ) { <nl> + throw std : : runtime_error ( " invalid range error " ) ; <nl> + } <nl> + ranges . emplace_back ( std : : make_pair ( first , last ) ) ; <nl> + } <nl> + } ) ; <nl> + return true ; <nl> } <nl> - return out ; <nl> + return false ; <nl> + } catch ( . . . ) { return false ; } <nl> } <nl> <nl> - inline void make_range_header_core ( std : : string & ) { } <nl> + inline std : : string to_lower ( const char * beg , const char * end ) { <nl> + std : : string out ; <nl> + auto it = beg ; <nl> + while ( it ! = end ) { <nl> + out + = static_cast < char > ( : : tolower ( * it ) ) ; <nl> + it + + ; <nl> + } <nl> + return out ; <nl> + } <nl> <nl> - template < typename uint64_t > <nl> - inline void make_range_header_core ( std : : string & field , uint64_t value ) <nl> - { <nl> - if ( ! field . empty ( ) ) { <nl> - field + = " , " ; <nl> - } <nl> - field + = std : : to_string ( value ) + " - " ; <nl> + inline std : : string make_multipart_data_boundary ( ) { <nl> + static const char data [ ] = <nl> + " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz " ; <nl> + <nl> + std : : random_device seed_gen ; <nl> + std : : mt19937 engine ( seed_gen ( ) ) ; <nl> + <nl> + std : : string result = " - - cpp - httplib - multipart - data - " ; <nl> + <nl> + for ( auto i = 0 ; i < 16 ; i + + ) { <nl> + result + = data [ engine ( ) % ( sizeof ( data ) - 1 ) ] ; <nl> + } <nl> + <nl> + return result ; <nl> } <nl> <nl> - template < typename uint64_t , typename . . . Args > <nl> - inline void make_range_header_core ( std : : string & field , uint64_t value1 , uint64_t value2 , Args . . . args ) <nl> - { <nl> - if ( ! field . empty ( ) ) { <nl> - field + = " , " ; <nl> - } <nl> - field + = std : : to_string ( value1 ) + " - " + std : : to_string ( value2 ) ; <nl> - make_range_header_core ( field , args . . . ) ; <nl> + inline std : : pair < size_t , size_t > <nl> + get_range_offset_and_length ( const Request & req , size_t content_length , <nl> + size_t index ) { <nl> + auto r = req . ranges [ index ] ; <nl> + <nl> + if ( r . first = = - 1 & & r . second = = - 1 ) { <nl> + return std : : make_pair ( 0 , content_length ) ; <nl> + } <nl> + <nl> + if ( r . first = = - 1 ) { <nl> + r . first = content_length - r . second ; <nl> + r . second = content_length - 1 ; <nl> + } <nl> + <nl> + if ( r . second = = - 1 ) { r . second = content_length - 1 ; } <nl> + <nl> + return std : : make_pair ( r . first , r . second - r . first + 1 ) ; <nl> } <nl> <nl> - # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> - inline bool can_compress ( const std : : string & content_type ) { <nl> - return ! content_type . find ( " text / " ) | | <nl> - content_type = = " image / svg + xml " | | <nl> - content_type = = " application / javascript " | | <nl> - content_type = = " application / json " | | <nl> - content_type = = " application / xml " | | <nl> - content_type = = " application / xhtml + xml " ; <nl> - } <nl> - <nl> - inline void compress ( std : : string & content ) <nl> - { <nl> - z_stream strm ; <nl> - strm . zalloc = Z_NULL ; <nl> - strm . zfree = Z_NULL ; <nl> - strm . opaque = Z_NULL ; <nl> + inline std : : string make_content_range_header_field ( size_t offset , size_t length , <nl> + size_t content_length ) { <nl> + std : : string field = " bytes " ; <nl> + field + = std : : to_string ( offset ) ; <nl> + field + = " - " ; <nl> + field + = std : : to_string ( offset + length - 1 ) ; <nl> + field + = " / " ; <nl> + field + = std : : to_string ( content_length ) ; <nl> + return field ; <nl> + } <nl> <nl> - auto ret = deflateInit2 ( & strm , Z_DEFAULT_COMPRESSION , Z_DEFLATED , 31 , 8 , Z_DEFAULT_STRATEGY ) ; <nl> - if ( ret ! = Z_OK ) { <nl> - return ; <nl> + template < typename SToken , typename CToken , typename Content > <nl> + bool process_multipart_ranges_data ( const Request & req , Response & res , <nl> + const std : : string & boundary , <nl> + const std : : string & content_type , <nl> + SToken stoken , CToken ctoken , <nl> + Content content ) { <nl> + for ( size_t i = 0 ; i < req . ranges . size ( ) ; i + + ) { <nl> + ctoken ( " - - " ) ; <nl> + stoken ( boundary ) ; <nl> + ctoken ( " \ r \ n " ) ; <nl> + if ( ! content_type . empty ( ) ) { <nl> + ctoken ( " Content - Type : " ) ; <nl> + stoken ( content_type ) ; <nl> + ctoken ( " \ r \ n " ) ; <nl> } <nl> <nl> - strm . avail_in = content . size ( ) ; <nl> - strm . next_in = ( Bytef * ) content . data ( ) ; <nl> + auto offsets = detail : : get_range_offset_and_length ( req , res . body . size ( ) , i ) ; <nl> + auto offset = offsets . first ; <nl> + auto length = offsets . second ; <nl> <nl> - std : : string compressed ; <nl> + ctoken ( " Content - Range : " ) ; <nl> + stoken ( make_content_range_header_field ( offset , length , res . body . size ( ) ) ) ; <nl> + ctoken ( " \ r \ n " ) ; <nl> + ctoken ( " \ r \ n " ) ; <nl> + if ( ! content ( offset , length ) ) { return false ; } <nl> + ctoken ( " \ r \ n " ) ; <nl> + } <nl> <nl> - const auto bufsiz = 16384 ; <nl> - char buff [ bufsiz ] ; <nl> - do { <nl> - strm . avail_out = bufsiz ; <nl> - strm . next_out = ( Bytef * ) buff ; <nl> - deflate ( & strm , Z_FINISH ) ; <nl> - compressed . append ( buff , bufsiz - strm . avail_out ) ; <nl> - } while ( strm . avail_out = = 0 ) ; <nl> + ctoken ( " - - " ) ; <nl> + stoken ( boundary ) ; <nl> + ctoken ( " - - \ r \ n " ) ; <nl> <nl> - content . swap ( compressed ) ; <nl> + return true ; <nl> + } <nl> + <nl> + inline std : : string make_multipart_ranges_data ( const Request & req , Response & res , <nl> + const std : : string & boundary , <nl> + const std : : string & content_type ) { <nl> + std : : string data ; <nl> + <nl> + process_multipart_ranges_data ( <nl> + req , res , boundary , content_type , <nl> + [ & ] ( const std : : string & token ) { data + = token ; } , <nl> + [ & ] ( const char * token ) { data + = token ; } , <nl> + [ & ] ( size_t offset , size_t length ) { <nl> + data + = res . body . substr ( offset , length ) ; <nl> + return true ; <nl> + } ) ; <nl> <nl> - deflateEnd ( & strm ) ; <nl> + return data ; <nl> } <nl> <nl> - inline void decompress ( std : : string & content ) <nl> - { <nl> - z_stream strm ; <nl> - strm . zalloc = Z_NULL ; <nl> - strm . zfree = Z_NULL ; <nl> - strm . opaque = Z_NULL ; <nl> + inline size_t <nl> + get_multipart_ranges_data_length ( const Request & req , Response & res , <nl> + const std : : string & boundary , <nl> + const std : : string & content_type ) { <nl> + size_t data_length = 0 ; <nl> <nl> - / / 15 is the value of wbits , which should be at the maximum possible value to ensure <nl> - / / that any gzip stream can be decoded . The offset of 16 specifies that the stream <nl> - / / to decompress will be formatted with a gzip wrapper . <nl> - auto ret = inflateInit2 ( & strm , 16 + 15 ) ; <nl> - if ( ret ! = Z_OK ) { <nl> - return ; <nl> - } <nl> + process_multipart_ranges_data ( <nl> + req , res , boundary , content_type , <nl> + [ & ] ( const std : : string & token ) { data_length + = token . size ( ) ; } , <nl> + [ & ] ( const char * token ) { data_length + = strlen ( token ) ; } , <nl> + [ & ] ( size_t / * offset * / , size_t length ) { <nl> + data_length + = length ; <nl> + return true ; <nl> + } ) ; <nl> <nl> - strm . avail_in = content . size ( ) ; <nl> - strm . next_in = ( Bytef * ) content . data ( ) ; <nl> + return data_length ; <nl> + } <nl> <nl> - std : : string decompressed ; <nl> + inline bool write_multipart_ranges_data ( Stream & strm , const Request & req , <nl> + Response & res , <nl> + const std : : string & boundary , <nl> + const std : : string & content_type ) { <nl> + return process_multipart_ranges_data ( <nl> + req , res , boundary , content_type , <nl> + [ & ] ( const std : : string & token ) { strm . write ( token ) ; } , <nl> + [ & ] ( const char * token ) { strm . write ( token ) ; } , <nl> + [ & ] ( size_t offset , size_t length ) { <nl> + return detail : : write_content ( strm , res . content_provider , offset , <nl> + length ) > = 0 ; <nl> + } ) ; <nl> + } <nl> <nl> - const auto bufsiz = 16384 ; <nl> - char buff [ bufsiz ] ; <nl> - do { <nl> - strm . avail_out = bufsiz ; <nl> - strm . next_out = ( Bytef * ) buff ; <nl> - inflate ( & strm , Z_NO_FLUSH ) ; <nl> - decompressed . append ( buff , bufsiz - strm . avail_out ) ; <nl> - } while ( strm . avail_out = = 0 ) ; <nl> + inline std : : pair < size_t , size_t > <nl> + get_range_offset_and_length ( const Request & req , const Response & res , <nl> + size_t index ) { <nl> + auto r = req . ranges [ index ] ; <nl> <nl> - content . swap ( decompressed ) ; <nl> + if ( r . second = = - 1 ) { r . second = res . content_provider_resource_length - 1 ; } <nl> <nl> - inflateEnd ( & strm ) ; <nl> + return std : : make_pair ( r . first , r . second - r . first + 1 ) ; <nl> } <nl> - # endif <nl> <nl> # ifdef _WIN32 <nl> class WSInit { <nl> public : <nl> - WSInit ( ) { <nl> - WSADATA wsaData ; <nl> - WSAStartup ( 0x0002 , & wsaData ) ; <nl> - } <nl> + WSInit ( ) { <nl> + WSADATA wsaData ; <nl> + WSAStartup ( 0x0002 , & wsaData ) ; <nl> + } <nl> <nl> - ~ WSInit ( ) { <nl> - WSACleanup ( ) ; <nl> - } <nl> + ~ WSInit ( ) { WSACleanup ( ) ; } <nl> } ; <nl> <nl> static WSInit wsinit_ ; <nl> static WSInit wsinit_ ; <nl> } / / namespace detail <nl> <nl> / / Header utilities <nl> - template < typename uint64_t , typename . . . Args > <nl> - inline std : : pair < std : : string , std : : string > make_range_header ( uint64_t value , Args . . . args ) <nl> - { <nl> - std : : string field ; <nl> - detail : : make_range_header_core ( field , value , args . . . ) ; <nl> - field . insert ( 0 , " bytes = " ) ; <nl> - return std : : make_pair ( " Range " , field ) ; <nl> + inline std : : pair < std : : string , std : : string > make_range_header ( Ranges ranges ) { <nl> + std : : string field = " bytes = " ; <nl> + auto i = 0 ; <nl> + for ( auto r : ranges ) { <nl> + if ( i ! = 0 ) { field + = " , " ; } <nl> + if ( r . first ! = - 1 ) { field + = std : : to_string ( r . first ) ; } <nl> + field + = ' - ' ; <nl> + if ( r . second ! = - 1 ) { field + = std : : to_string ( r . second ) ; } <nl> + i + + ; <nl> + } <nl> + return std : : make_pair ( " Range " , field ) ; <nl> + } <nl> + <nl> + inline std : : pair < std : : string , std : : string > <nl> + make_basic_authentication_header ( const std : : string & username , <nl> + const std : : string & password ) { <nl> + auto field = " Basic " + detail : : base64_encode ( username + " : " + password ) ; <nl> + return std : : make_pair ( " Authorization " , field ) ; <nl> } <nl> <nl> / / Request implementation <nl> - inline bool Request : : has_header ( const char * key ) const <nl> - { <nl> - return headers . find ( key ) ! = headers . end ( ) ; <nl> + inline bool Request : : has_header ( const char * key ) const { <nl> + return detail : : has_header ( headers , key ) ; <nl> } <nl> <nl> - inline std : : string Request : : get_header_value ( const char * key ) const <nl> - { <nl> - return detail : : get_header_value ( headers , key , " " ) ; <nl> + inline std : : string Request : : get_header_value ( const char * key , size_t id ) const { <nl> + return detail : : get_header_value ( headers , key , id , " " ) ; <nl> } <nl> <nl> - inline void Request : : set_header ( const char * key , const char * val ) <nl> - { <nl> - headers . emplace ( key , val ) ; <nl> + inline size_t Request : : get_header_value_count ( const char * key ) const { <nl> + auto r = headers . equal_range ( key ) ; <nl> + return std : : distance ( r . first , r . second ) ; <nl> } <nl> <nl> - inline bool Request : : has_param ( const char * key ) const <nl> - { <nl> - return params . find ( key ) ! = params . end ( ) ; <nl> + inline void Request : : set_header ( const char * key , const char * val ) { <nl> + headers . emplace ( key , val ) ; <nl> } <nl> <nl> - inline std : : string Request : : get_param_value ( const char * key ) const <nl> - { <nl> - auto it = params . find ( key ) ; <nl> - if ( it ! = params . end ( ) ) { <nl> - return it - > second ; <nl> - } <nl> - return std : : string ( ) ; <nl> + inline void Request : : set_header ( const char * key , const std : : string & val ) { <nl> + headers . emplace ( key , val ) ; <nl> } <nl> <nl> - inline bool Request : : has_file ( const char * key ) const <nl> - { <nl> - return files . find ( key ) ! = files . end ( ) ; <nl> + inline bool Request : : has_param ( const char * key ) const { <nl> + return params . find ( key ) ! = params . end ( ) ; <nl> } <nl> <nl> - inline MultipartFile Request : : get_file_value ( const char * key ) const <nl> - { <nl> - auto it = files . find ( key ) ; <nl> - if ( it ! = files . end ( ) ) { <nl> - return it - > second ; <nl> - } <nl> - return MultipartFile ( ) ; <nl> + inline std : : string Request : : get_param_value ( const char * key , size_t id ) const { <nl> + auto it = params . find ( key ) ; <nl> + std : : advance ( it , id ) ; <nl> + if ( it ! = params . end ( ) ) { return it - > second ; } <nl> + return std : : string ( ) ; <nl> + } <nl> + <nl> + inline size_t Request : : get_param_value_count ( const char * key ) const { <nl> + auto r = params . equal_range ( key ) ; <nl> + return std : : distance ( r . first , r . second ) ; <nl> + } <nl> + <nl> + inline bool Request : : has_file ( const char * key ) const { <nl> + return files . find ( key ) ! = files . end ( ) ; <nl> + } <nl> + <nl> + inline MultipartFile Request : : get_file_value ( const char * key ) const { <nl> + auto it = files . find ( key ) ; <nl> + if ( it ! = files . end ( ) ) { return it - > second ; } <nl> + return MultipartFile ( ) ; <nl> } <nl> <nl> / / Response implementation <nl> - inline bool Response : : has_header ( const char * key ) const <nl> - { <nl> - return headers . find ( key ) ! = headers . end ( ) ; <nl> + inline bool Response : : has_header ( const char * key ) const { <nl> + return headers . find ( key ) ! = headers . end ( ) ; <nl> + } <nl> + <nl> + inline std : : string Response : : get_header_value ( const char * key , <nl> + size_t id ) const { <nl> + return detail : : get_header_value ( headers , key , id , " " ) ; <nl> } <nl> <nl> - inline std : : string Response : : get_header_value ( const char * key ) const <nl> - { <nl> - return detail : : get_header_value ( headers , key , " " ) ; <nl> + inline size_t Response : : get_header_value_count ( const char * key ) const { <nl> + auto r = headers . equal_range ( key ) ; <nl> + return std : : distance ( r . first , r . second ) ; <nl> } <nl> <nl> - inline void Response : : set_header ( const char * key , const char * val ) <nl> - { <nl> - headers . emplace ( key , val ) ; <nl> + inline void Response : : set_header ( const char * key , const char * val ) { <nl> + headers . emplace ( key , val ) ; <nl> } <nl> <nl> - inline void Response : : set_redirect ( const char * url ) <nl> - { <nl> - set_header ( " Location " , url ) ; <nl> - status = 302 ; <nl> + inline void Response : : set_header ( const char * key , const std : : string & val ) { <nl> + headers . emplace ( key , val ) ; <nl> } <nl> <nl> - inline void Response : : set_content ( const char * s , size_t n , const char * content_type ) <nl> - { <nl> - body . assign ( s , n ) ; <nl> - set_header ( " Content - Type " , content_type ) ; <nl> + inline void Response : : set_redirect ( const char * url ) { <nl> + set_header ( " Location " , url ) ; <nl> + status = 302 ; <nl> } <nl> <nl> - inline void Response : : set_content ( const std : : string & s , const char * content_type ) <nl> - { <nl> - body = s ; <nl> - set_header ( " Content - Type " , content_type ) ; <nl> + inline void Response : : set_content ( const char * s , size_t n , <nl> + const char * content_type ) { <nl> + body . assign ( s , n ) ; <nl> + set_header ( " Content - Type " , content_type ) ; <nl> + } <nl> + <nl> + inline void Response : : set_content ( const std : : string & s , <nl> + const char * content_type ) { <nl> + body = s ; <nl> + set_header ( " Content - Type " , content_type ) ; <nl> + } <nl> + <nl> + inline void Response : : set_content_provider ( <nl> + size_t length , <nl> + std : : function < void ( size_t offset , size_t length , DataSink sink ) > provider , <nl> + std : : function < void ( ) > resource_releaser ) { <nl> + assert ( length > 0 ) ; <nl> + content_provider_resource_length = length ; <nl> + content_provider = [ provider ] ( size_t offset , size_t length , DataSink sink , <nl> + Done ) { provider ( offset , length , sink ) ; } ; <nl> + content_provider_resource_releaser = resource_releaser ; <nl> + } <nl> + <nl> + inline void Response : : set_chunked_content_provider ( <nl> + std : : function < void ( size_t offset , DataSink sink , Done done ) > provider , <nl> + std : : function < void ( ) > resource_releaser ) { <nl> + content_provider_resource_length = 0 ; <nl> + content_provider = [ provider ] ( size_t offset , size_t , DataSink sink , <nl> + Done done ) { provider ( offset , sink , done ) ; } ; <nl> + content_provider_resource_releaser = resource_releaser ; <nl> } <nl> <nl> / / Rstream implementation <nl> - template < typename . . . Args > <nl> - inline void Stream : : write_format ( const char * fmt , const Args & . . . args ) <nl> - { <nl> - const auto bufsiz = 2048 ; <nl> - char buf [ bufsiz ] ; <nl> + template < typename . . . Args > <nl> + inline int Stream : : write_format ( const char * fmt , const Args & . . . args ) { <nl> + const auto bufsiz = 2048 ; <nl> + char buf [ bufsiz ] ; <nl> <nl> # if defined ( _MSC_VER ) & & _MSC_VER < 1900 <nl> - auto n = _snprintf_s ( buf , bufsiz , bufsiz - 1 , fmt , args . . . ) ; <nl> + auto n = _snprintf_s ( buf , bufsiz , bufsiz - 1 , fmt , args . . . ) ; <nl> # else <nl> - auto n = snprintf ( buf , bufsiz - 1 , fmt , args . . . ) ; <nl> + auto n = snprintf ( buf , bufsiz - 1 , fmt , args . . . ) ; <nl> # endif <nl> - if ( n > 0 ) { <nl> - if ( n > = bufsiz - 1 ) { <nl> - std : : vector < char > glowable_buf ( bufsiz ) ; <nl> + if ( n < = 0 ) { return n ; } <nl> <nl> - while ( n > = static_cast < int > ( glowable_buf . size ( ) - 1 ) ) { <nl> - glowable_buf . resize ( glowable_buf . size ( ) * 2 ) ; <nl> + if ( n > = bufsiz - 1 ) { <nl> + std : : vector < char > glowable_buf ( bufsiz ) ; <nl> + <nl> + while ( n > = static_cast < int > ( glowable_buf . size ( ) - 1 ) ) { <nl> + glowable_buf . resize ( glowable_buf . size ( ) * 2 ) ; <nl> # if defined ( _MSC_VER ) & & _MSC_VER < 1900 <nl> - n = _snprintf_s ( & glowable_buf [ 0 ] , glowable_buf . size ( ) , glowable_buf . size ( ) - 1 , fmt , args . . . ) ; <nl> + n = _snprintf_s ( & glowable_buf [ 0 ] , glowable_buf . size ( ) , <nl> + glowable_buf . size ( ) - 1 , fmt , args . . . ) ; <nl> # else <nl> - n = snprintf ( & glowable_buf [ 0 ] , glowable_buf . size ( ) - 1 , fmt , args . . . ) ; <nl> + n = snprintf ( & glowable_buf [ 0 ] , glowable_buf . size ( ) - 1 , fmt , args . . . ) ; <nl> # endif <nl> - } <nl> - write ( & glowable_buf [ 0 ] , n ) ; <nl> - } else { <nl> - write ( buf , n ) ; <nl> - } <nl> } <nl> + return write ( & glowable_buf [ 0 ] , n ) ; <nl> + } else { <nl> + return write ( buf , n ) ; <nl> + } <nl> } <nl> <nl> / / Socket stream implementation <nl> - inline SocketStream : : SocketStream ( socket_t sock ) : sock_ ( sock ) <nl> - { <nl> + inline SocketStream : : SocketStream ( socket_t sock ) : sock_ ( sock ) { } <nl> + <nl> + inline SocketStream : : ~ SocketStream ( ) { } <nl> + <nl> + inline int SocketStream : : read ( char * ptr , size_t size ) { <nl> + if ( detail : : select_read ( sock_ , CPPHTTPLIB_READ_TIMEOUT_SECOND , <nl> + CPPHTTPLIB_READ_TIMEOUT_USECOND ) > 0 ) { <nl> + return recv ( sock_ , ptr , static_cast < int > ( size ) , 0 ) ; <nl> + } <nl> + return - 1 ; <nl> + } <nl> + <nl> + inline int SocketStream : : write ( const char * ptr , size_t size ) { <nl> + return send ( sock_ , ptr , static_cast < int > ( size ) , 0 ) ; <nl> + } <nl> + <nl> + inline int SocketStream : : write ( const char * ptr ) { <nl> + return write ( ptr , strlen ( ptr ) ) ; <nl> } <nl> <nl> - inline SocketStream : : ~ SocketStream ( ) <nl> - { <nl> + inline int SocketStream : : write ( const std : : string & s ) { <nl> + return write ( s . data ( ) , s . size ( ) ) ; <nl> } <nl> <nl> - inline int SocketStream : : read ( char * ptr , size_t size ) <nl> - { <nl> - return recv ( sock_ , ptr , size , 0 ) ; <nl> + inline std : : string SocketStream : : get_remote_addr ( ) const { <nl> + return detail : : get_remote_addr ( sock_ ) ; <nl> } <nl> <nl> - inline int SocketStream : : write ( const char * ptr , size_t size ) <nl> - { <nl> - return send ( sock_ , ptr , size , 0 ) ; <nl> + / / Buffer stream implementation <nl> + inline int BufferStream : : read ( char * ptr , size_t size ) { <nl> + # if defined ( _MSC_VER ) & & _MSC_VER < 1900 <nl> + return static_cast < int > ( buffer . _Copy_s ( ptr , size , size ) ) ; <nl> + # else <nl> + return static_cast < int > ( buffer . copy ( ptr , size ) ) ; <nl> + # endif <nl> + } <nl> + <nl> + inline int BufferStream : : write ( const char * ptr , size_t size ) { <nl> + buffer . append ( ptr , size ) ; <nl> + return static_cast < int > ( size ) ; <nl> } <nl> <nl> - inline int SocketStream : : write ( const char * ptr ) <nl> - { <nl> - return write ( ptr , strlen ( ptr ) ) ; <nl> + inline int BufferStream : : write ( const char * ptr ) { <nl> + return write ( ptr , strlen ( ptr ) ) ; <nl> } <nl> <nl> - inline std : : string SocketStream : : get_remote_addr ( ) { <nl> - return detail : : get_remote_addr ( sock_ ) ; <nl> + inline int BufferStream : : write ( const std : : string & s ) { <nl> + return write ( s . data ( ) , s . size ( ) ) ; <nl> } <nl> <nl> + inline std : : string BufferStream : : get_remote_addr ( ) const { return " " ; } <nl> + <nl> + inline const std : : string & BufferStream : : get_buffer ( ) const { return buffer ; } <nl> + <nl> / / HTTP server implementation <nl> inline Server : : Server ( ) <nl> - : keep_alive_max_count_ ( 5 ) <nl> - , is_running_ ( false ) <nl> - , svr_sock_ ( INVALID_SOCKET ) <nl> - , running_threads_ ( 0 ) <nl> - { <nl> + : keep_alive_max_count_ ( CPPHTTPLIB_KEEPALIVE_MAX_COUNT ) , <nl> + payload_max_length_ ( CPPHTTPLIB_PAYLOAD_MAX_LENGTH ) , is_running_ ( false ) , <nl> + svr_sock_ ( INVALID_SOCKET ) { <nl> # ifndef _WIN32 <nl> - signal ( SIGPIPE , SIG_IGN ) ; <nl> + signal ( SIGPIPE , SIG_IGN ) ; <nl> + # endif <nl> + new_task_queue = [ ] { <nl> + # if CPPHTTPLIB_THREAD_POOL_COUNT > 0 <nl> + return new ThreadPool ( CPPHTTPLIB_THREAD_POOL_COUNT ) ; <nl> + # else <nl> + return new Threads ( ) ; <nl> # endif <nl> + } ; <nl> } <nl> <nl> - inline Server : : ~ Server ( ) <nl> - { <nl> + inline Server : : ~ Server ( ) { } <nl> + <nl> + inline Server & Server : : Get ( const char * pattern , Handler handler ) { <nl> + get_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> + return * this ; <nl> } <nl> <nl> - inline Server & Server : : Get ( const char * pattern , Handler handler ) <nl> - { <nl> - get_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> - return * this ; <nl> + inline Server & Server : : Post ( const char * pattern , Handler handler ) { <nl> + post_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> + return * this ; <nl> } <nl> <nl> - inline Server & Server : : Post ( const char * pattern , Handler handler ) <nl> - { <nl> - post_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> - return * this ; <nl> + inline Server & Server : : Put ( const char * pattern , Handler handler ) { <nl> + put_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> + return * this ; <nl> } <nl> <nl> - inline Server & Server : : Put ( const char * pattern , Handler handler ) <nl> - { <nl> - put_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> - return * this ; <nl> + inline Server & Server : : Patch ( const char * pattern , Handler handler ) { <nl> + patch_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> + return * this ; <nl> } <nl> <nl> - inline Server & Server : : Delete ( const char * pattern , Handler handler ) <nl> - { <nl> - delete_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> - return * this ; <nl> + inline Server & Server : : Delete ( const char * pattern , Handler handler ) { <nl> + delete_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> + return * this ; <nl> } <nl> <nl> - inline Server & Server : : Options ( const char * pattern , Handler handler ) <nl> - { <nl> - options_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> - return * this ; <nl> + inline Server & Server : : Options ( const char * pattern , Handler handler ) { <nl> + options_handlers_ . push_back ( std : : make_pair ( std : : regex ( pattern ) , handler ) ) ; <nl> + return * this ; <nl> } <nl> <nl> - inline bool Server : : set_base_dir ( const char * path ) <nl> - { <nl> - if ( detail : : is_dir ( path ) ) { <nl> - base_dir_ = path ; <nl> - return true ; <nl> - } <nl> - return false ; <nl> + inline bool Server : : set_base_dir ( const char * path ) { <nl> + if ( detail : : is_dir ( path ) ) { <nl> + base_dir_ = path ; <nl> + return true ; <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + inline void Server : : set_file_request_handler ( Handler handler ) { <nl> + file_request_handler_ = handler ; <nl> } <nl> <nl> - inline void Server : : set_error_handler ( Handler handler ) <nl> - { <nl> - error_handler_ = handler ; <nl> + inline void Server : : set_error_handler ( Handler handler ) { <nl> + error_handler_ = handler ; <nl> } <nl> <nl> - inline void Server : : set_logger ( Logger logger ) <nl> - { <nl> - logger_ = logger ; <nl> + inline void Server : : set_logger ( Logger logger ) { logger_ = logger ; } <nl> + <nl> + inline void Server : : set_keep_alive_max_count ( size_t count ) { <nl> + keep_alive_max_count_ = count ; <nl> + } <nl> + <nl> + inline void Server : : set_payload_max_length ( size_t length ) { <nl> + payload_max_length_ = length ; <nl> + } <nl> + <nl> + inline int Server : : bind_to_any_port ( const char * host , int socket_flags ) { <nl> + return bind_internal ( host , 0 , socket_flags ) ; <nl> + } <nl> + <nl> + inline bool Server : : listen_after_bind ( ) { return listen_internal ( ) ; } <nl> + <nl> + inline bool Server : : listen ( const char * host , int port , int socket_flags ) { <nl> + if ( bind_internal ( host , port , socket_flags ) < 0 ) return false ; <nl> + return listen_internal ( ) ; <nl> } <nl> <nl> - inline void Server : : set_keep_alive_max_count ( size_t count ) <nl> - { <nl> - keep_alive_max_count_ = count ; <nl> + inline bool Server : : is_running ( ) const { return is_running_ ; } <nl> + <nl> + inline void Server : : stop ( ) { <nl> + if ( is_running_ ) { <nl> + assert ( svr_sock_ ! = INVALID_SOCKET ) ; <nl> + std : : atomic < socket_t > sock ( svr_sock_ . exchange ( INVALID_SOCKET ) ) ; <nl> + detail : : shutdown_socket ( sock ) ; <nl> + detail : : close_socket ( sock ) ; <nl> + } <nl> } <nl> <nl> - inline int Server : : bind_to_any_port ( const char * host , int socket_flags ) <nl> - { <nl> - return bind_internal ( host , 0 , socket_flags ) ; <nl> + inline bool Server : : parse_request_line ( const char * s , Request & req ) { <nl> + static std : : regex re ( " ( GET | HEAD | POST | PUT | DELETE | CONNECT | OPTIONS | TRACE | PATCH | PRI ) " <nl> + " ( ( [ ^ ? ] + ) ( ? : \ \ ? ( . + ? ) ) ? ) ( HTTP / 1 \ \ . [ 01 ] ) \ r \ n " ) ; <nl> + <nl> + std : : cmatch m ; <nl> + if ( std : : regex_match ( s , m , re ) ) { <nl> + req . version = std : : string ( m [ 5 ] ) ; <nl> + req . method = std : : string ( m [ 1 ] ) ; <nl> + req . target = std : : string ( m [ 2 ] ) ; <nl> + req . path = detail : : decode_url ( m [ 3 ] ) ; <nl> + <nl> + / / Parse query text <nl> + auto len = std : : distance ( m [ 4 ] . first , m [ 4 ] . second ) ; <nl> + if ( len > 0 ) { detail : : parse_query_text ( m [ 4 ] , req . params ) ; } <nl> + <nl> + return true ; <nl> + } <nl> + <nl> + return false ; <nl> } <nl> <nl> - inline bool Server : : listen_after_bind ( ) { <nl> - return listen_internal ( ) ; <nl> + inline bool Server : : write_response ( Stream & strm , bool last_connection , <nl> + const Request & req , Response & res ) { <nl> + assert ( res . status ! = - 1 ) ; <nl> + <nl> + if ( 400 < = res . status & & error_handler_ ) { error_handler_ ( req , res ) ; } <nl> + <nl> + / / Response line <nl> + if ( ! strm . write_format ( " HTTP / 1 . 1 % d % s \ r \ n " , res . status , <nl> + detail : : status_message ( res . status ) ) ) { <nl> + return false ; <nl> + } <nl> + <nl> + / / Headers <nl> + if ( last_connection | | req . get_header_value ( " Connection " ) = = " close " ) { <nl> + res . set_header ( " Connection " , " close " ) ; <nl> + } <nl> + <nl> + if ( ! last_connection & & req . get_header_value ( " Connection " ) = = " Keep - Alive " ) { <nl> + res . set_header ( " Connection " , " Keep - Alive " ) ; <nl> + } <nl> + <nl> + if ( ! res . has_header ( " Content - Type " ) ) { <nl> + res . set_header ( " Content - Type " , " text / plain " ) ; <nl> + } <nl> + <nl> + if ( ! res . has_header ( " Accept - Ranges " ) ) { <nl> + res . set_header ( " Accept - Ranges " , " bytes " ) ; <nl> + } <nl> + <nl> + std : : string content_type ; <nl> + std : : string boundary ; <nl> + <nl> + if ( req . ranges . size ( ) > 1 ) { <nl> + boundary = detail : : make_multipart_data_boundary ( ) ; <nl> + <nl> + auto it = res . headers . find ( " Content - Type " ) ; <nl> + if ( it ! = res . headers . end ( ) ) { <nl> + content_type = it - > second ; <nl> + res . headers . erase ( it ) ; <nl> + } <nl> + <nl> + res . headers . emplace ( " Content - Type " , <nl> + " multipart / byteranges ; boundary = " + boundary ) ; <nl> + } <nl> + <nl> + if ( res . body . empty ( ) ) { <nl> + if ( res . content_provider_resource_length > 0 ) { <nl> + size_t length = 0 ; <nl> + if ( req . ranges . empty ( ) ) { <nl> + length = res . content_provider_resource_length ; <nl> + } else if ( req . ranges . size ( ) = = 1 ) { <nl> + auto offsets = detail : : get_range_offset_and_length ( <nl> + req , res . content_provider_resource_length , 0 ) ; <nl> + auto offset = offsets . first ; <nl> + length = offsets . second ; <nl> + auto content_range = detail : : make_content_range_header_field ( <nl> + offset , length , res . content_provider_resource_length ) ; <nl> + res . set_header ( " Content - Range " , content_range ) ; <nl> + } else { <nl> + length = detail : : get_multipart_ranges_data_length ( req , res , boundary , <nl> + content_type ) ; <nl> + } <nl> + res . set_header ( " Content - Length " , std : : to_string ( length ) ) ; <nl> + } else { <nl> + if ( res . content_provider ) { <nl> + res . set_header ( " Transfer - Encoding " , " chunked " ) ; <nl> + } else { <nl> + res . set_header ( " Content - Length " , " 0 " ) ; <nl> + } <nl> + } <nl> + } else { <nl> + if ( req . ranges . empty ( ) ) { <nl> + ; <nl> + } else if ( req . ranges . size ( ) = = 1 ) { <nl> + auto offsets = <nl> + detail : : get_range_offset_and_length ( req , res . body . size ( ) , 0 ) ; <nl> + auto offset = offsets . first ; <nl> + auto length = offsets . second ; <nl> + auto content_range = detail : : make_content_range_header_field ( <nl> + offset , length , res . body . size ( ) ) ; <nl> + res . set_header ( " Content - Range " , content_range ) ; <nl> + res . body = res . body . substr ( offset , length ) ; <nl> + } else { <nl> + res . body = <nl> + detail : : make_multipart_ranges_data ( req , res , boundary , content_type ) ; <nl> + } <nl> + <nl> + # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> + / / TODO : ' Accpet - Encoding ' has gzip , not gzip ; q = 0 <nl> + const auto & encodings = req . get_header_value ( " Accept - Encoding " ) ; <nl> + if ( encodings . find ( " gzip " ) ! = std : : string : : npos & & <nl> + detail : : can_compress ( res . get_header_value ( " Content - Type " ) ) ) { <nl> + if ( detail : : compress ( res . body ) ) { <nl> + res . set_header ( " Content - Encoding " , " gzip " ) ; <nl> + } <nl> + } <nl> + # endif <nl> + <nl> + auto length = std : : to_string ( res . body . size ( ) ) ; <nl> + res . set_header ( " Content - Length " , length ) ; <nl> + } <nl> + <nl> + if ( ! detail : : write_headers ( strm , res , Headers ( ) ) ) { return false ; } <nl> + <nl> + / / Body <nl> + if ( req . method ! = " HEAD " ) { <nl> + if ( ! res . body . empty ( ) ) { <nl> + if ( ! strm . write ( res . body ) ) { return false ; } <nl> + } else if ( res . content_provider ) { <nl> + if ( ! write_content_with_provider ( strm , req , res , boundary , <nl> + content_type ) ) { <nl> + return false ; <nl> + } <nl> + } <nl> + } <nl> + <nl> + / / Log <nl> + if ( logger_ ) { logger_ ( req , res ) ; } <nl> + <nl> + return true ; <nl> } <nl> <nl> - inline bool Server : : listen ( const char * host , int port , int socket_flags ) <nl> - { <nl> - if ( bind_internal ( host , port , socket_flags ) < 0 ) <nl> + inline bool <nl> + Server : : write_content_with_provider ( Stream & strm , const Request & req , <nl> + Response & res , const std : : string & boundary , <nl> + const std : : string & content_type ) { <nl> + if ( res . content_provider_resource_length ) { <nl> + if ( req . ranges . empty ( ) ) { <nl> + if ( detail : : write_content ( strm , res . content_provider , 0 , <nl> + res . content_provider_resource_length ) < 0 ) { <nl> return false ; <nl> - return listen_internal ( ) ; <nl> + } <nl> + } else if ( req . ranges . size ( ) = = 1 ) { <nl> + auto offsets = detail : : get_range_offset_and_length ( <nl> + req , res . content_provider_resource_length , 0 ) ; <nl> + auto offset = offsets . first ; <nl> + auto length = offsets . second ; <nl> + if ( detail : : write_content ( strm , res . content_provider , offset , length ) < <nl> + 0 ) { <nl> + return false ; <nl> + } <nl> + } else { <nl> + if ( ! detail : : write_multipart_ranges_data ( strm , req , res , boundary , <nl> + content_type ) ) { <nl> + return false ; <nl> + } <nl> + } <nl> + } else { <nl> + if ( detail : : write_content_chunked ( strm , res . content_provider ) < 0 ) { <nl> + return false ; <nl> + } <nl> + } <nl> + return true ; <nl> + } <nl> + <nl> + inline bool Server : : handle_file_request ( Request & req , Response & res ) { <nl> + if ( ! base_dir_ . empty ( ) & & detail : : is_valid_path ( req . path ) ) { <nl> + std : : string path = base_dir_ + req . path ; <nl> + <nl> + if ( ! path . empty ( ) & & path . back ( ) = = ' / ' ) { path + = " index . html " ; } <nl> + <nl> + if ( detail : : is_file ( path ) ) { <nl> + detail : : read_file ( path , res . body ) ; <nl> + auto type = detail : : find_content_type ( path ) ; <nl> + if ( type ) { res . set_header ( " Content - Type " , type ) ; } <nl> + res . status = 200 ; <nl> + if ( file_request_handler_ ) { file_request_handler_ ( req , res ) ; } <nl> + return true ; <nl> + } <nl> + } <nl> + <nl> + return false ; <nl> + } <nl> + <nl> + inline socket_t Server : : create_server_socket ( const char * host , int port , <nl> + int socket_flags ) const { <nl> + return detail : : create_socket ( <nl> + host , port , <nl> + [ ] ( socket_t sock , struct addrinfo & ai ) - > bool { <nl> + if ( : : bind ( sock , ai . ai_addr , static_cast < int > ( ai . ai_addrlen ) ) ) { <nl> + return false ; <nl> + } <nl> + if ( : : listen ( sock , 5 ) ) { / / Listen through 5 channels <nl> + return false ; <nl> + } <nl> + return true ; <nl> + } , <nl> + socket_flags ) ; <nl> } <nl> <nl> - inline bool Server : : is_running ( ) const <nl> - { <nl> - return is_running_ ; <nl> - } <nl> + inline int Server : : bind_internal ( const char * host , int port , int socket_flags ) { <nl> + if ( ! is_valid ( ) ) { return - 1 ; } <nl> + <nl> + svr_sock_ = create_server_socket ( host , port , socket_flags ) ; <nl> + if ( svr_sock_ = = INVALID_SOCKET ) { return - 1 ; } <nl> <nl> - inline void Server : : stop ( ) <nl> - { <nl> - if ( is_running_ ) { <nl> - assert ( svr_sock_ ! = INVALID_SOCKET ) ; <nl> - detail : : shutdown_socket ( svr_sock_ ) ; <nl> - detail : : close_socket ( svr_sock_ ) ; <nl> - svr_sock_ = INVALID_SOCKET ; <nl> + if ( port = = 0 ) { <nl> + struct sockaddr_storage address ; <nl> + socklen_t len = sizeof ( address ) ; <nl> + if ( getsockname ( svr_sock_ , reinterpret_cast < struct sockaddr * > ( & address ) , <nl> + & len ) = = - 1 ) { <nl> + return - 1 ; <nl> + } <nl> + if ( address . ss_family = = AF_INET ) { <nl> + return ntohs ( reinterpret_cast < struct sockaddr_in * > ( & address ) - > sin_port ) ; <nl> + } else if ( address . ss_family = = AF_INET6 ) { <nl> + return ntohs ( <nl> + reinterpret_cast < struct sockaddr_in6 * > ( & address ) - > sin6_port ) ; <nl> + } else { <nl> + return - 1 ; <nl> } <nl> + } else { <nl> + return port ; <nl> + } <nl> } <nl> <nl> - inline bool Server : : parse_request_line ( const char * s , Request & req ) <nl> - { <nl> - static std : : regex re ( " ( GET | HEAD | POST | PUT | DELETE | OPTIONS ) ( ( [ ^ ? ] + ) ( ? : \ \ ? ( . + ? ) ) ? ) ( HTTP / 1 \ \ . [ 01 ] ) \ r \ n " ) ; <nl> - <nl> - std : : cmatch m ; <nl> - if ( std : : regex_match ( s , m , re ) ) { <nl> - req . version = std : : string ( m [ 4 ] ) ; <nl> - req . method = std : : string ( m [ 1 ] ) ; <nl> - req . target = std : : string ( m [ 2 ] ) ; <nl> - req . path = detail : : decode_url ( m [ 3 ] ) ; <nl> - <nl> - / / Parse query text <nl> - auto len = std : : distance ( m [ 4 ] . first , m [ 4 ] . second ) ; <nl> - if ( len > 0 ) { <nl> - detail : : parse_query_text ( m [ 4 ] , req . params ) ; <nl> - } <nl> - <nl> - return true ; <nl> - } <nl> + inline bool Server : : listen_internal ( ) { <nl> + auto ret = true ; <nl> + is_running_ = true ; <nl> <nl> - return false ; <nl> - } <nl> + { <nl> + std : : unique_ptr < TaskQueue > task_queue ( new_task_queue ( ) ) ; <nl> <nl> - inline void Server : : write_response ( Stream & strm , bool last_connection , const Request & req , Response & res ) <nl> - { <nl> - assert ( res . status ! = - 1 ) ; <nl> + for ( ; ; ) { <nl> + if ( svr_sock_ = = INVALID_SOCKET ) { <nl> + / / The server socket was closed by ' stop ' method . <nl> + break ; <nl> + } <nl> <nl> - if ( 400 < = res . status & & error_handler_ ) { <nl> - error_handler_ ( req , res ) ; <nl> - } <nl> + auto val = detail : : select_read ( svr_sock_ , 0 , 100000 ) ; <nl> <nl> - / / Response line <nl> - strm . write_format ( " HTTP / 1 . 1 % d % s \ r \ n " , <nl> - res . status , <nl> - detail : : status_message ( res . status ) ) ; <nl> + if ( val = = 0 ) { / / Timeout <nl> + continue ; <nl> + } <nl> <nl> - / / Headers <nl> - if ( last_connection | | <nl> - req . version = = " HTTP / 1 . 0 " | | <nl> - req . get_header_value ( " Connection " ) = = " close " ) { <nl> - res . set_header ( " Connection " , " close " ) ; <nl> - } <nl> + socket_t sock = accept ( svr_sock_ , nullptr , nullptr ) ; <nl> <nl> - if ( ! res . body . empty ( ) ) { <nl> - # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> - / / TODO : ' Accpet - Encoding ' has gzip , not gzip ; q = 0 <nl> - const auto & encodings = req . get_header_value ( " Accept - Encoding " ) ; <nl> - if ( encodings . find ( " gzip " ) ! = std : : string : : npos & & <nl> - detail : : can_compress ( res . get_header_value ( " Content - Type " ) ) ) { <nl> - detail : : compress ( res . body ) ; <nl> - res . set_header ( " Content - Encoding " , " gzip " ) ; <nl> + if ( sock = = INVALID_SOCKET ) { <nl> + if ( errno = = EMFILE ) { <nl> + / / The per - process limit of open file descriptors has been reached . <nl> + / / Try to accept new connections after a short sleep . <nl> + std : : this_thread : : sleep_for ( std : : chrono : : milliseconds ( 1 ) ) ; <nl> + continue ; <nl> } <nl> - # endif <nl> - <nl> - if ( ! res . has_header ( " Content - Type " ) ) { <nl> - res . set_header ( " Content - Type " , " text / plain " ) ; <nl> + if ( svr_sock_ ! = INVALID_SOCKET ) { <nl> + detail : : close_socket ( svr_sock_ ) ; <nl> + ret = false ; <nl> + } else { <nl> + ; / / The server socket was closed by user . <nl> } <nl> + break ; <nl> + } <nl> <nl> - auto length = std : : to_string ( res . body . size ( ) ) ; <nl> - res . set_header ( " Content - Length " , length . c_str ( ) ) ; <nl> + task_queue - > enqueue ( [ = ] ( ) { process_and_close_socket ( sock ) ; } ) ; <nl> } <nl> <nl> - detail : : write_headers ( strm , res ) ; <nl> + task_queue - > shutdown ( ) ; <nl> + } <nl> <nl> - / / Body <nl> - if ( ! res . body . empty ( ) & & req . method ! = " HEAD " ) { <nl> - strm . write ( res . body . c_str ( ) , res . body . size ( ) ) ; <nl> + is_running_ = false ; <nl> + return ret ; <nl> + } <nl> + <nl> + inline bool Server : : routing ( Request & req , Response & res ) { <nl> + if ( req . method = = " GET " & & handle_file_request ( req , res ) ) { return true ; } <nl> + <nl> + if ( req . method = = " GET " | | req . method = = " HEAD " ) { <nl> + return dispatch_request ( req , res , get_handlers_ ) ; <nl> + } else if ( req . method = = " POST " ) { <nl> + return dispatch_request ( req , res , post_handlers_ ) ; <nl> + } else if ( req . method = = " PUT " ) { <nl> + return dispatch_request ( req , res , put_handlers_ ) ; <nl> + } else if ( req . method = = " DELETE " ) { <nl> + return dispatch_request ( req , res , delete_handlers_ ) ; <nl> + } else if ( req . method = = " OPTIONS " ) { <nl> + return dispatch_request ( req , res , options_handlers_ ) ; <nl> + } else if ( req . method = = " PATCH " ) { <nl> + return dispatch_request ( req , res , patch_handlers_ ) ; <nl> + } <nl> + <nl> + res . status = 400 ; <nl> + return false ; <nl> + } <nl> + <nl> + inline bool Server : : dispatch_request ( Request & req , Response & res , <nl> + Handlers & handlers ) { <nl> + for ( const auto & x : handlers ) { <nl> + const auto & pattern = x . first ; <nl> + const auto & handler = x . second ; <nl> + <nl> + if ( std : : regex_match ( req . path , req . matches , pattern ) ) { <nl> + handler ( req , res ) ; <nl> + return true ; <nl> + } <nl> + } <nl> + return false ; <nl> + } <nl> + <nl> + inline bool <nl> + Server : : process_request ( Stream & strm , bool last_connection , <nl> + bool & connection_close , <nl> + std : : function < void ( Request & ) > setup_request ) { <nl> + const auto bufsiz = 2048 ; <nl> + char buf [ bufsiz ] ; <nl> + <nl> + detail : : stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> + <nl> + / / Connection has been closed on client <nl> + if ( ! reader . getline ( ) ) { return false ; } <nl> + <nl> + Request req ; <nl> + Response res ; <nl> + <nl> + res . version = " HTTP / 1 . 1 " ; <nl> + <nl> + / / Check if the request URI doesn ' t exceed the limit <nl> + if ( reader . size ( ) > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH ) { <nl> + Headers dummy ; <nl> + detail : : read_headers ( strm , dummy ) ; <nl> + res . status = 414 ; <nl> + return write_response ( strm , last_connection , req , res ) ; <nl> + } <nl> + <nl> + / / Request line and headers <nl> + if ( ! parse_request_line ( reader . ptr ( ) , req ) | | <nl> + ! detail : : read_headers ( strm , req . headers ) ) { <nl> + res . status = 400 ; <nl> + return write_response ( strm , last_connection , req , res ) ; <nl> + } <nl> + <nl> + if ( req . get_header_value ( " Connection " ) = = " close " ) { <nl> + connection_close = true ; <nl> + } <nl> + <nl> + if ( req . version = = " HTTP / 1 . 0 " & & <nl> + req . get_header_value ( " Connection " ) ! = " Keep - Alive " ) { <nl> + connection_close = true ; <nl> + } <nl> + <nl> + req . set_header ( " REMOTE_ADDR " , strm . get_remote_addr ( ) ) ; <nl> + <nl> + / / Body <nl> + if ( req . method = = " POST " | | req . method = = " PUT " | | req . method = = " PATCH " | | req . method = = " PRI " ) { <nl> + if ( ! detail : : read_content ( strm , req , payload_max_length_ , res . status , <nl> + Progress ( ) , [ & ] ( const char * buf , size_t n ) { <nl> + if ( req . body . size ( ) + n > req . body . max_size ( ) ) { <nl> + return false ; <nl> + } <nl> + req . body . append ( buf , n ) ; <nl> + return true ; <nl> + } ) ) { <nl> + return write_response ( strm , last_connection , req , res ) ; <nl> + } <nl> + <nl> + const auto & content_type = req . get_header_value ( " Content - Type " ) ; <nl> + <nl> + if ( ! content_type . find ( " application / x - www - form - urlencoded " ) ) { <nl> + detail : : parse_query_text ( req . body , req . params ) ; <nl> + } else if ( ! content_type . find ( " multipart / form - data " ) ) { <nl> + std : : string boundary ; <nl> + if ( ! detail : : parse_multipart_boundary ( content_type , boundary ) | | <nl> + ! detail : : parse_multipart_formdata ( boundary , req . body , req . files ) ) { <nl> + res . status = 400 ; <nl> + return write_response ( strm , last_connection , req , res ) ; <nl> + } <nl> } <nl> + } <nl> <nl> - / / Log <nl> - if ( logger_ ) { <nl> - logger_ ( req , res ) ; <nl> + if ( req . has_header ( " Range " ) ) { <nl> + const auto & range_header_value = req . get_header_value ( " Range " ) ; <nl> + if ( ! detail : : parse_range_header ( range_header_value , req . ranges ) ) { <nl> + / / TODO : error <nl> } <nl> + } <nl> + <nl> + if ( setup_request ) { setup_request ( req ) ; } <nl> + <nl> + if ( routing ( req , res ) ) { <nl> + if ( res . status = = - 1 ) { res . status = req . ranges . empty ( ) ? 200 : 206 ; } <nl> + } else { <nl> + if ( res . status = = - 1 ) { res . status = 404 ; } <nl> + } <nl> + <nl> + return write_response ( strm , last_connection , req , res ) ; <nl> } <nl> <nl> - inline bool Server : : handle_file_request ( Request & req , Response & res ) <nl> - { <nl> - if ( ! base_dir_ . empty ( ) & & detail : : is_valid_path ( req . path ) ) { <nl> - std : : string path = base_dir_ + req . path ; <nl> + inline bool Server : : is_valid ( ) const { return true ; } <nl> <nl> - if ( ! path . empty ( ) & & path . back ( ) = = ' / ' ) { <nl> - path + = " index . html " ; <nl> - } <nl> + inline bool Server : : process_and_close_socket ( socket_t sock ) { <nl> + return detail : : process_and_close_socket ( <nl> + false , sock , keep_alive_max_count_ , <nl> + [ this ] ( Stream & strm , bool last_connection , bool & connection_close ) { <nl> + return process_request ( strm , last_connection , connection_close , <nl> + nullptr ) ; <nl> + } ) ; <nl> + } <nl> <nl> - if ( detail : : is_file ( path ) ) { <nl> - detail : : read_file ( path , res . body ) ; <nl> - auto type = detail : : find_content_type ( path ) ; <nl> - if ( type ) { <nl> - res . set_header ( " Content - Type " , type ) ; <nl> - } <nl> - res . status = 200 ; <nl> - return true ; <nl> + / / HTTP client implementation <nl> + inline Client : : Client ( const char * host , int port , time_t timeout_sec ) <nl> + : host_ ( host ) , port_ ( port ) , timeout_sec_ ( timeout_sec ) , <nl> + host_and_port_ ( host_ + " : " + std : : to_string ( port_ ) ) , <nl> + keep_alive_max_count_ ( CPPHTTPLIB_KEEPALIVE_MAX_COUNT ) , <nl> + follow_location_ ( false ) { } <nl> + <nl> + inline Client : : ~ Client ( ) { } <nl> + <nl> + inline bool Client : : is_valid ( ) const { return true ; } <nl> + <nl> + inline socket_t Client : : create_client_socket ( ) const { <nl> + return detail : : create_socket ( <nl> + host_ . c_str ( ) , port_ , [ = ] ( socket_t sock , struct addrinfo & ai ) - > bool { <nl> + detail : : set_nonblocking ( sock , true ) ; <nl> + <nl> + auto ret = connect ( sock , ai . ai_addr , static_cast < int > ( ai . ai_addrlen ) ) ; <nl> + if ( ret < 0 ) { <nl> + if ( detail : : is_connection_error ( ) | | <nl> + ! detail : : wait_until_socket_is_ready ( sock , timeout_sec_ , 0 ) ) { <nl> + detail : : close_socket ( sock ) ; <nl> + return false ; <nl> + } <nl> } <nl> - } <nl> <nl> - return false ; <nl> + detail : : set_nonblocking ( sock , false ) ; <nl> + return true ; <nl> + } ) ; <nl> } <nl> <nl> - inline socket_t Server : : create_server_socket ( const char * host , int port , int socket_flags ) const <nl> - { <nl> - return detail : : create_socket ( host , port , <nl> - [ ] ( socket_t sock , struct addrinfo & ai ) - > bool { <nl> - if ( : : bind ( sock , ai . ai_addr , ai . ai_addrlen ) ) { <nl> - return false ; <nl> - } <nl> - if ( : : listen ( sock , 5 ) ) { / / Listen through 5 channels <nl> - return false ; <nl> - } <nl> - return true ; <nl> - } , socket_flags ) ; <nl> - } <nl> - <nl> - inline int Server : : bind_internal ( const char * host , int port , int socket_flags ) <nl> - { <nl> - if ( ! is_valid ( ) ) { <nl> - return - 1 ; <nl> - } <nl> + inline bool Client : : read_response_line ( Stream & strm , Response & res ) { <nl> + const auto bufsiz = 2048 ; <nl> + char buf [ bufsiz ] ; <nl> <nl> - svr_sock_ = create_server_socket ( host , port , socket_flags ) ; <nl> - if ( svr_sock_ = = INVALID_SOCKET ) { <nl> - return - 1 ; <nl> - } <nl> + detail : : stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> <nl> - if ( port = = 0 ) { <nl> - struct sockaddr_storage address ; <nl> - socklen_t len = sizeof ( address ) ; <nl> - if ( getsockname ( svr_sock_ , reinterpret_cast < struct sockaddr * > ( & address ) , & len ) = = - 1 ) { <nl> - return - 1 ; <nl> - } <nl> - if ( address . ss_family = = AF_INET ) { <nl> - return ntohs ( reinterpret_cast < struct sockaddr_in * > ( & address ) - > sin_port ) ; <nl> - } else if ( address . ss_family = = AF_INET6 ) { <nl> - return ntohs ( reinterpret_cast < struct sockaddr_in6 * > ( & address ) - > sin6_port ) ; <nl> - } else { <nl> - return - 1 ; <nl> - } <nl> - } else { <nl> - return port ; <nl> - } <nl> - } <nl> + if ( ! reader . getline ( ) ) { return false ; } <nl> <nl> - inline bool Server : : listen_internal ( ) <nl> - { <nl> - auto ret = true ; <nl> + const static std : : regex re ( " ( HTTP / 1 \ \ . [ 01 ] ) ( \ \ d + ? ) . * \ r \ n " ) ; <nl> <nl> - is_running_ = true ; <nl> + std : : cmatch m ; <nl> + if ( std : : regex_match ( reader . ptr ( ) , m , re ) ) { <nl> + res . version = std : : string ( m [ 1 ] ) ; <nl> + res . status = std : : stoi ( std : : string ( m [ 2 ] ) ) ; <nl> + } <nl> <nl> - for ( ; ; ) { <nl> - auto val = detail : : select_read ( svr_sock_ , 0 , 100000 ) ; <nl> + return true ; <nl> + } <nl> <nl> - if ( val = = 0 ) { / / Timeout <nl> - if ( svr_sock_ = = INVALID_SOCKET ) { <nl> - / / The server socket was closed by ' stop ' method . <nl> - break ; <nl> - } <nl> - continue ; <nl> - } <nl> + inline bool Client : : send ( const Request & req , Response & res ) { <nl> + if ( req . path . empty ( ) ) { return false ; } <nl> <nl> - socket_t sock = accept ( svr_sock_ , NULL , NULL ) ; <nl> + auto sock = create_client_socket ( ) ; <nl> + if ( sock = = INVALID_SOCKET ) { return false ; } <nl> <nl> - if ( sock = = INVALID_SOCKET ) { <nl> - if ( svr_sock_ ! = INVALID_SOCKET ) { <nl> - detail : : close_socket ( svr_sock_ ) ; <nl> - ret = false ; <nl> - } else { <nl> - ; / / The server socket was closed by user . <nl> - } <nl> - break ; <nl> - } <nl> + auto ret = process_and_close_socket ( <nl> + sock , 1 , [ & ] ( Stream & strm , bool last_connection , bool & connection_close ) { <nl> + return process_request ( strm , req , res , last_connection , <nl> + connection_close ) ; <nl> + } ) ; <nl> <nl> - / / TODO : Use thread pool . . . <nl> - std : : thread ( [ = ] ( ) { <nl> - { <nl> - std : : lock_guard < std : : mutex > guard ( running_threads_mutex_ ) ; <nl> - running_threads_ + + ; <nl> - } <nl> + if ( ret & & follow_location_ & & ( 300 < res . status & & res . status < 400 ) ) { <nl> + ret = redirect ( req , res ) ; <nl> + } <nl> <nl> - read_and_close_socket ( sock ) ; <nl> + return ret ; <nl> + } <nl> <nl> - { <nl> - std : : lock_guard < std : : mutex > guard ( running_threads_mutex_ ) ; <nl> - running_threads_ - - ; <nl> - } <nl> - } ) . detach ( ) ; <nl> - } <nl> + inline bool Client : : send ( const std : : vector < Request > & requests , <nl> + std : : vector < Response > & responses ) { <nl> + size_t i = 0 ; <nl> + while ( i < requests . size ( ) ) { <nl> + auto sock = create_client_socket ( ) ; <nl> + if ( sock = = INVALID_SOCKET ) { return false ; } <nl> <nl> - / / TODO : Use thread pool . . . <nl> - for ( ; ; ) { <nl> - std : : this_thread : : sleep_for ( std : : chrono : : milliseconds ( 10 ) ) ; <nl> - std : : lock_guard < std : : mutex > guard ( running_threads_mutex_ ) ; <nl> - if ( ! running_threads_ ) { <nl> - break ; <nl> - } <nl> - } <nl> + if ( ! process_and_close_socket ( <nl> + sock , requests . size ( ) - i , <nl> + [ & ] ( Stream & strm , bool last_connection , bool & connection_close ) - > bool { <nl> + auto & req = requests [ i ] ; <nl> + auto res = Response ( ) ; <nl> + i + + ; <nl> <nl> - is_running_ = false ; <nl> + if ( req . path . empty ( ) ) { return false ; } <nl> + auto ret = process_request ( strm , req , res , last_connection , <nl> + connection_close ) ; <nl> <nl> - return ret ; <nl> - } <nl> + if ( ret & & follow_location_ & & <nl> + ( 300 < res . status & & res . status < 400 ) ) { <nl> + ret = redirect ( req , res ) ; <nl> + } <nl> <nl> - inline bool Server : : routing ( Request & req , Response & res ) <nl> - { <nl> - if ( req . method = = " GET " & & handle_file_request ( req , res ) ) { <nl> - return true ; <nl> - } <nl> + if ( ret ) { responses . emplace_back ( std : : move ( res ) ) ; } <nl> <nl> - if ( req . method = = " GET " | | req . method = = " HEAD " ) { <nl> - return dispatch_request ( req , res , get_handlers_ ) ; <nl> - } else if ( req . method = = " POST " ) { <nl> - return dispatch_request ( req , res , post_handlers_ ) ; <nl> - } else if ( req . method = = " PUT " ) { <nl> - return dispatch_request ( req , res , put_handlers_ ) ; <nl> - } else if ( req . method = = " DELETE " ) { <nl> - return dispatch_request ( req , res , delete_handlers_ ) ; <nl> - } else if ( req . method = = " OPTIONS " ) { <nl> - return dispatch_request ( req , res , options_handlers_ ) ; <nl> + return ret ; <nl> + } ) ) { <nl> + return false ; <nl> } <nl> - return false ; <nl> + } <nl> + <nl> + return true ; <nl> } <nl> <nl> - inline bool Server : : dispatch_request ( Request & req , Response & res , Handlers & handlers ) <nl> - { <nl> - for ( const auto & x : handlers ) { <nl> - const auto & pattern = x . first ; <nl> - const auto & handler = x . second ; <nl> + inline bool Client : : redirect ( const Request & req , Response & res ) { <nl> + if ( req . redirect_count = = 0 ) { return false ; } <nl> <nl> - if ( std : : regex_match ( req . path , req . matches , pattern ) ) { <nl> - handler ( req , res ) ; <nl> - return true ; <nl> - } <nl> + auto location = res . get_header_value ( " location " ) ; <nl> + if ( location . empty ( ) ) { return false ; } <nl> + <nl> + std : : regex re ( <nl> + R " ( ^ ( ? : ( [ ^ : / ? # ] + ) : ) ? ( ? : / / ( [ ^ / ? # ] * ) ) ? ( [ ^ ? # ] * ( ? : \ ? [ ^ # ] * ) ? ) ( ? : # . * ) ? ) " ) ; <nl> + <nl> + auto scheme = is_ssl ( ) ? " https " : " http " ; <nl> + <nl> + std : : smatch m ; <nl> + if ( regex_match ( location , m , re ) ) { <nl> + auto next_scheme = m [ 1 ] . str ( ) ; <nl> + auto next_host = m [ 2 ] . str ( ) ; <nl> + auto next_path = m [ 3 ] . str ( ) ; <nl> + if ( next_host . empty ( ) ) { next_host = host_ ; } <nl> + if ( next_path . empty ( ) ) { next_path = " / " ; } <nl> + <nl> + if ( next_scheme = = scheme & & next_host = = host_ ) { <nl> + return detail : : redirect ( * this , req , res , next_path ) ; <nl> + } else { <nl> + if ( next_scheme = = " https " ) { <nl> + # ifdef CPPHTTPLIB_OPENSSL_SUPPORT <nl> + SSLClient cli ( next_host . c_str ( ) ) ; <nl> + cli . follow_location ( true ) ; <nl> + return detail : : redirect ( cli , req , res , next_path ) ; <nl> + # else <nl> + return false ; <nl> + # endif <nl> + } else { <nl> + Client cli ( next_host . c_str ( ) ) ; <nl> + cli . follow_location ( true ) ; <nl> + return detail : : redirect ( cli , req , res , next_path ) ; <nl> + } <nl> } <nl> - return false ; <nl> + } <nl> + return false ; <nl> } <nl> <nl> - inline bool Server : : process_request ( Stream & strm , bool last_connection , bool & connection_close ) <nl> - { <nl> - const auto bufsiz = 2048 ; <nl> - char buf [ bufsiz ] ; <nl> + inline void Client : : write_request ( Stream & strm , const Request & req , <nl> + bool last_connection ) { <nl> + BufferStream bstrm ; <nl> <nl> - detail : : stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> + / / Request line <nl> + auto path = detail : : encode_url ( req . path ) ; <nl> <nl> - / / Connection has been closed on client <nl> - if ( ! reader . getline ( ) ) { <nl> - return false ; <nl> + bstrm . write_format ( " % s % s HTTP / 1 . 1 \ r \ n " , req . method . c_str ( ) , path . c_str ( ) ) ; <nl> + <nl> + / / Additonal headers <nl> + Headers headers ; <nl> + if ( last_connection ) { headers . emplace ( " Connection " , " close " ) ; } <nl> + <nl> + if ( ! req . has_header ( " Host " ) ) { <nl> + if ( is_ssl ( ) ) { <nl> + if ( port_ = = 443 ) { <nl> + headers . emplace ( " Host " , host_ ) ; <nl> + } else { <nl> + headers . emplace ( " Host " , host_and_port_ ) ; <nl> + } <nl> + } else { <nl> + if ( port_ = = 80 ) { <nl> + headers . emplace ( " Host " , host_ ) ; <nl> + } else { <nl> + headers . emplace ( " Host " , host_and_port_ ) ; <nl> + } <nl> } <nl> + } <nl> <nl> - Request req ; <nl> - Response res ; <nl> + if ( ! req . has_header ( " Accept " ) ) { headers . emplace ( " Accept " , " * / * " ) ; } <nl> <nl> - res . version = " HTTP / 1 . 1 " ; <nl> + if ( ! req . has_header ( " User - Agent " ) ) { <nl> + headers . emplace ( " User - Agent " , " cpp - httplib / 0 . 2 " ) ; <nl> + } <nl> <nl> - / / Request line and headers <nl> - if ( ! parse_request_line ( reader . ptr ( ) , req ) | | ! detail : : read_headers ( strm , req . headers ) ) { <nl> - res . status = 400 ; <nl> - write_response ( strm , last_connection , req , res ) ; <nl> - return true ; <nl> + if ( req . body . empty ( ) ) { <nl> + if ( req . method = = " POST " | | req . method = = " PUT " | | req . method = = " PATCH " ) { <nl> + headers . emplace ( " Content - Length " , " 0 " ) ; <nl> + } <nl> + } else { <nl> + if ( ! req . has_header ( " Content - Type " ) ) { <nl> + headers . emplace ( " Content - Type " , " text / plain " ) ; <nl> } <nl> <nl> - auto ret = true ; <nl> - if ( req . get_header_value ( " Connection " ) = = " close " ) { <nl> - / / ret = false ; <nl> - connection_close = true ; <nl> + if ( ! req . has_header ( " Content - Length " ) ) { <nl> + auto length = std : : to_string ( req . body . size ( ) ) ; <nl> + headers . emplace ( " Content - Length " , length ) ; <nl> } <nl> + } <nl> <nl> - req . set_header ( " REMOTE_ADDR " , strm . get_remote_addr ( ) . c_str ( ) ) ; <nl> + detail : : write_headers ( bstrm , req , headers ) ; <nl> <nl> - / / Body <nl> - if ( req . method = = " POST " | | req . method = = " PUT " ) { <nl> - if ( ! detail : : read_content ( strm , req ) ) { <nl> - res . status = 400 ; <nl> - write_response ( strm , last_connection , req , res ) ; <nl> - return ret ; <nl> - } <nl> + / / Body <nl> + if ( ! req . body . empty ( ) ) { bstrm . write ( req . body ) ; } <nl> <nl> - const auto & content_type = req . get_header_value ( " Content - Type " ) ; <nl> + / / Flush buffer <nl> + auto & data = bstrm . get_buffer ( ) ; <nl> + strm . write ( data . data ( ) , data . size ( ) ) ; <nl> + } <nl> <nl> - if ( req . get_header_value ( " Content - Encoding " ) = = " gzip " ) { <nl> - # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> - detail : : decompress ( req . body ) ; <nl> - # else <nl> - res . status = 415 ; <nl> - write_response ( strm , last_connection , req , res ) ; <nl> - return ret ; <nl> - # endif <nl> - } <nl> + inline bool Client : : process_request ( Stream & strm , const Request & req , <nl> + Response & res , bool last_connection , <nl> + bool & connection_close ) { <nl> + / / Send request <nl> + write_request ( strm , req , last_connection ) ; <nl> <nl> - if ( ! content_type . find ( " application / x - www - form - urlencoded " ) ) { <nl> - detail : : parse_query_text ( req . body , req . params ) ; <nl> - } else if ( ! content_type . find ( " multipart / form - data " ) ) { <nl> - std : : string boundary ; <nl> - if ( ! detail : : parse_multipart_boundary ( content_type , boundary ) | | <nl> - ! detail : : parse_multipart_formdata ( boundary , req . body , req . files ) ) { <nl> - res . status = 400 ; <nl> - write_response ( strm , last_connection , req , res ) ; <nl> - return ret ; <nl> - } <nl> - } <nl> + / / Receive response and headers <nl> + if ( ! read_response_line ( strm , res ) | | <nl> + ! detail : : read_headers ( strm , res . headers ) ) { <nl> + return false ; <nl> + } <nl> + <nl> + if ( res . get_header_value ( " Connection " ) = = " close " | | <nl> + res . version = = " HTTP / 1 . 0 " ) { <nl> + connection_close = true ; <nl> + } <nl> + <nl> + if ( req . response_handler ) { <nl> + if ( ! req . response_handler ( res ) ) { return false ; } <nl> + } <nl> + <nl> + / / Body <nl> + if ( req . method ! = " HEAD " ) { <nl> + detail : : ContentReceiverCore out = [ & ] ( const char * buf , size_t n ) { <nl> + if ( res . body . size ( ) + n > res . body . max_size ( ) ) { return false ; } <nl> + res . body . append ( buf , n ) ; <nl> + return true ; <nl> + } ; <nl> + <nl> + if ( req . content_receiver ) { <nl> + auto offset = std : : make_shared < size_t > ( ) ; <nl> + auto length = get_header_value_uint64 ( res . headers , " Content - Length " , 0 ) ; <nl> + auto receiver = req . content_receiver ; <nl> + out = [ offset , length , receiver ] ( const char * buf , size_t n ) { <nl> + auto ret = receiver ( buf , n , * offset , length ) ; <nl> + ( * offset ) + = n ; <nl> + return ret ; <nl> + } ; <nl> } <nl> <nl> - if ( routing ( req , res ) ) { <nl> - if ( res . status = = - 1 ) { <nl> - res . status = 200 ; <nl> - } <nl> - } else { <nl> - res . status = 404 ; <nl> + int dummy_status ; <nl> + if ( ! detail : : read_content ( strm , res , std : : numeric_limits < size_t > : : max ( ) , <nl> + dummy_status , req . progress , out ) ) { <nl> + return false ; <nl> } <nl> + } <nl> <nl> - write_response ( strm , last_connection , req , res ) ; <nl> - return ret ; <nl> + return true ; <nl> } <nl> <nl> - inline bool Server : : is_valid ( ) const <nl> - { <nl> - return true ; <nl> + inline bool Client : : process_and_close_socket ( <nl> + socket_t sock , size_t request_count , <nl> + std : : function < bool ( Stream & strm , bool last_connection , <nl> + bool & connection_close ) > <nl> + callback ) { <nl> + request_count = std : : min ( request_count , keep_alive_max_count_ ) ; <nl> + return detail : : process_and_close_socket ( true , sock , request_count , callback ) ; <nl> } <nl> <nl> - inline bool Server : : read_and_close_socket ( socket_t sock ) <nl> - { <nl> - return detail : : read_and_close_socket ( <nl> - sock , <nl> - keep_alive_max_count_ , <nl> - [ this ] ( Stream & strm , bool last_connection , bool & connection_close ) { <nl> - return process_request ( strm , last_connection , connection_close ) ; <nl> - } ) ; <nl> - } <nl> + inline bool Client : : is_ssl ( ) const { return false ; } <nl> <nl> - / / HTTP client implementation <nl> - inline Client : : Client ( <nl> - const char * host , int port , size_t timeout_sec ) <nl> - : host_ ( host ) <nl> - , port_ ( port ) <nl> - , timeout_sec_ ( timeout_sec ) <nl> - , host_and_port_ ( host_ + " : " + std : : to_string ( port_ ) ) <nl> - { <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path ) { <nl> + Progress dummy ; <nl> + return Get ( path , Headers ( ) , dummy ) ; <nl> } <nl> <nl> - inline Client : : ~ Client ( ) <nl> - { <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + Progress progress ) { <nl> + return Get ( path , Headers ( ) , progress ) ; <nl> } <nl> <nl> - inline bool Client : : is_valid ( ) const <nl> - { <nl> - return true ; <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + const Headers & headers ) { <nl> + Progress dummy ; <nl> + return Get ( path , headers , dummy ) ; <nl> } <nl> <nl> - inline socket_t Client : : create_client_socket ( ) const <nl> - { <nl> - return detail : : create_socket ( host_ . c_str ( ) , port_ , <nl> - [ = ] ( socket_t sock , struct addrinfo & ai ) - > bool { <nl> - detail : : set_nonblocking ( sock , true ) ; <nl> - <nl> - auto ret = connect ( sock , ai . ai_addr , ai . ai_addrlen ) ; <nl> - if ( ret < 0 ) { <nl> - if ( detail : : is_connection_error ( ) | | <nl> - ! detail : : wait_until_socket_is_ready ( sock , timeout_sec_ , 0 ) ) { <nl> - detail : : close_socket ( sock ) ; <nl> - return false ; <nl> - } <nl> - } <nl> + inline std : : shared_ptr < Response > <nl> + Client : : Get ( const char * path , const Headers & headers , Progress progress ) { <nl> + Request req ; <nl> + req . method = " GET " ; <nl> + req . path = path ; <nl> + req . headers = headers ; <nl> + req . progress = progress ; <nl> <nl> - detail : : set_nonblocking ( sock , false ) ; <nl> - return true ; <nl> - } ) ; <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> } <nl> <nl> - inline bool Client : : read_response_line ( Stream & strm , Response & res ) <nl> - { <nl> - const auto bufsiz = 2048 ; <nl> - char buf [ bufsiz ] ; <nl> - <nl> - detail : : stream_line_reader reader ( strm , buf , bufsiz ) ; <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + ContentReceiver content_receiver ) { <nl> + Progress dummy ; <nl> + return Get ( path , Headers ( ) , nullptr , content_receiver , dummy ) ; <nl> + } <nl> <nl> - if ( ! reader . getline ( ) ) { <nl> - return false ; <nl> - } <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + ContentReceiver content_receiver , <nl> + Progress progress ) { <nl> + return Get ( path , Headers ( ) , nullptr , content_receiver , progress ) ; <nl> + } <nl> <nl> - const static std : : regex re ( " ( HTTP / 1 \ \ . [ 01 ] ) ( \ \ d + ? ) . + \ r \ n " ) ; <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + const Headers & headers , <nl> + ContentReceiver content_receiver ) { <nl> + Progress dummy ; <nl> + return Get ( path , headers , nullptr , content_receiver , dummy ) ; <nl> + } <nl> <nl> - std : : cmatch m ; <nl> - if ( std : : regex_match ( reader . ptr ( ) , m , re ) ) { <nl> - res . version = std : : string ( m [ 1 ] ) ; <nl> - res . status = std : : stoi ( std : : string ( m [ 2 ] ) ) ; <nl> - } <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + const Headers & headers , <nl> + ContentReceiver content_receiver , <nl> + Progress progress ) { <nl> + return Get ( path , headers , nullptr , content_receiver , progress ) ; <nl> + } <nl> <nl> - return true ; <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + const Headers & headers , <nl> + ResponseHandler response_handler , <nl> + ContentReceiver content_receiver ) { <nl> + Progress dummy ; <nl> + return Get ( path , headers , response_handler , content_receiver , dummy ) ; <nl> } <nl> <nl> - inline bool Client : : send ( Request & req , Response & res ) <nl> - { <nl> - if ( req . path . empty ( ) ) { <nl> - return false ; <nl> - } <nl> + inline std : : shared_ptr < Response > Client : : Get ( const char * path , <nl> + const Headers & headers , <nl> + ResponseHandler response_handler , <nl> + ContentReceiver content_receiver , <nl> + Progress progress ) { <nl> + Request req ; <nl> + req . method = " GET " ; <nl> + req . path = path ; <nl> + req . headers = headers ; <nl> + req . response_handler = response_handler ; <nl> + req . content_receiver = content_receiver ; <nl> + req . progress = progress ; <nl> <nl> - auto sock = create_client_socket ( ) ; <nl> - if ( sock = = INVALID_SOCKET ) { <nl> - return false ; <nl> - } <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> + } <nl> <nl> - return read_and_close_socket ( sock , req , res ) ; <nl> + inline std : : shared_ptr < Response > Client : : Head ( const char * path ) { <nl> + return Head ( path , Headers ( ) ) ; <nl> } <nl> <nl> - inline void Client : : write_request ( Stream & strm , Request & req ) <nl> - { <nl> - auto path = detail : : encode_url ( req . path ) ; <nl> + inline std : : shared_ptr < Response > Client : : Head ( const char * path , <nl> + const Headers & headers ) { <nl> + Request req ; <nl> + req . method = " HEAD " ; <nl> + req . headers = headers ; <nl> + req . path = path ; <nl> <nl> - / / Request line <nl> - strm . write_format ( " % s % s HTTP / 1 . 1 \ r \ n " , <nl> - req . method . c_str ( ) , <nl> - path . c_str ( ) ) ; <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - / / Headers <nl> - req . set_header ( " Host " , host_and_port_ . c_str ( ) ) ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> + } <nl> <nl> - if ( ! req . has_header ( " Accept " ) ) { <nl> - req . set_header ( " Accept " , " * / * " ) ; <nl> - } <nl> + inline std : : shared_ptr < Response > Client : : Post ( const char * path , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + return Post ( path , Headers ( ) , body , content_type ) ; <nl> + } <nl> <nl> - if ( ! req . has_header ( " User - Agent " ) ) { <nl> - req . set_header ( " User - Agent " , " cpp - httplib / 0 . 2 " ) ; <nl> - } <nl> + inline std : : shared_ptr < Response > Client : : Post ( const char * path , <nl> + const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + Request req ; <nl> + req . method = " POST " ; <nl> + req . headers = headers ; <nl> + req . path = path ; <nl> <nl> - / / TODO : Support KeepAlive connection <nl> - / / if ( ! req . has_header ( " Connection " ) ) { <nl> - req . set_header ( " Connection " , " close " ) ; <nl> - / / } <nl> + req . headers . emplace ( " Content - Type " , content_type ) ; <nl> + req . body = body ; <nl> <nl> - if ( ! req . body . empty ( ) ) { <nl> - if ( ! req . has_header ( " Content - Type " ) ) { <nl> - req . set_header ( " Content - Type " , " text / plain " ) ; <nl> - } <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - auto length = std : : to_string ( req . body . size ( ) ) ; <nl> - req . set_header ( " Content - Length " , length . c_str ( ) ) ; <nl> - } <nl> + return send ( req , * res ) ? res : nullptr ; <nl> + } <nl> <nl> - detail : : write_headers ( strm , req ) ; <nl> + inline std : : shared_ptr < Response > Client : : Post ( const char * path , <nl> + const Params & params ) { <nl> + return Post ( path , Headers ( ) , params ) ; <nl> + } <nl> <nl> - / / Body <nl> - if ( ! req . body . empty ( ) ) { <nl> - if ( req . get_header_value ( " Content - Type " ) = = " application / x - www - form - urlencoded " ) { <nl> - auto str = detail : : encode_url ( req . body ) ; <nl> - strm . write ( str . c_str ( ) , str . size ( ) ) ; <nl> - } else { <nl> - strm . write ( req . body . c_str ( ) , req . body . size ( ) ) ; <nl> - } <nl> - } <nl> + inline std : : shared_ptr < Response > <nl> + Client : : Post ( const char * path , const Headers & headers , const Params & params ) { <nl> + std : : string query ; <nl> + for ( auto it = params . begin ( ) ; it ! = params . end ( ) ; + + it ) { <nl> + if ( it ! = params . begin ( ) ) { query + = " & " ; } <nl> + query + = it - > first ; <nl> + query + = " = " ; <nl> + query + = detail : : encode_url ( it - > second ) ; <nl> + } <nl> + <nl> + return Post ( path , headers , query , " application / x - www - form - urlencoded " ) ; <nl> } <nl> <nl> - inline bool Client : : process_request ( Stream & strm , Request & req , Response & res , bool & connection_close ) <nl> - { <nl> - / / Send request <nl> - write_request ( strm , req ) ; <nl> + inline std : : shared_ptr < Response > <nl> + Client : : Post ( const char * path , const MultipartFormDataItems & items ) { <nl> + return Post ( path , Headers ( ) , items ) ; <nl> + } <nl> <nl> - / / Receive response and headers <nl> - if ( ! read_response_line ( strm , res ) | | ! detail : : read_headers ( strm , res . headers ) ) { <nl> - return false ; <nl> - } <nl> + inline std : : shared_ptr < Response > <nl> + Client : : Post ( const char * path , const Headers & headers , <nl> + const MultipartFormDataItems & items ) { <nl> + Request req ; <nl> + req . method = " POST " ; <nl> + req . headers = headers ; <nl> + req . path = path ; <nl> <nl> - if ( res . get_header_value ( " Connection " ) = = " close " | | res . version = = " HTTP / 1 . 0 " ) { <nl> - connection_close = true ; <nl> - } <nl> + auto boundary = detail : : make_multipart_data_boundary ( ) ; <nl> <nl> - / / Body <nl> - if ( req . method ! = " HEAD " ) { <nl> - if ( ! detail : : read_content ( strm , res , req . progress ) ) { <nl> - return false ; <nl> - } <nl> + req . headers . emplace ( " Content - Type " , <nl> + " multipart / form - data ; boundary = " + boundary ) ; <nl> <nl> - if ( res . get_header_value ( " Content - Encoding " ) = = " gzip " ) { <nl> - # ifdef CPPHTTPLIB_ZLIB_SUPPORT <nl> - detail : : decompress ( res . body ) ; <nl> - # else <nl> - return false ; <nl> - # endif <nl> - } <nl> + for ( const auto & item : items ) { <nl> + req . body + = " - - " + boundary + " \ r \ n " ; <nl> + req . body + = " Content - Disposition : form - data ; name = \ " " + item . name + " \ " " ; <nl> + if ( ! item . filename . empty ( ) ) { <nl> + req . body + = " ; filename = \ " " + item . filename + " \ " " ; <nl> } <nl> + req . body + = " \ r \ n " ; <nl> + if ( ! item . content_type . empty ( ) ) { <nl> + req . body + = " Content - Type : " + item . content_type + " \ r \ n " ; <nl> + } <nl> + req . body + = " \ r \ n " ; <nl> + req . body + = item . content + " \ r \ n " ; <nl> + } <nl> <nl> - return true ; <nl> - } <nl> + req . body + = " - - " + boundary + " - - \ r \ n " ; <nl> <nl> - inline bool Client : : read_and_close_socket ( socket_t sock , Request & req , Response & res ) <nl> - { <nl> - return detail : : read_and_close_socket ( <nl> - sock , <nl> - 0 , <nl> - [ & ] ( Stream & strm , bool / * last_connection * / , bool & connection_close ) { <nl> - return process_request ( strm , req , res , connection_close ) ; <nl> - } ) ; <nl> - } <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - inline std : : shared_ptr < Response > Client : : Get ( const char * path , Progress progress ) <nl> - { <nl> - return Get ( path , Headers ( ) , progress ) ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Get ( const char * path , const Headers & headers , Progress progress ) <nl> - { <nl> - Request req ; <nl> - req . method = " GET " ; <nl> - req . path = path ; <nl> - req . headers = headers ; <nl> - req . progress = progress ; <nl> - <nl> - auto res = std : : make_shared < Response > ( ) ; <nl> - <nl> - return send ( req , * res ) ? res : nullptr ; <nl> + inline std : : shared_ptr < Response > Client : : Put ( const char * path , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + return Put ( path , Headers ( ) , body , content_type ) ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Head ( const char * path ) <nl> - { <nl> - return Head ( path , Headers ( ) ) ; <nl> - } <nl> + inline std : : shared_ptr < Response > Client : : Put ( const char * path , <nl> + const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + Request req ; <nl> + req . method = " PUT " ; <nl> + req . headers = headers ; <nl> + req . path = path ; <nl> <nl> - inline std : : shared_ptr < Response > Client : : Head ( const char * path , const Headers & headers ) <nl> - { <nl> - Request req ; <nl> - req . method = " HEAD " ; <nl> - req . headers = headers ; <nl> - req . path = path ; <nl> + req . headers . emplace ( " Content - Type " , content_type ) ; <nl> + req . body = body ; <nl> <nl> - auto res = std : : make_shared < Response > ( ) ; <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - return send ( req , * res ) ? res : nullptr ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Post ( <nl> - const char * path , const std : : string & body , const char * content_type ) <nl> - { <nl> - return Post ( path , Headers ( ) , body , content_type ) ; <nl> + inline std : : shared_ptr < Response > Client : : Patch ( const char * path , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + return Patch ( path , Headers ( ) , body , content_type ) ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Post ( <nl> - const char * path , const Headers & headers , const std : : string & body , const char * content_type ) <nl> - { <nl> - Request req ; <nl> - req . method = " POST " ; <nl> - req . headers = headers ; <nl> - req . path = path ; <nl> + inline std : : shared_ptr < Response > Client : : Patch ( const char * path , <nl> + const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + Request req ; <nl> + req . method = " PATCH " ; <nl> + req . headers = headers ; <nl> + req . path = path ; <nl> <nl> - req . headers . emplace ( " Content - Type " , content_type ) ; <nl> - req . body = body ; <nl> + req . headers . emplace ( " Content - Type " , content_type ) ; <nl> + req . body = body ; <nl> <nl> - auto res = std : : make_shared < Response > ( ) ; <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - return send ( req , * res ) ? res : nullptr ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Post ( const char * path , const Params & params ) <nl> - { <nl> - return Post ( path , Headers ( ) , params ) ; <nl> + inline std : : shared_ptr < Response > Client : : Delete ( const char * path ) { <nl> + return Delete ( path , Headers ( ) , std : : string ( ) , nullptr ) ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Post ( const char * path , const Headers & headers , const Params & params ) <nl> - { <nl> - std : : string query ; <nl> - for ( auto it = params . begin ( ) ; it ! = params . end ( ) ; + + it ) { <nl> - if ( it ! = params . begin ( ) ) { <nl> - query + = " & " ; <nl> - } <nl> - query + = it - > first ; <nl> - query + = " = " ; <nl> - query + = it - > second ; <nl> - } <nl> - <nl> - return Post ( path , headers , query , " application / x - www - form - urlencoded " ) ; <nl> + inline std : : shared_ptr < Response > Client : : Delete ( const char * path , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + return Delete ( path , Headers ( ) , body , content_type ) ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Put ( <nl> - const char * path , const std : : string & body , const char * content_type ) <nl> - { <nl> - return Put ( path , Headers ( ) , body , content_type ) ; <nl> + inline std : : shared_ptr < Response > Client : : Delete ( const char * path , <nl> + const Headers & headers ) { <nl> + return Delete ( path , headers , std : : string ( ) , nullptr ) ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Put ( <nl> - const char * path , const Headers & headers , const std : : string & body , const char * content_type ) <nl> - { <nl> - Request req ; <nl> - req . method = " PUT " ; <nl> - req . headers = headers ; <nl> - req . path = path ; <nl> + inline std : : shared_ptr < Response > Client : : Delete ( const char * path , <nl> + const Headers & headers , <nl> + const std : : string & body , <nl> + const char * content_type ) { <nl> + Request req ; <nl> + req . method = " DELETE " ; <nl> + req . headers = headers ; <nl> + req . path = path ; <nl> <nl> - req . headers . emplace ( " Content - Type " , content_type ) ; <nl> - req . body = body ; <nl> + if ( content_type ) { req . headers . emplace ( " Content - Type " , content_type ) ; } <nl> + req . body = body ; <nl> <nl> - auto res = std : : make_shared < Response > ( ) ; <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - return send ( req , * res ) ? res : nullptr ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Delete ( const char * path ) <nl> - { <nl> - return Delete ( path , Headers ( ) ) ; <nl> + inline std : : shared_ptr < Response > Client : : Options ( const char * path ) { <nl> + return Options ( path , Headers ( ) ) ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Delete ( const char * path , const Headers & headers ) <nl> - { <nl> - Request req ; <nl> - req . method = " DELETE " ; <nl> - req . path = path ; <nl> - req . headers = headers ; <nl> + inline std : : shared_ptr < Response > Client : : Options ( const char * path , <nl> + const Headers & headers ) { <nl> + Request req ; <nl> + req . method = " OPTIONS " ; <nl> + req . path = path ; <nl> + req . headers = headers ; <nl> <nl> - auto res = std : : make_shared < Response > ( ) ; <nl> + auto res = std : : make_shared < Response > ( ) ; <nl> <nl> - return send ( req , * res ) ? res : nullptr ; <nl> + return send ( req , * res ) ? res : nullptr ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Options ( const char * path ) <nl> - { <nl> - return Options ( path , Headers ( ) ) ; <nl> + inline void Client : : set_keep_alive_max_count ( size_t count ) { <nl> + keep_alive_max_count_ = count ; <nl> } <nl> <nl> - inline std : : shared_ptr < Response > Client : : Options ( const char * path , const Headers & headers ) <nl> - { <nl> - Request req ; <nl> - req . method = " OPTIONS " ; <nl> - req . path = path ; <nl> - req . headers = headers ; <nl> - <nl> - auto res = std : : make_shared < Response > ( ) ; <nl> - <nl> - return send ( req , * res ) ? res : nullptr ; <nl> - } <nl> + inline void Client : : follow_location ( bool on ) { follow_location_ = on ; } <nl> <nl> / * <nl> * SSL Implementation <nl> inline std : : shared_ptr < Response > Client : : Options ( const char * path , const Headers <nl> namespace detail { <nl> <nl> template < typename U , typename V , typename T > <nl> - inline bool read_and_close_socket_ssl ( <nl> - socket_t sock , size_t keep_alive_max_count , <nl> - / / TODO : OpenSSL 1 . 0 . 2 occasionally crashes . . . <nl> - / / The upcoming 1 . 1 . 0 is going to be thread safe . <nl> - SSL_CTX * ctx , std : : mutex & ctx_mutex , <nl> - U SSL_connect_or_accept , V setup , <nl> - T callback ) <nl> - { <nl> - SSL * ssl = nullptr ; <nl> - { <nl> - std : : lock_guard < std : : mutex > guard ( ctx_mutex ) ; <nl> - <nl> - ssl = SSL_new ( ctx ) ; <nl> - if ( ! ssl ) { <nl> - return false ; <nl> - } <nl> - } <nl> + inline bool process_and_close_socket_ssl ( bool is_client_request , socket_t sock , <nl> + size_t keep_alive_max_count , <nl> + SSL_CTX * ctx , std : : mutex & ctx_mutex , <nl> + U SSL_connect_or_accept , V setup , <nl> + T callback ) { <nl> + assert ( keep_alive_max_count > 0 ) ; <nl> + <nl> + SSL * ssl = nullptr ; <nl> + { <nl> + std : : lock_guard < std : : mutex > guard ( ctx_mutex ) ; <nl> + ssl = SSL_new ( ctx ) ; <nl> + } <nl> + <nl> + if ( ! ssl ) { <nl> + close_socket ( sock ) ; <nl> + return false ; <nl> + } <nl> <nl> - auto bio = BIO_new_socket ( sock , BIO_NOCLOSE ) ; <nl> - SSL_set_bio ( ssl , bio , bio ) ; <nl> + auto bio = BIO_new_socket ( static_cast < int > ( sock ) , BIO_NOCLOSE ) ; <nl> + SSL_set_bio ( ssl , bio , bio ) ; <nl> <nl> - setup ( ssl ) ; <nl> + if ( ! setup ( ssl ) ) { <nl> + SSL_shutdown ( ssl ) ; <nl> + { <nl> + std : : lock_guard < std : : mutex > guard ( ctx_mutex ) ; <nl> + SSL_free ( ssl ) ; <nl> + } <nl> <nl> - SSL_connect_or_accept ( ssl ) ; <nl> + close_socket ( sock ) ; <nl> + return false ; <nl> + } <nl> <nl> - bool ret = false ; <nl> + bool ret = false ; <nl> <nl> - if ( keep_alive_max_count > 0 ) { <nl> - auto count = keep_alive_max_count ; <nl> - while ( count > 0 & & <nl> - detail : : select_read ( sock , <nl> - CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND , <nl> - CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND ) > 0 ) { <nl> - SSLSocketStream strm ( sock , ssl ) ; <nl> - auto last_connection = count = = 1 ; <nl> - auto connection_close = false ; <nl> + if ( SSL_connect_or_accept ( ssl ) = = 1 ) { <nl> + if ( keep_alive_max_count > 1 ) { <nl> + auto count = keep_alive_max_count ; <nl> + while ( count > 0 & & <nl> + ( is_client_request | | <nl> + detail : : select_read ( sock , CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND , <nl> + CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND ) > 0 ) ) { <nl> + SSLSocketStream strm ( sock , ssl ) ; <nl> + auto last_connection = count = = 1 ; <nl> + auto connection_close = false ; <nl> <nl> - ret = callback ( strm , last_connection , connection_close ) ; <nl> - if ( ! ret | | connection_close ) { <nl> - break ; <nl> - } <nl> + ret = callback ( ssl , strm , last_connection , connection_close ) ; <nl> + if ( ! ret | | connection_close ) { break ; } <nl> <nl> - count - - ; <nl> - } <nl> + count - - ; <nl> + } <nl> } else { <nl> - SSLSocketStream strm ( sock , ssl ) ; <nl> - auto dummy_connection_close = false ; <nl> - ret = callback ( strm , true , dummy_connection_close ) ; <nl> + SSLSocketStream strm ( sock , ssl ) ; <nl> + auto dummy_connection_close = false ; <nl> + ret = callback ( ssl , strm , true , dummy_connection_close ) ; <nl> } <nl> + } <nl> <nl> - SSL_shutdown ( ssl ) ; <nl> - <nl> - { <nl> - std : : lock_guard < std : : mutex > guard ( ctx_mutex ) ; <nl> - SSL_free ( ssl ) ; <nl> - } <nl> + SSL_shutdown ( ssl ) ; <nl> + { <nl> + std : : lock_guard < std : : mutex > guard ( ctx_mutex ) ; <nl> + SSL_free ( ssl ) ; <nl> + } <nl> <nl> - close_socket ( sock ) ; <nl> + close_socket ( sock ) ; <nl> <nl> - return ret ; <nl> + return ret ; <nl> } <nl> <nl> - class SSLInit { <nl> + # if OPENSSL_VERSION_NUMBER < 0x10100000L <nl> + static std : : shared_ptr < std : : vector < std : : mutex > > openSSL_locks_ ; <nl> + <nl> + class SSLThreadLocks { <nl> public : <nl> - SSLInit ( ) { <nl> - SSL_load_error_strings ( ) ; <nl> - SSL_library_init ( ) ; <nl> + SSLThreadLocks ( ) { <nl> + openSSL_locks_ = <nl> + std : : make_shared < std : : vector < std : : mutex > > ( CRYPTO_num_locks ( ) ) ; <nl> + CRYPTO_set_locking_callback ( locking_callback ) ; <nl> + } <nl> + <nl> + ~ SSLThreadLocks ( ) { CRYPTO_set_locking_callback ( nullptr ) ; } <nl> + <nl> + private : <nl> + static void locking_callback ( int mode , int type , const char * / * file * / , <nl> + int / * line * / ) { <nl> + auto & locks = * openSSL_locks_ ; <nl> + if ( mode & CRYPTO_LOCK ) { <nl> + locks [ type ] . lock ( ) ; <nl> + } else { <nl> + locks [ type ] . unlock ( ) ; <nl> } <nl> + } <nl> + } ; <nl> + <nl> + # endif <nl> + <nl> + class SSLInit { <nl> + public : <nl> + SSLInit ( ) { <nl> + SSL_load_error_strings ( ) ; <nl> + SSL_library_init ( ) ; <nl> + } <nl> + <nl> + ~ SSLInit ( ) { ERR_free_strings ( ) ; } <nl> + <nl> + private : <nl> + # if OPENSSL_VERSION_NUMBER < 0x10100000L <nl> + SSLThreadLocks thread_init_ ; <nl> + # endif <nl> } ; <nl> <nl> static SSLInit sslinit_ ; <nl> static SSLInit sslinit_ ; <nl> } / / namespace detail <nl> <nl> / / SSL socket stream implementation <nl> - inline SSLSocketStream : : SSLSocketStream ( socket_t sock , SSL * ssl ) <nl> - : sock_ ( sock ) , ssl_ ( ssl ) <nl> - { <nl> - } <nl> + inline SSLSocketStream : : SSLSocketStream ( socket_t sock , SSL * ssl ) <nl> + : sock_ ( sock ) , ssl_ ( ssl ) { } <nl> + <nl> + inline SSLSocketStream : : ~ SSLSocketStream ( ) { } <nl> <nl> - inline SSLSocketStream : : ~ SSLSocketStream ( ) <nl> - { <nl> + inline int SSLSocketStream : : read ( char * ptr , size_t size ) { <nl> + if ( SSL_pending ( ssl_ ) > 0 | | <nl> + detail : : select_read ( sock_ , CPPHTTPLIB_READ_TIMEOUT_SECOND , <nl> + CPPHTTPLIB_READ_TIMEOUT_USECOND ) > 0 ) { <nl> + return SSL_read ( ssl_ , ptr , static_cast < int > ( size ) ) ; <nl> + } <nl> + return - 1 ; <nl> } <nl> <nl> - inline int SSLSocketStream : : read ( char * ptr , size_t size ) <nl> - { <nl> - return SSL_read ( ssl_ , ptr , size ) ; <nl> + inline int SSLSocketStream : : write ( const char * ptr , size_t size ) { <nl> + return SSL_write ( ssl_ , ptr , static_cast < int > ( size ) ) ; <nl> } <nl> <nl> - inline int SSLSocketStream : : write ( const char * ptr , size_t size ) <nl> - { <nl> - return SSL_write ( ssl_ , ptr , size ) ; <nl> + inline int SSLSocketStream : : write ( const char * ptr ) { <nl> + return write ( ptr , strlen ( ptr ) ) ; <nl> } <nl> <nl> - inline int SSLSocketStream : : write ( const char * ptr ) <nl> - { <nl> - return write ( ptr , strlen ( ptr ) ) ; <nl> + inline int SSLSocketStream : : write ( const std : : string & s ) { <nl> + return write ( s . data ( ) , s . size ( ) ) ; <nl> } <nl> <nl> - inline std : : string SSLSocketStream : : get_remote_addr ( ) { <nl> - return detail : : get_remote_addr ( sock_ ) ; <nl> + inline std : : string SSLSocketStream : : get_remote_addr ( ) const { <nl> + return detail : : get_remote_addr ( sock_ ) ; <nl> } <nl> <nl> / / SSL HTTP server implementation <nl> - inline SSLServer : : SSLServer ( const char * cert_path , const char * private_key_path ) <nl> - { <nl> - ctx_ = SSL_CTX_new ( SSLv23_server_method ( ) ) ; <nl> - <nl> - if ( ctx_ ) { <nl> - SSL_CTX_set_options ( ctx_ , <nl> - SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | <nl> + inline SSLServer : : SSLServer ( const char * cert_path , const char * private_key_path , <nl> + const char * client_ca_cert_file_path , <nl> + const char * client_ca_cert_dir_path ) { <nl> + ctx_ = SSL_CTX_new ( SSLv23_server_method ( ) ) ; <nl> + <nl> + if ( ctx_ ) { <nl> + SSL_CTX_set_options ( ctx_ , <nl> + SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | <nl> SSL_OP_NO_COMPRESSION | <nl> SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION ) ; <nl> <nl> - / / auto ecdh = EC_KEY_new_by_curve_name ( NID_X9_62_prime256v1 ) ; <nl> - / / SSL_CTX_set_tmp_ecdh ( ctx_ , ecdh ) ; <nl> - / / EC_KEY_free ( ecdh ) ; <nl> + / / auto ecdh = EC_KEY_new_by_curve_name ( NID_X9_62_prime256v1 ) ; <nl> + / / SSL_CTX_set_tmp_ecdh ( ctx_ , ecdh ) ; <nl> + / / EC_KEY_free ( ecdh ) ; <nl> <nl> - if ( SSL_CTX_use_certificate_file ( ctx_ , cert_path , SSL_FILETYPE_PEM ) ! = 1 | | <nl> - SSL_CTX_use_PrivateKey_file ( ctx_ , private_key_path , SSL_FILETYPE_PEM ) ! = 1 ) { <nl> - SSL_CTX_free ( ctx_ ) ; <nl> - ctx_ = nullptr ; <nl> - } <nl> + if ( SSL_CTX_use_certificate_chain_file ( ctx_ , cert_path ) ! = 1 | | <nl> + SSL_CTX_use_PrivateKey_file ( ctx_ , private_key_path , SSL_FILETYPE_PEM ) ! = <nl> + 1 ) { <nl> + SSL_CTX_free ( ctx_ ) ; <nl> + ctx_ = nullptr ; <nl> + } else if ( client_ca_cert_file_path | | client_ca_cert_dir_path ) { <nl> + / / if ( client_ca_cert_file_path ) { <nl> + / / auto list = SSL_load_client_CA_file ( client_ca_cert_file_path ) ; <nl> + / / SSL_CTX_set_client_CA_list ( ctx_ , list ) ; <nl> + / / } <nl> + <nl> + SSL_CTX_load_verify_locations ( ctx_ , client_ca_cert_file_path , <nl> + client_ca_cert_dir_path ) ; <nl> + <nl> + SSL_CTX_set_verify ( <nl> + ctx_ , <nl> + SSL_VERIFY_PEER | <nl> + SSL_VERIFY_FAIL_IF_NO_PEER_CERT , / / SSL_VERIFY_CLIENT_ONCE , <nl> + nullptr ) ; <nl> } <nl> + } <nl> + } <nl> + <nl> + inline SSLServer : : ~ SSLServer ( ) { <nl> + if ( ctx_ ) { SSL_CTX_free ( ctx_ ) ; } <nl> } <nl> <nl> - inline SSLServer : : ~ SSLServer ( ) <nl> - { <nl> - if ( ctx_ ) { <nl> - SSL_CTX_free ( ctx_ ) ; <nl> + inline bool SSLServer : : is_valid ( ) const { return ctx_ ; } <nl> + <nl> + inline bool SSLServer : : process_and_close_socket ( socket_t sock ) { <nl> + return detail : : process_and_close_socket_ssl ( <nl> + false , sock , keep_alive_max_count_ , ctx_ , ctx_mutex_ , SSL_accept , <nl> + [ ] ( SSL * / * ssl * / ) { return true ; } , <nl> + [ this ] ( SSL * ssl , Stream & strm , bool last_connection , <nl> + bool & connection_close ) { <nl> + return process_request ( strm , last_connection , connection_close , <nl> + [ & ] ( Request & req ) { req . ssl = ssl ; } ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + / / SSL HTTP client implementation <nl> + inline SSLClient : : SSLClient ( const char * host , int port , time_t timeout_sec , <nl> + const char * client_cert_path , <nl> + const char * client_key_path ) <nl> + : Client ( host , port , timeout_sec ) { <nl> + ctx_ = SSL_CTX_new ( SSLv23_client_method ( ) ) ; <nl> + <nl> + detail : : split ( & host_ [ 0 ] , & host_ [ host_ . size ( ) ] , ' . ' , <nl> + [ & ] ( const char * b , const char * e ) { <nl> + host_components_ . emplace_back ( std : : string ( b , e ) ) ; <nl> + } ) ; <nl> + if ( client_cert_path & & client_key_path ) { <nl> + if ( SSL_CTX_use_certificate_file ( ctx_ , client_cert_path , <nl> + SSL_FILETYPE_PEM ) ! = 1 | | <nl> + SSL_CTX_use_PrivateKey_file ( ctx_ , client_key_path , SSL_FILETYPE_PEM ) ! = <nl> + 1 ) { <nl> + SSL_CTX_free ( ctx_ ) ; <nl> + ctx_ = nullptr ; <nl> } <nl> + } <nl> } <nl> <nl> - inline bool SSLServer : : is_valid ( ) const <nl> - { <nl> - return ctx_ ; <nl> + inline SSLClient : : ~ SSLClient ( ) { <nl> + if ( ctx_ ) { SSL_CTX_free ( ctx_ ) ; } <nl> } <nl> <nl> - inline bool SSLServer : : read_and_close_socket ( socket_t sock ) <nl> - { <nl> - return detail : : read_and_close_socket_ssl ( <nl> - sock , <nl> - keep_alive_max_count_ , <nl> - ctx_ , ctx_mutex_ , <nl> - SSL_accept , <nl> - [ ] ( SSL * / * ssl * / ) { } , <nl> - [ this ] ( Stream & strm , bool last_connection , bool & connection_close ) { <nl> - return process_request ( strm , last_connection , connection_close ) ; <nl> - } ) ; <nl> + inline bool SSLClient : : is_valid ( ) const { return ctx_ ; } <nl> + <nl> + inline void SSLClient : : set_ca_cert_path ( const char * ca_cert_file_path , <nl> + const char * ca_cert_dir_path ) { <nl> + if ( ca_cert_file_path ) { ca_cert_file_path_ = ca_cert_file_path ; } <nl> + if ( ca_cert_dir_path ) { ca_cert_dir_path_ = ca_cert_dir_path ; } <nl> } <nl> <nl> - / / SSL HTTP client implementation <nl> - inline SSLClient : : SSLClient ( const char * host , int port , size_t timeout_sec ) <nl> - : Client ( host , port , timeout_sec ) <nl> - { <nl> - ctx_ = SSL_CTX_new ( SSLv23_client_method ( ) ) ; <nl> + inline void SSLClient : : enable_server_certificate_verification ( bool enabled ) { <nl> + server_certificate_verification_ = enabled ; <nl> } <nl> <nl> - inline SSLClient : : ~ SSLClient ( ) <nl> - { <nl> - if ( ctx_ ) { <nl> - SSL_CTX_free ( ctx_ ) ; <nl> - } <nl> + inline long SSLClient : : get_openssl_verify_result ( ) const { <nl> + return verify_result_ ; <nl> } <nl> <nl> - inline bool SSLClient : : is_valid ( ) const <nl> - { <nl> - return ctx_ ; <nl> + inline SSL_CTX * SSLClient : : ssl_context ( ) const noexcept { <nl> + return ctx_ ; <nl> } <nl> <nl> - inline bool SSLClient : : read_and_close_socket ( socket_t sock , Request & req , Response & res ) <nl> - { <nl> - return is_valid ( ) & & detail : : read_and_close_socket_ssl ( <nl> - sock , 0 , <nl> - ctx_ , ctx_mutex_ , <nl> - SSL_connect , <nl> - [ & ] ( SSL * ssl ) { <nl> - SSL_set_tlsext_host_name ( ssl , host_ . c_str ( ) ) ; <nl> - } , <nl> - [ & ] ( Stream & strm , bool / * last_connection * / , bool & connection_close ) { <nl> - return process_request ( strm , req , res , connection_close ) ; <nl> - } ) ; <nl> + inline bool SSLClient : : process_and_close_socket ( <nl> + socket_t sock , size_t request_count , <nl> + std : : function < bool ( Stream & strm , bool last_connection , <nl> + bool & connection_close ) > <nl> + callback ) { <nl> + <nl> + request_count = std : : min ( request_count , keep_alive_max_count_ ) ; <nl> + <nl> + return is_valid ( ) & & <nl> + detail : : process_and_close_socket_ssl ( <nl> + true , sock , request_count , ctx_ , ctx_mutex_ , <nl> + [ & ] ( SSL * ssl ) { <nl> + if ( ca_cert_file_path_ . empty ( ) ) { <nl> + SSL_CTX_set_verify ( ctx_ , SSL_VERIFY_NONE , nullptr ) ; <nl> + } else { <nl> + if ( ! SSL_CTX_load_verify_locations ( <nl> + ctx_ , ca_cert_file_path_ . c_str ( ) , nullptr ) ) { <nl> + return false ; <nl> + } <nl> + SSL_CTX_set_verify ( ctx_ , SSL_VERIFY_PEER , nullptr ) ; <nl> + } <nl> + <nl> + if ( SSL_connect ( ssl ) ! = 1 ) { return false ; } <nl> + <nl> + if ( server_certificate_verification_ ) { <nl> + verify_result_ = SSL_get_verify_result ( ssl ) ; <nl> + <nl> + if ( verify_result_ ! = X509_V_OK ) { return false ; } <nl> + <nl> + auto server_cert = SSL_get_peer_certificate ( ssl ) ; <nl> + <nl> + if ( server_cert = = nullptr ) { return false ; } <nl> + <nl> + if ( ! verify_host ( server_cert ) ) { <nl> + X509_free ( server_cert ) ; <nl> + return false ; <nl> + } <nl> + X509_free ( server_cert ) ; <nl> + } <nl> + <nl> + return true ; <nl> + } , <nl> + [ & ] ( SSL * ssl ) { <nl> + SSL_set_tlsext_host_name ( ssl , host_ . c_str ( ) ) ; <nl> + return true ; <nl> + } , <nl> + [ & ] ( SSL * / * ssl * / , Stream & strm , bool last_connection , <nl> + bool & connection_close ) { <nl> + return callback ( strm , last_connection , connection_close ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + inline bool SSLClient : : is_ssl ( ) const { return true ; } <nl> + <nl> + inline bool SSLClient : : verify_host ( X509 * server_cert ) const { <nl> + / * Quote from RFC2818 section 3 . 1 " Server Identity " <nl> + <nl> + If a subjectAltName extension of type dNSName is present , that MUST <nl> + be used as the identity . Otherwise , the ( most specific ) Common Name <nl> + field in the Subject field of the certificate MUST be used . Although <nl> + the use of the Common Name is existing practice , it is deprecated and <nl> + Certification Authorities are encouraged to use the dNSName instead . <nl> + <nl> + Matching is performed using the matching rules specified by <nl> + [ RFC2459 ] . If more than one identity of a given type is present in <nl> + the certificate ( e . g . , more than one dNSName name , a match in any one <nl> + of the set is considered acceptable . ) Names may contain the wildcard <nl> + character * which is considered to match any single domain name <nl> + component or component fragment . E . g . , * . a . com matches foo . a . com but <nl> + not bar . foo . a . com . f * . com matches foo . com but not bar . com . <nl> + <nl> + In some cases , the URI is specified as an IP address rather than a <nl> + hostname . In this case , the iPAddress subjectAltName must be present <nl> + in the certificate and must exactly match the IP in the URI . <nl> + <nl> + * / <nl> + return verify_host_with_subject_alt_name ( server_cert ) | | <nl> + verify_host_with_common_name ( server_cert ) ; <nl> } <nl> + <nl> + inline bool <nl> + SSLClient : : verify_host_with_subject_alt_name ( X509 * server_cert ) const { <nl> + auto ret = false ; <nl> + <nl> + auto type = GEN_DNS ; <nl> + <nl> + struct in6_addr addr6 ; <nl> + struct in_addr addr ; <nl> + size_t addr_len = 0 ; <nl> + <nl> + # ifndef __MINGW32__ <nl> + if ( inet_pton ( AF_INET6 , host_ . c_str ( ) , & addr6 ) ) { <nl> + type = GEN_IPADD ; <nl> + addr_len = sizeof ( struct in6_addr ) ; <nl> + } else if ( inet_pton ( AF_INET , host_ . c_str ( ) , & addr ) ) { <nl> + type = GEN_IPADD ; <nl> + addr_len = sizeof ( struct in_addr ) ; <nl> + } <nl> # endif <nl> <nl> - } / / namespace httplib <nl> + auto alt_names = static_cast < const struct stack_st_GENERAL_NAME * > ( <nl> + X509_get_ext_d2i ( server_cert , NID_subject_alt_name , nullptr , nullptr ) ) ; <nl> + <nl> + if ( alt_names ) { <nl> + auto dsn_matched = false ; <nl> + auto ip_mached = false ; <nl> + <nl> + auto count = sk_GENERAL_NAME_num ( alt_names ) ; <nl> + <nl> + for ( auto i = 0 ; i < count & & ! dsn_matched ; i + + ) { <nl> + auto val = sk_GENERAL_NAME_value ( alt_names , i ) ; <nl> + if ( val - > type = = type ) { <nl> + auto name = ( const char * ) ASN1_STRING_get0_data ( val - > d . ia5 ) ; <nl> + auto name_len = ( size_t ) ASN1_STRING_length ( val - > d . ia5 ) ; <nl> + <nl> + if ( strlen ( name ) = = name_len ) { <nl> + switch ( type ) { <nl> + case GEN_DNS : dsn_matched = check_host_name ( name , name_len ) ; break ; <nl> + <nl> + case GEN_IPADD : <nl> + if ( ! memcmp ( & addr6 , name , addr_len ) | | <nl> + ! memcmp ( & addr , name , addr_len ) ) { <nl> + ip_mached = true ; <nl> + } <nl> + break ; <nl> + } <nl> + } <nl> + } <nl> + } <nl> + <nl> + if ( dsn_matched | | ip_mached ) { ret = true ; } <nl> + } <nl> + <nl> + GENERAL_NAMES_free ( ( STACK_OF ( GENERAL_NAME ) * ) alt_names ) ; <nl> <nl> + return ret ; <nl> + } <nl> + <nl> + inline bool SSLClient : : verify_host_with_common_name ( X509 * server_cert ) const { <nl> + const auto subject_name = X509_get_subject_name ( server_cert ) ; <nl> + <nl> + if ( subject_name ! = nullptr ) { <nl> + char name [ BUFSIZ ] ; <nl> + auto name_len = X509_NAME_get_text_by_NID ( subject_name , NID_commonName , <nl> + name , sizeof ( name ) ) ; <nl> + <nl> + if ( name_len ! = - 1 ) { return check_host_name ( name , name_len ) ; } <nl> + } <nl> + <nl> + return false ; <nl> + } <nl> + <nl> + inline bool SSLClient : : check_host_name ( const char * pattern , <nl> + size_t pattern_len ) const { <nl> + if ( host_ . size ( ) = = pattern_len & & host_ = = pattern ) { return true ; } <nl> + <nl> + / / Wildcard match <nl> + / / https : / / bugs . launchpad . net / ubuntu / + source / firefox - 3 . 0 / + bug / 376484 <nl> + std : : vector < std : : string > pattern_components ; <nl> + detail : : split ( & pattern [ 0 ] , & pattern [ pattern_len ] , ' . ' , <nl> + [ & ] ( const char * b , const char * e ) { <nl> + pattern_components . emplace_back ( std : : string ( b , e ) ) ; <nl> + } ) ; <nl> + <nl> + if ( host_components_ . size ( ) ! = pattern_components . size ( ) ) { return false ; } <nl> + <nl> + auto itr = pattern_components . begin ( ) ; <nl> + for ( const auto & h : host_components_ ) { <nl> + auto & p = * itr ; <nl> + if ( p ! = h & & p ! = " * " ) { <nl> + auto partial_match = ( p . size ( ) > 0 & & p [ p . size ( ) - 1 ] = = ' * ' & & <nl> + ! p . compare ( 0 , p . size ( ) - 1 , h ) ) ; <nl> + if ( ! partial_match ) { return false ; } <nl> + } <nl> + + + itr ; <nl> + } <nl> + <nl> + return true ; <nl> + } <nl> # endif <nl> <nl> - / / vim : et ts = 4 sw = 4 cin cino = { 1s ff = unix <nl> + } / / namespace httplib <nl> + <nl> + # endif / / CPPHTTPLIB_HTTPLIB_H <nl> mmm a / src / core / crypto / key_manager . cpp <nl> ppp b / src / core / crypto / key_manager . cpp <nl> <nl> # include " common / common_paths . h " <nl> # include " common / file_util . h " <nl> # include " common / hex_util . h " <nl> - # include " common / string_util . h " <nl> # include " common / logging / log . h " <nl> + # include " common / string_util . h " <nl> # include " core / core . h " <nl> # include " core / crypto / aes_util . h " <nl> # include " core / crypto / key_manager . h " <nl>
externals : Update httplib
yuzu-emu/yuzu
47a6bb2d5ba9c8488ef1588c99fbebd8d9417374
2019-11-12T13:31:27Z
mmm a / Telegram / SourceFiles / pspecific_linux . cpp <nl> ppp b / Telegram / SourceFiles / pspecific_linux . cpp <nl> QString psCurrentExeDirectory ( int argc , char * argv [ ] ) { <nl> QString first = argc ? QString : : fromLocal8Bit ( argv [ 0 ] ) : QString ( ) ; <nl> if ( ! first . isEmpty ( ) ) { <nl> QFileInfo info ( first ) ; <nl> + if ( info . isSymLink ( ) ) { <nl> + info = info . symLinkTarget ( ) ; <nl> + } <nl> if ( info . exists ( ) ) { <nl> return QDir ( info . absolutePath ( ) ) . absolutePath ( ) + ' / ' ; <nl> } <nl> QString psCurrentExeName ( int argc , char * argv [ ] ) { <nl> QString first = argc ? QString : : fromLocal8Bit ( argv [ 0 ] ) : QString ( ) ; <nl> if ( ! first . isEmpty ( ) ) { <nl> QFileInfo info ( first ) ; <nl> - if ( info . exists ( ) ) { <nl> + if ( info . isSymLink ( ) ) { <nl> + info = info . symLinkTarget ( ) ; <nl> + } <nl> + if ( info . exists ( ) ) { <nl> return info . fileName ( ) ; <nl> } <nl> } <nl> mmm a / Telegram / SourceFiles / settings . cpp <nl> ppp b / Telegram / SourceFiles / settings . cpp <nl> void settingsParseArgs ( int argc , char * argv [ ] ) { <nl> memset_rand ( & gInstance , sizeof ( gInstance ) ) ; <nl> gExeDir = psCurrentExeDirectory ( argc , argv ) ; <nl> gExeName = psCurrentExeName ( argc , argv ) ; <nl> - for ( int32 i = 0 ; i < argc ; + + i ) { <nl> + for ( int32 i = 0 ; i < argc ; + + i ) { <nl> if ( string ( " - release " ) = = argv [ i ] ) { <nl> gTestMode = false ; <nl> } else if ( string ( " - debug " ) = = argv [ i ] ) { <nl> mmm a / Telegram / SourceFiles / title . cpp <nl> ppp b / Telegram / SourceFiles / title . cpp <nl> TitleWidget : : TitleWidget ( Window * window ) <nl> { <nl> setGeometry ( 0 , 0 , wnd - > width ( ) , st : : titleHeight ) ; <nl> _update . hide ( ) ; <nl> + _cancel . hide ( ) ; <nl> + _back . hide ( ) ; <nl> if ( App : : app ( ) - > updatingState ( ) = = Application : : UpdatingReady ) { <nl> showUpdateBtn ( ) ; <nl> } <nl>
fixed title for first run , fixed linux exec - by - link
telegramdesktop/tdesktop
96e72af5093e3c89a634af36bcf2a60aca5141ba
2014-12-16T17:05:18Z
mmm a / folly / io / TypedIOBuf . h <nl> ppp b / folly / io / TypedIOBuf . h <nl> class TypedIOBuf { <nl> return data ( ) [ idx ] ; <nl> } <nl> <nl> + T & operator [ ] ( ssize_t idx ) { <nl> + assert ( idx > = 0 & & idx < length ( ) ) ; <nl> + return writableData ( ) [ idx ] ; <nl> + } <nl> + <nl> / * * <nl> * Append one element . <nl> * / <nl>
Add non - const operator [ ] to TypedIOBuf
facebook/folly
0c8631dcba8f9ca23615166c36e9c9c267bf1e5a
2014-04-18T19:04:15Z
mmm a / doc / classes / CollisionPolygon . xml <nl> ppp b / doc / classes / CollisionPolygon . xml <nl> <nl> < ? xml version = " 1 . 0 " encoding = " UTF - 8 " ? > <nl> < class name = " CollisionPolygon " inherits = " Spatial " category = " Core " version = " 3 . 0 . alpha . custom_build " > <nl> < brief_description > <nl> + Editor - only class for defining a collision polygon in 3D space . <nl> < / brief_description > <nl> < description > <nl> + Allows editing a collision polygon ' s vertices on a selected plane . Can also set a depth perpendicular to that plane . This class is only available in the editor . It will not appear in the scene tree at runtime . Creates a [ Shape ] for gameplay . Properties modified during gameplay will have no effect . <nl> < / description > <nl> < tutorials > <nl> < / tutorials > <nl> <nl> < / methods > <nl> < members > <nl> < member name = " depth " type = " float " setter = " set_depth " getter = " get_depth " > <nl> + Length that the resulting collision extends in either direction perpendicular to its polygon . <nl> < / member > <nl> < member name = " disabled " type = " bool " setter = " set_disabled " getter = " is_disabled " > <nl> + If true , no collision will be produced . <nl> < / member > <nl> < member name = " polygon " type = " PoolVector2Array " setter = " set_polygon " getter = " get_polygon " > <nl> + Array of vertices which define the polygon . <nl> < / member > <nl> < / members > <nl> < constants > <nl> mmm a / doc / classes / CollisionPolygon2D . xml <nl> ppp b / doc / classes / CollisionPolygon2D . xml <nl> <nl> < ? xml version = " 1 . 0 " encoding = " UTF - 8 " ? > <nl> < class name = " CollisionPolygon2D " inherits = " Node2D " category = " Core " version = " 3 . 0 . alpha . custom_build " > <nl> < brief_description > <nl> - Editor - only class for easy editing of collision polygons . <nl> + Editor - only class for defining a collision polygon in 2D space . <nl> < / brief_description > <nl> < description > <nl> - Editor - only class . This is not present when running the game . It ' s used in the editor to properly edit and position collision shapes in [ CollisionObject2D ] . This is not accessible from regular code . This class is for editing custom shape polygons . <nl> + Allows editing a collision polygon ' s vertices . This class is only available in the editor . It will not appear in the scene tree at runtime . Creates a [ Shape2D ] for gameplay . Properties modified during gameplay will have no effect . <nl> < / description > <nl> < tutorials > <nl> < / tutorials > <nl> <nl> < / methods > <nl> < members > <nl> < member name = " build_mode " type = " int " setter = " set_build_mode " getter = " get_build_mode " enum = " CollisionPolygon2D . BuildMode " > <nl> + If BUILD_SOLIDS , the polygon and the area within it will have collision . If BUILD_SEGMENTS , only the edges of the polygon will have collision . <nl> < / member > <nl> < member name = " disabled " type = " bool " setter = " set_disabled " getter = " is_disabled " > <nl> + If true , no collision will be produced . <nl> < / member > <nl> < member name = " one_way_collision " type = " bool " setter = " set_one_way_collision " getter = " is_one_way_collision_enabled " > <nl> + If true , only edges that face up , relative to CollisionPolygon2D ' s rotation , will collide with other objects . <nl> < / member > <nl> < member name = " polygon " type = " PoolVector2Array " setter = " set_polygon " getter = " get_polygon " > <nl> + Array of vertices which define the polygon . <nl> < / member > <nl> < / members > <nl> < constants > <nl>
Modified the descriptions for CollisionPolygon2D and created descriptions for CollisionPolygon
godotengine/godot
60a929d18e942a08457d29c7f958fbf2acffb02d
2017-09-17T01:42:47Z
new file mode 100644 <nl> index 0000000000 . . af275d37d2 <nl> mmm / dev / null <nl> ppp b / tools / db_crashtest . py <nl> <nl> + import os <nl> + import sys <nl> + import time <nl> + import shlex <nl> + import getopt <nl> + import logging <nl> + import subprocess <nl> + <nl> + # This python script runs and kills db_stress multiple times with <nl> + # test - batches - snapshot ON , <nl> + # total operations much less than the total keys , and <nl> + # a high read percentage . <nl> + # This checks consistency in case of unsafe crashes in Rocksdb <nl> + <nl> + def main ( argv ) : <nl> + os . system ( " make - C ~ / rocksdb db_stress " ) <nl> + try : <nl> + opts , args = getopt . getopt ( argv , " hd : t : i : o : b : " ) <nl> + except getopt . GetoptError : <nl> + print " db_crashtest . py - d < duration_test > - t < # threads > " \ <nl> + " - i < interval for one run > - o < ops_per_thread > \ n " <nl> + sys . exit ( 2 ) <nl> + <nl> + # default values , will be overridden by cmdline args <nl> + interval = 120 # time for one db_stress instance to run <nl> + duration = 6000 # total time for this script to test db_stress <nl> + threads = 32 <nl> + ops_per_thread = 500000 <nl> + write_buf_size = 4 * 1024 * 1024 <nl> + <nl> + for opt , arg in opts : <nl> + if opt = = ' - h ' : <nl> + print " db_crashtest . py - d < duration_test > - t < # threads > " \ <nl> + " - i < interval for one run > - o < ops_per_thread > " \ <nl> + " - b < write_buffer_size > \ n " <nl> + sys . exit ( ) <nl> + elif opt = = ( " - d " ) : <nl> + duration = int ( arg ) <nl> + elif opt = = ( " - t " ) : <nl> + threads = int ( arg ) <nl> + elif opt = = ( " - i " ) : <nl> + interval = int ( arg ) <nl> + elif opt = = ( " - o " ) : <nl> + ops_per_thread = int ( arg ) <nl> + elif opt = = ( " - b " ) : <nl> + write_buf_size = int ( arg ) <nl> + else : <nl> + print " db_crashtest . py - d < duration_test > - t < # threads > " \ <nl> + " - i < interval for one run > - o < ops_per_thread > " \ <nl> + " - b < write_buffer_size > \ n " <nl> + sys . exit ( 2 ) <nl> + <nl> + exit_time = time . time ( ) + duration <nl> + <nl> + while time . time ( ) < exit_time : <nl> + run_had_errors = False <nl> + print " Running db_stress \ n " <nl> + os . system ( " mkdir - p / tmp / rocksdb / crashtest " ) <nl> + killtime = time . time ( ) + interval <nl> + child = subprocess . Popen ( [ ' ~ / rocksdb / db_stress \ <nl> + - - test_batches_snapshots = 1 \ <nl> + - - ops_per_thread = 0 ' + str ( ops_per_thread ) + ' \ <nl> + - - threads = 0 ' + str ( threads ) + ' \ <nl> + - - write_buffer_size = ' + str ( write_buf_size ) + ' \ <nl> + - - reopen = 10 \ <nl> + - - readpercent = 50 \ <nl> + - - db = / tmp / rocksdb / crashtest \ <nl> + - - max_key = 100 ' ] , stderr = subprocess . PIPE , shell = True ) <nl> + time . sleep ( interval ) <nl> + while True : <nl> + if time . time ( ) > killtime : <nl> + if child . poll ( ) is not None : <nl> + logging . warn ( " WARNING : db_stress completed before kill \ n " ) <nl> + else : <nl> + child . kill ( ) <nl> + print " KILLED \ n " <nl> + time . sleep ( 1 ) # time to stabilize after a kill <nl> + <nl> + while True : <nl> + line = child . stderr . readline ( ) . strip ( ) <nl> + if line ! = ' ' : <nl> + run_had_errors = True <nl> + print ' * * * ' + line + ' ^ ' <nl> + else : <nl> + break <nl> + if run_had_errors : <nl> + sys . exit ( 2 ) <nl> + break <nl> + <nl> + time . sleep ( 1 ) # time to stabilize before the next run <nl> + <nl> + if __name__ = = " __main__ " : <nl> + sys . exit ( main ( sys . argv [ 1 : ] ) ) <nl> mmm a / tools / db_stress . cc <nl> ppp b / tools / db_stress . cc <nl> class Stats { <nl> double micros = now - last_op_finish_ ; <nl> hist_ . Add ( micros ) ; <nl> if ( micros > 20000 ) { <nl> - fprintf ( stderr , " long op : % . 1f micros % 30s \ r " , micros , " " ) ; <nl> - fflush ( stderr ) ; <nl> + fprintf ( stdout , " long op : % . 1f micros % 30s \ r " , micros , " " ) ; <nl> } <nl> last_op_finish_ = now ; <nl> } <nl> class Stats { <nl> else if ( next_report_ < 100000 ) next_report_ + = 10000 ; <nl> else if ( next_report_ < 500000 ) next_report_ + = 50000 ; <nl> else next_report_ + = 100000 ; <nl> - fprintf ( stderr , " . . . finished % ld ops % 30s \ r " , done_ , " " ) ; <nl> - fflush ( stderr ) ; <nl> + fprintf ( stdout , " . . . finished % ld ops % 30s \ r " , done_ , " " ) ; <nl> } <nl> } <nl> <nl> class StressTest { <nl> fprintf ( stdout , " Number of threads : % d \ n " , FLAGS_threads ) ; <nl> fprintf ( stdout , " Ops per thread : % d \ n " , FLAGS_ops_per_thread ) ; <nl> fprintf ( stdout , " Read percentage : % d \ n " , FLAGS_readpercent ) ; <nl> + fprintf ( stdout , " Write - buffer - size : % d \ n " , FLAGS_write_buffer_size ) ; <nl> fprintf ( stdout , " Delete percentage : % d \ n " , FLAGS_delpercent ) ; <nl> fprintf ( stdout , " Max key : % ld \ n " , FLAGS_max_key ) ; <nl> fprintf ( stdout , " Ratio # ops / # keys : % ld \ n " , <nl>
Python script to periodically run and kill the db_stress test
facebook/rocksdb
e937d471801b3a9237a0b19cb3f4af43c20ed9a9
2013-04-01T19:18:46Z
mmm a / grpc . def <nl> ppp b / grpc . def <nl> EXPORTS <nl> grpc_local_server_credentials_create <nl> grpc_tls_credentials_options_create <nl> grpc_tls_credentials_options_set_cert_request_type <nl> + grpc_tls_credentials_options_set_server_verification_option <nl> grpc_tls_credentials_options_set_key_materials_config <nl> grpc_tls_credentials_options_set_credential_reload_config <nl> grpc_tls_credentials_options_set_server_authorization_check_config <nl> mmm a / include / grpc / grpc_security . h <nl> ppp b / include / grpc / grpc_security . h <nl> GRPCAPI int grpc_tls_credentials_options_set_cert_request_type ( <nl> grpc_tls_credentials_options * options , <nl> grpc_ssl_client_certificate_request_type type ) ; <nl> <nl> + / * * Set grpc_tls_server_verification_option field in credentials options <nl> + with the provided server_verification_option . options should not be NULL . <nl> + This should be called only on the client side . <nl> + If grpc_tls_server_verification_option is not <nl> + GRPC_TLS_SERVER_VERIFICATION , use of a customer server <nl> + authorization check ( grpc_tls_server_authorization_check_config ) <nl> + will be mandatory . <nl> + It returns 1 on success and 0 on failure . It is used for <nl> + experimental purpose for now and subject to change . * / <nl> + GRPCAPI int grpc_tls_credentials_options_set_server_verification_option ( <nl> + grpc_tls_credentials_options * options , <nl> + grpc_tls_server_verification_option server_verification_option ) ; <nl> + <nl> / * * Set grpc_tls_key_materials_config field in credentials options <nl> with the provided config struct whose ownership is transferred . <nl> Both parameters should not be NULL . <nl> struct grpc_tls_server_authorization_check_arg { <nl> int success ; <nl> const char * target_name ; <nl> const char * peer_cert ; <nl> + const char * peer_cert_full_chain ; <nl> grpc_status_code status ; <nl> const char * error_details ; <nl> grpc_tls_server_authorization_check_config * config ; <nl> mmm a / include / grpc / grpc_security_constants . h <nl> ppp b / include / grpc / grpc_security_constants . h <nl> extern " C " { <nl> # define GRPC_X509_CN_PROPERTY_NAME " x509_common_name " <nl> # define GRPC_X509_SAN_PROPERTY_NAME " x509_subject_alternative_name " <nl> # define GRPC_X509_PEM_CERT_PROPERTY_NAME " x509_pem_cert " <nl> + # define GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME " x509_pem_cert_chain " <nl> # define GRPC_SSL_SESSION_REUSED_PROPERTY " ssl_session_reused " <nl> <nl> / * * Environment variable that points to the default SSL roots file . This file <nl> typedef enum { <nl> GRPC_SECURITY_MAX = GRPC_PRIVACY_AND_INTEGRITY , <nl> } grpc_security_level ; <nl> <nl> + typedef enum { <nl> + / * * Default option : performs server certificate verification and hostname <nl> + verification * / <nl> + GRPC_TLS_SERVER_VERIFICATION , <nl> + / * * Performs server certificate verification , but skips hostname verification <nl> + * / <nl> + GRPC_TLS_SKIP_HOSTNAME_VERIFICATION , <nl> + / * * Skips both server certificate and hostname verification * / <nl> + GRPC_TLS_SKIP_ALL_SERVER_VERIFICATION <nl> + } grpc_tls_server_verification_option ; <nl> + <nl> / * * <nl> * Type of local connections for which local channel / server credentials will be <nl> * applied . It supports UDS and local TCP connections . <nl> mmm a / include / grpcpp / security / tls_credentials_options . h <nl> ppp b / include / grpcpp / security / tls_credentials_options . h <nl> class TlsServerAuthorizationCheckArg { <nl> int success ( ) const ; <nl> grpc : : string target_name ( ) const ; <nl> grpc : : string peer_cert ( ) const ; <nl> + grpc : : string peer_cert_full_chain ( ) const ; <nl> grpc_status_code status ( ) const ; <nl> grpc : : string error_details ( ) const ; <nl> <nl> class TlsServerAuthorizationCheckArg { <nl> void set_success ( int success ) ; <nl> void set_target_name ( const grpc : : string & target_name ) ; <nl> void set_peer_cert ( const grpc : : string & peer_cert ) ; <nl> + void set_peer_cert_full_chain ( const grpc : : string & peer_cert_full_chain ) ; <nl> void set_status ( grpc_status_code status ) ; <nl> void set_error_details ( const grpc : : string & error_details ) ; <nl> <nl> class TlsCredentialsOptions { <nl> public : <nl> TlsCredentialsOptions ( <nl> grpc_ssl_client_certificate_request_type cert_request_type , <nl> + grpc_tls_server_verification_option server_verification_option , <nl> std : : shared_ptr < TlsKeyMaterialsConfig > key_materials_config , <nl> std : : shared_ptr < TlsCredentialReloadConfig > credential_reload_config , <nl> std : : shared_ptr < TlsServerAuthorizationCheckConfig > <nl> class TlsCredentialsOptions { <nl> grpc_ssl_client_certificate_request_type cert_request_type ( ) const { <nl> return cert_request_type_ ; <nl> } <nl> + grpc_tls_server_verification_option server_verification_option ( ) const { <nl> + return server_verification_option_ ; <nl> + } <nl> std : : shared_ptr < TlsKeyMaterialsConfig > key_materials_config ( ) const { <nl> return key_materials_config_ ; <nl> } <nl> class TlsCredentialsOptions { <nl> * goes unused when creating channel credentials , and the user can set it to <nl> * GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE . * * / <nl> grpc_ssl_client_certificate_request_type cert_request_type_ ; <nl> + / * * The server_verification_option_ flag is only relevant when the <nl> + * TlsCredentialsOptions are used to instantiate client credentials ; * * / <nl> + grpc_tls_server_verification_option server_verification_option_ ; <nl> std : : shared_ptr < TlsKeyMaterialsConfig > key_materials_config_ ; <nl> std : : shared_ptr < TlsCredentialReloadConfig > credential_reload_config_ ; <nl> std : : shared_ptr < TlsServerAuthorizationCheckConfig > <nl> mmm a / src / core / lib / security / credentials / tls / grpc_tls_credentials_options . cc <nl> ppp b / src / core / lib / security / credentials / tls / grpc_tls_credentials_options . cc <nl> int grpc_tls_credentials_options_set_cert_request_type ( <nl> return 1 ; <nl> } <nl> <nl> + int grpc_tls_credentials_options_set_server_verification_option ( <nl> + grpc_tls_credentials_options * options , <nl> + grpc_tls_server_verification_option server_verification_option ) { <nl> + if ( options = = nullptr ) { <nl> + gpr_log ( GPR_ERROR , <nl> + " Invalid nullptr arguments to " <nl> + " grpc_tls_credentials_options_set_server_verification_option ( ) " ) ; <nl> + return 0 ; <nl> + } <nl> + if ( server_verification_option ! = GRPC_TLS_SERVER_VERIFICATION & & <nl> + options - > server_authorization_check_config ( ) = = nullptr ) { <nl> + gpr_log ( GPR_ERROR , <nl> + " server_authorization_check_config needs to be specified when " <nl> + " server_verification_option is not GRPC_TLS_SERVER_VERIFICATION " ) ; <nl> + return 0 ; <nl> + } <nl> + options - > set_server_verification_option ( server_verification_option ) ; <nl> + return 1 ; <nl> + } <nl> + <nl> int grpc_tls_credentials_options_set_key_materials_config ( <nl> grpc_tls_credentials_options * options , <nl> grpc_tls_key_materials_config * config ) { <nl> mmm a / src / core / lib / security / credentials / tls / grpc_tls_credentials_options . h <nl> ppp b / src / core / lib / security / credentials / tls / grpc_tls_credentials_options . h <nl> struct grpc_tls_credentials_options <nl> grpc_ssl_client_certificate_request_type cert_request_type ( ) const { <nl> return cert_request_type_ ; <nl> } <nl> + grpc_tls_server_verification_option server_verification_option ( ) const { <nl> + return server_verification_option_ ; <nl> + } <nl> grpc_tls_key_materials_config * key_materials_config ( ) const { <nl> return key_materials_config_ . get ( ) ; <nl> } <nl> struct grpc_tls_credentials_options <nl> const grpc_ssl_client_certificate_request_type type ) { <nl> cert_request_type_ = type ; <nl> } <nl> + void set_server_verification_option ( <nl> + const grpc_tls_server_verification_option server_verification_option ) { <nl> + server_verification_option_ = server_verification_option ; <nl> + } <nl> void set_key_materials_config ( <nl> grpc_core : : RefCountedPtr < grpc_tls_key_materials_config > config ) { <nl> key_materials_config_ = std : : move ( config ) ; <nl> struct grpc_tls_credentials_options <nl> <nl> private : <nl> grpc_ssl_client_certificate_request_type cert_request_type_ ; <nl> + grpc_tls_server_verification_option server_verification_option_ ; <nl> grpc_core : : RefCountedPtr < grpc_tls_key_materials_config > key_materials_config_ ; <nl> grpc_core : : RefCountedPtr < grpc_tls_credential_reload_config > <nl> credential_reload_config_ ; <nl> mmm a / src / core / lib / security / security_connector / ssl_utils . cc <nl> ppp b / src / core / lib / security / security_connector / ssl_utils . cc <nl> grpc_get_tsi_client_certificate_request_type ( <nl> } <nl> } <nl> <nl> + tsi_server_verification_option grpc_get_tsi_server_verification_option ( <nl> + grpc_tls_server_verification_option server_verification_option ) { <nl> + switch ( server_verification_option ) { <nl> + case GRPC_TLS_SERVER_VERIFICATION : <nl> + return TSI_SERVER_VERIFICATION ; <nl> + case GRPC_TLS_SKIP_HOSTNAME_VERIFICATION : <nl> + return TSI_SKIP_HOSTNAME_VERIFICATION ; <nl> + case GRPC_TLS_SKIP_ALL_SERVER_VERIFICATION : <nl> + return TSI_SKIP_ALL_SERVER_VERIFICATION ; <nl> + default : <nl> + return TSI_SERVER_VERIFICATION ; <nl> + } <nl> + } <nl> + <nl> grpc_error * grpc_ssl_check_alpn ( const tsi_peer * peer ) { <nl> # if TSI_OPENSSL_ALPN_SUPPORT <nl> / * Check the ALPN if ALPN is supported . * / <nl> grpc_core : : RefCountedPtr < grpc_auth_context > grpc_ssl_peer_to_auth_context ( <nl> grpc_auth_context_add_property ( ctx . get ( ) , <nl> GRPC_X509_PEM_CERT_PROPERTY_NAME , <nl> prop - > value . data , prop - > value . length ) ; <nl> + } else if ( strcmp ( prop - > name , TSI_X509_PEM_CERT_CHAIN_PROPERTY ) = = 0 ) { <nl> + grpc_auth_context_add_property ( ctx . get ( ) , <nl> + GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME , <nl> + prop - > value . data , prop - > value . length ) ; <nl> } else if ( strcmp ( prop - > name , TSI_SSL_SESSION_REUSED_PEER_PROPERTY ) = = 0 ) { <nl> grpc_auth_context_add_property ( ctx . get ( ) , <nl> GRPC_SSL_SESSION_REUSED_PROPERTY , <nl> tsi_peer grpc_shallow_peer_from_ssl_auth_context ( <nl> } else if ( strcmp ( prop - > name , GRPC_X509_PEM_CERT_PROPERTY_NAME ) = = 0 ) { <nl> add_shallow_auth_property_to_peer ( & peer , prop , <nl> TSI_X509_PEM_CERT_PROPERTY ) ; <nl> + } else if ( strcmp ( prop - > name , GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME ) = = <nl> + 0 ) { <nl> + add_shallow_auth_property_to_peer ( & peer , prop , <nl> + TSI_X509_PEM_CERT_CHAIN_PROPERTY ) ; <nl> } <nl> } <nl> } <nl> void grpc_shallow_peer_destruct ( tsi_peer * peer ) { <nl> <nl> grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init ( <nl> tsi_ssl_pem_key_cert_pair * pem_key_cert_pair , const char * pem_root_certs , <nl> + tsi_server_verification_option server_verification_option , <nl> tsi_ssl_session_cache * ssl_session_cache , <nl> tsi_ssl_client_handshaker_factory * * handshaker_factory ) { <nl> const char * root_certs ; <nl> grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init ( <nl> } <nl> options . cipher_suites = grpc_get_ssl_cipher_suites ( ) ; <nl> options . session_cache = ssl_session_cache ; <nl> + options . server_verification_option = server_verification_option ; <nl> const tsi_result result = <nl> tsi_create_ssl_client_handshaker_factory_with_options ( & options , <nl> handshaker_factory ) ; <nl> mmm a / src / core / lib / security / security_connector / ssl_utils . h <nl> ppp b / src / core / lib / security / security_connector / ssl_utils . h <nl> tsi_client_certificate_request_type <nl> grpc_get_tsi_client_certificate_request_type ( <nl> grpc_ssl_client_certificate_request_type grpc_request_type ) ; <nl> <nl> + / * Map from grpc_tls_server_verification_option to <nl> + * tsi_server_verification_option . * / <nl> + tsi_server_verification_option grpc_get_tsi_server_verification_option ( <nl> + grpc_tls_server_verification_option server_verification_option ) ; <nl> + <nl> / * Return an array of strings containing alpn protocols . * / <nl> const char * * grpc_fill_alpn_protocol_strings ( size_t * num_alpn_protocols ) ; <nl> <nl> / * Initialize TSI SSL server / client handshaker factory . * / <nl> grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init ( <nl> tsi_ssl_pem_key_cert_pair * key_cert_pair , const char * pem_root_certs , <nl> + tsi_server_verification_option server_verification_option , <nl> tsi_ssl_session_cache * ssl_session_cache , <nl> tsi_ssl_client_handshaker_factory * * handshaker_factory ) ; <nl> <nl> mmm a / src / core / lib / security / security_connector / tls / tls_security_connector . cc <nl> ppp b / src / core / lib / security / security_connector / tls / tls_security_connector . cc <nl> tsi_ssl_pem_key_cert_pair * ConvertToTsiPemKeyCertPair ( <nl> grpc_status_code TlsFetchKeyMaterials ( <nl> const grpc_core : : RefCountedPtr < grpc_tls_key_materials_config > & <nl> key_materials_config , <nl> - const grpc_tls_credentials_options & options , <nl> + const grpc_tls_credentials_options & options , bool server_config , <nl> grpc_ssl_certificate_config_reload_status * reload_status ) { <nl> GPR_ASSERT ( key_materials_config ! = nullptr ) ; <nl> bool is_key_materials_empty = <nl> key_materials_config - > pem_key_cert_pair_list ( ) . empty ( ) ; <nl> - if ( options . credential_reload_config ( ) = = nullptr & & is_key_materials_empty ) { <nl> + if ( options . credential_reload_config ( ) = = nullptr & & is_key_materials_empty & & <nl> + server_config ) { <nl> gpr_log ( GPR_ERROR , <nl> " Either credential reload config or key materials should be " <nl> " provisioned . " ) ; <nl> void TlsChannelSecurityConnector : : check_peer ( <nl> error = GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> " Cannot check peer : missing pem cert property . " ) ; <nl> } else { <nl> - char * peer_pem = static_cast < char * > ( gpr_malloc ( p - > value . length + 1 ) ) ; <nl> + char * peer_pem = static_cast < char * > ( gpr_zalloc ( p - > value . length + 1 ) ) ; <nl> memcpy ( peer_pem , p - > value . data , p - > value . length ) ; <nl> - peer_pem [ p - > value . length ] = ' \ 0 ' ; <nl> GPR_ASSERT ( check_arg_ ! = nullptr ) ; <nl> check_arg_ - > peer_cert = check_arg_ - > peer_cert = = nullptr <nl> ? gpr_strdup ( peer_pem ) <nl> void TlsChannelSecurityConnector : : check_peer ( <nl> : check_arg_ - > target_name ; <nl> on_peer_checked_ = on_peer_checked ; <nl> gpr_free ( peer_pem ) ; <nl> + const tsi_peer_property * chain = tsi_peer_get_property_by_name ( <nl> + & peer , TSI_X509_PEM_CERT_CHAIN_PROPERTY ) ; <nl> + if ( chain ! = nullptr ) { <nl> + char * peer_pem_chain = <nl> + static_cast < char * > ( gpr_zalloc ( chain - > value . length + 1 ) ) ; <nl> + memcpy ( peer_pem_chain , chain - > value . data , chain - > value . length ) ; <nl> + check_arg_ - > peer_cert_full_chain = <nl> + check_arg_ - > peer_cert_full_chain = = nullptr <nl> + ? gpr_strdup ( peer_pem_chain ) <nl> + : check_arg_ - > peer_cert_full_chain ; <nl> + gpr_free ( peer_pem_chain ) ; <nl> + } <nl> int callback_status = config - > Schedule ( check_arg_ ) ; <nl> / * Server authorization check is handled asynchronously . * / <nl> if ( callback_status ) { <nl> TlsChannelSecurityConnector : : CreateTlsChannelSecurityConnector ( <nl> <nl> grpc_security_status TlsChannelSecurityConnector : : ReplaceHandshakerFactory ( <nl> tsi_ssl_session_cache * ssl_session_cache ) { <nl> + const TlsCredentials * creds = <nl> + static_cast < const TlsCredentials * > ( channel_creds ( ) ) ; <nl> + tsi_server_verification_option server_verification_option = <nl> + grpc_get_tsi_server_verification_option ( <nl> + creds - > options ( ) . server_verification_option ( ) ) ; <nl> / * Free the client handshaker factory if exists . * / <nl> if ( client_handshaker_factory_ ) { <nl> tsi_ssl_client_handshaker_factory_unref ( client_handshaker_factory_ ) ; <nl> } <nl> - GPR_ASSERT ( ! key_materials_config_ - > pem_key_cert_pair_list ( ) . empty ( ) ) ; <nl> tsi_ssl_pem_key_cert_pair * pem_key_cert_pair = ConvertToTsiPemKeyCertPair ( <nl> key_materials_config_ - > pem_key_cert_pair_list ( ) ) ; <nl> grpc_security_status status = grpc_ssl_tsi_client_handshaker_factory_init ( <nl> pem_key_cert_pair , key_materials_config_ - > pem_root_certs ( ) , <nl> - ssl_session_cache , & client_handshaker_factory_ ) ; <nl> + server_verification_option , ssl_session_cache , <nl> + & client_handshaker_factory_ ) ; <nl> / * Free memory . * / <nl> grpc_tsi_ssl_pem_key_cert_pairs_destroy ( pem_key_cert_pair , 1 ) ; <nl> return status ; <nl> grpc_security_status TlsChannelSecurityConnector : : InitializeHandshakerFactory ( <nl> } <nl> grpc_ssl_certificate_config_reload_status reload_status = <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> - if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , <nl> + if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , false , <nl> & reload_status ) ! = GRPC_STATUS_OK ) { <nl> / * Raise an error if key materials are not populated . * / <nl> return GRPC_SECURITY_ERROR ; <nl> grpc_security_status TlsChannelSecurityConnector : : RefreshHandshakerFactory ( ) { <nl> static_cast < const TlsCredentials * > ( channel_creds ( ) ) ; <nl> grpc_ssl_certificate_config_reload_status reload_status = <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> - if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , <nl> + if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , false , <nl> & reload_status ) ! = GRPC_STATUS_OK ) { <nl> return GRPC_SECURITY_ERROR ; <nl> } <nl> grpc_security_status TlsServerSecurityConnector : : InitializeHandshakerFactory ( ) { <nl> } <nl> grpc_ssl_certificate_config_reload_status reload_status = <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> - if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , <nl> + if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , true , <nl> & reload_status ) ! = GRPC_STATUS_OK ) { <nl> / * Raise an error if key materials are not populated . * / <nl> return GRPC_SECURITY_ERROR ; <nl> grpc_security_status TlsServerSecurityConnector : : RefreshHandshakerFactory ( ) { <nl> static_cast < const TlsServerCredentials * > ( server_creds ( ) ) ; <nl> grpc_ssl_certificate_config_reload_status reload_status = <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> - if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , <nl> + if ( TlsFetchKeyMaterials ( key_materials_config_ , creds - > options ( ) , true , <nl> & reload_status ) ! = GRPC_STATUS_OK ) { <nl> return GRPC_SECURITY_ERROR ; <nl> } <nl> mmm a / src / core / lib / security / security_connector / tls / tls_security_connector . h <nl> ppp b / src / core / lib / security / security_connector / tls / tls_security_connector . h <nl> class TlsServerSecurityConnector final : public grpc_server_security_connector { <nl> grpc_status_code TlsFetchKeyMaterials ( <nl> const grpc_core : : RefCountedPtr < grpc_tls_key_materials_config > & <nl> key_materials_config , <nl> - const grpc_tls_credentials_options & options , <nl> + const grpc_tls_credentials_options & options , bool server_config , <nl> grpc_ssl_certificate_config_reload_status * status ) ; <nl> <nl> } / / namespace grpc_core <nl> mmm a / src / core / tsi / ssl_transport_security . cc <nl> ppp b / src / core / tsi / ssl_transport_security . cc <nl> <nl> # include < sys / socket . h > <nl> # endif <nl> <nl> + # include < grpc / grpc_security . h > <nl> # include < grpc / support / alloc . h > <nl> # include < grpc / support / log . h > <nl> # include < grpc / support / string_util . h > <nl> static void tsi_ssl_handshaker_factory_init ( <nl> gpr_ref_init ( & factory - > refcount , 1 ) ; <nl> } <nl> <nl> + / * Gets the X509 cert chain in PEM format as a tsi_peer_property . * / <nl> + tsi_result tsi_ssl_get_cert_chain_contents ( STACK_OF ( X509 ) * peer_chain , <nl> + tsi_peer_property * property ) { <nl> + BIO * bio = BIO_new ( BIO_s_mem ( ) ) ; <nl> + for ( int i = 0 ; i < sk_X509_num ( peer_chain ) ; i + + ) { <nl> + if ( ! PEM_write_bio_X509 ( bio , sk_X509_value ( peer_chain , i ) ) ) { <nl> + BIO_free ( bio ) ; <nl> + return TSI_INTERNAL_ERROR ; <nl> + } <nl> + } <nl> + char * contents ; <nl> + long len = BIO_get_mem_data ( bio , & contents ) ; <nl> + if ( len < = 0 ) { <nl> + BIO_free ( bio ) ; <nl> + return TSI_INTERNAL_ERROR ; <nl> + } <nl> + tsi_result result = tsi_construct_string_peer_property ( <nl> + TSI_X509_PEM_CERT_CHAIN_PROPERTY , ( const char * ) contents , <nl> + static_cast < size_t > ( len ) , property ) ; <nl> + BIO_free ( bio ) ; <nl> + return result ; <nl> + } <nl> + <nl> / * mmm tsi_handshaker_result methods implementation . mmm * / <nl> static tsi_result ssl_handshaker_result_extract_peer ( <nl> const tsi_handshaker_result * self , tsi_peer * peer ) { <nl> static tsi_result ssl_handshaker_result_extract_peer ( <nl> unsigned int alpn_selected_len ; <nl> const tsi_ssl_handshaker_result * impl = <nl> reinterpret_cast < const tsi_ssl_handshaker_result * > ( self ) ; <nl> - / / TODO ( yihuazhang ) : Return a full certificate chain as a peer property . <nl> X509 * peer_cert = SSL_get_peer_certificate ( impl - > ssl ) ; <nl> if ( peer_cert ! = nullptr ) { <nl> result = peer_from_x509 ( peer_cert , 1 , peer ) ; <nl> static tsi_result ssl_handshaker_result_extract_peer ( <nl> SSL_get0_next_proto_negotiated ( impl - > ssl , & alpn_selected , <nl> & alpn_selected_len ) ; <nl> } <nl> - <nl> + / / When called on the client side , the stack also contains the <nl> + / / peer ' s certificate ; When called on the server side , <nl> + / / the peer ' s certificate is not present in the stack <nl> + STACK_OF ( X509 ) * peer_chain = SSL_get_peer_cert_chain ( impl - > ssl ) ; <nl> / / 1 is for session reused property . <nl> size_t new_property_count = peer - > property_count + 1 ; <nl> if ( alpn_selected ! = nullptr ) new_property_count + + ; <nl> + if ( peer_chain ! = nullptr ) new_property_count + + ; <nl> tsi_peer_property * new_properties = static_cast < tsi_peer_property * > ( <nl> gpr_zalloc ( sizeof ( * new_properties ) * new_property_count ) ) ; <nl> for ( size_t i = 0 ; i < peer - > property_count ; i + + ) { <nl> static tsi_result ssl_handshaker_result_extract_peer ( <nl> } <nl> if ( peer - > properties ! = nullptr ) gpr_free ( peer - > properties ) ; <nl> peer - > properties = new_properties ; <nl> - <nl> + / / Add peer chain if available <nl> + if ( peer_chain ! = nullptr ) { <nl> + result = tsi_ssl_get_cert_chain_contents ( <nl> + peer_chain , & peer - > properties [ peer - > property_count ] ) ; <nl> + if ( result = = TSI_OK ) peer - > property_count + + ; <nl> + } <nl> if ( alpn_selected ! = nullptr ) { <nl> result = tsi_construct_string_peer_property ( <nl> TSI_SSL_ALPN_SELECTED_PROTOCOL , <nl> tsi_result tsi_create_ssl_client_handshaker_factory_with_options ( <nl> tsi_ssl_handshaker_factory_unref ( & impl - > base ) ; <nl> return result ; <nl> } <nl> - SSL_CTX_set_verify ( ssl_context , SSL_VERIFY_PEER , nullptr ) ; <nl> + if ( options - > server_verification_option = = TSI_SKIP_ALL_SERVER_VERIFICATION ) { <nl> + SSL_CTX_set_verify ( ssl_context , SSL_VERIFY_PEER , NullVerifyCallback ) ; <nl> + } else { <nl> + SSL_CTX_set_verify ( ssl_context , SSL_VERIFY_PEER , nullptr ) ; <nl> + } <nl> / * TODO ( jboeuf ) : Add revocation verification . * / <nl> <nl> * factory = impl ; <nl> mmm a / src / core / tsi / ssl_transport_security . h <nl> ppp b / src / core / tsi / ssl_transport_security . h <nl> <nl> # define GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H <nl> <nl> # include < grpc / support / port_platform . h > <nl> + extern " C " { <nl> + # include < openssl / x509 . h > <nl> + } <nl> <nl> # include " src / core / lib / gprpp / string_view . h " <nl> # include " src / core / tsi / transport_security_interface . h " <nl> <nl> <nl> # define TSI_X509_PEM_CERT_PROPERTY " x509_pem_cert " <nl> <nl> + # define TSI_X509_PEM_CERT_CHAIN_PROPERTY " x509_pem_cert_chain " <nl> + <nl> # define TSI_SSL_ALPN_SELECTED_PROTOCOL " ssl_alpn_selected_protocol " <nl> <nl> / * mmm tsi_ssl_root_certs_store object mmm <nl> struct tsi_ssl_client_handshaker_options { <nl> / * ssl_session_cache is a cache for reusable client - side sessions . * / <nl> tsi_ssl_session_cache * session_cache ; <nl> <nl> + / * Server verification option * / <nl> + tsi_server_verification_option server_verification_option ; <nl> + <nl> tsi_ssl_client_handshaker_options ( ) <nl> : pem_key_cert_pair ( nullptr ) , <nl> pem_root_certs ( nullptr ) , <nl> struct tsi_ssl_client_handshaker_options { <nl> cipher_suites ( nullptr ) , <nl> alpn_protocols ( nullptr ) , <nl> num_alpn_protocols ( 0 ) , <nl> - session_cache ( nullptr ) { } <nl> + session_cache ( nullptr ) , <nl> + server_verification_option ( TSI_SERVER_VERIFICATION ) { } <nl> } ; <nl> <nl> / * Creates a client handshaker factory . <nl> const tsi_ssl_handshaker_factory_vtable * tsi_ssl_handshaker_factory_swap_vtable ( <nl> tsi_result tsi_ssl_extract_x509_subject_names_from_pem_cert ( <nl> const char * pem_cert , tsi_peer * peer ) ; <nl> <nl> + / * Exposed for testing only . * / <nl> + tsi_result tsi_ssl_get_cert_chain_contents ( STACK_OF ( X509 ) * peer_chain , <nl> + tsi_peer_property * property ) ; <nl> + <nl> # endif / * GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H * / <nl> mmm a / src / core / tsi / transport_security_interface . h <nl> ppp b / src / core / tsi / transport_security_interface . h <nl> typedef enum { <nl> TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY , <nl> } tsi_client_certificate_request_type ; <nl> <nl> + typedef enum { <nl> + / * * Default option : performs server certificate verification and hostname <nl> + verification * / <nl> + TSI_SERVER_VERIFICATION , <nl> + / * * Performs server certificate verification , but skips hostname verification <nl> + * / <nl> + TSI_SKIP_HOSTNAME_VERIFICATION , <nl> + / * * Skips both server certificate and hostname verification * / <nl> + TSI_SKIP_ALL_SERVER_VERIFICATION , <nl> + } tsi_server_verification_option ; <nl> + <nl> const char * tsi_result_to_string ( tsi_result result ) ; <nl> <nl> / * mmm tsi tracing mmm * / <nl> mmm a / src / cpp / common / tls_credentials_options . cc <nl> ppp b / src / cpp / common / tls_credentials_options . cc <nl> grpc : : string TlsServerAuthorizationCheckArg : : peer_cert ( ) const { <nl> return cpp_peer_cert ; <nl> } <nl> <nl> + grpc : : string TlsServerAuthorizationCheckArg : : peer_cert_full_chain ( ) const { <nl> + grpc : : string cpp_peer_cert_full_chain ( c_arg_ - > peer_cert_full_chain ) ; <nl> + return cpp_peer_cert_full_chain ; <nl> + } <nl> + <nl> grpc_status_code TlsServerAuthorizationCheckArg : : status ( ) const { <nl> return c_arg_ - > status ; <nl> } <nl> void TlsServerAuthorizationCheckArg : : set_peer_cert ( <nl> c_arg_ - > peer_cert = gpr_strdup ( peer_cert . c_str ( ) ) ; <nl> } <nl> <nl> + void TlsServerAuthorizationCheckArg : : set_peer_cert_full_chain ( <nl> + const grpc : : string & peer_cert_full_chain ) { <nl> + c_arg_ - > peer_cert_full_chain = gpr_strdup ( peer_cert_full_chain . c_str ( ) ) ; <nl> + } <nl> + <nl> void TlsServerAuthorizationCheckArg : : set_status ( grpc_status_code status ) { <nl> c_arg_ - > status = status ; <nl> } <nl> TlsServerAuthorizationCheckConfig : : ~ TlsServerAuthorizationCheckConfig ( ) { } <nl> / * * gRPC TLS credential options API implementation * * / <nl> TlsCredentialsOptions : : TlsCredentialsOptions ( <nl> grpc_ssl_client_certificate_request_type cert_request_type , <nl> + grpc_tls_server_verification_option server_verification_option , <nl> std : : shared_ptr < TlsKeyMaterialsConfig > key_materials_config , <nl> std : : shared_ptr < TlsCredentialReloadConfig > credential_reload_config , <nl> std : : shared_ptr < TlsServerAuthorizationCheckConfig > <nl> server_authorization_check_config ) <nl> : cert_request_type_ ( cert_request_type ) , <nl> + server_verification_option_ ( server_verification_option ) , <nl> key_materials_config_ ( std : : move ( key_materials_config ) ) , <nl> credential_reload_config_ ( std : : move ( credential_reload_config ) ) , <nl> server_authorization_check_config_ ( <nl> TlsCredentialsOptions : : TlsCredentialsOptions ( <nl> grpc_tls_credentials_options_set_server_authorization_check_config ( <nl> c_credentials_options_ , server_authorization_check_config_ - > c_config ( ) ) ; <nl> } <nl> + grpc_tls_credentials_options_set_server_verification_option ( <nl> + c_credentials_options_ , server_verification_option ) ; <nl> } <nl> <nl> TlsCredentialsOptions : : ~ TlsCredentialsOptions ( ) { } <nl> mmm a / test / core / security / security_connector_test . cc <nl> ppp b / test / core / security / security_connector_test . cc <nl> static int check_x509_pem_cert ( const grpc_auth_context * ctx , <nl> return 1 ; <nl> } <nl> <nl> + static int check_x509_pem_cert_chain ( const grpc_auth_context * ctx , <nl> + const char * expected_pem_cert_chain ) { <nl> + grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name ( <nl> + ctx , GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME ) ; <nl> + const grpc_auth_property * prop = grpc_auth_property_iterator_next ( & it ) ; <nl> + if ( prop = = nullptr ) { <nl> + gpr_log ( GPR_ERROR , " Pem certificate chain property not found . " ) ; <nl> + return 0 ; <nl> + } <nl> + if ( strncmp ( prop - > value , expected_pem_cert_chain , prop - > value_length ) ! = 0 ) { <nl> + gpr_log ( GPR_ERROR , " Expected pem cert chain % s and got % s " , <nl> + expected_pem_cert_chain , prop - > value ) ; <nl> + return 0 ; <nl> + } <nl> + if ( grpc_auth_property_iterator_next ( & it ) ! = nullptr ) { <nl> + gpr_log ( GPR_ERROR , " Expected only one property for pem cert chain . " ) ; <nl> + return 0 ; <nl> + } <nl> + return 1 ; <nl> + } <nl> + <nl> static void test_cn_only_ssl_peer_to_auth_context ( void ) { <nl> tsi_peer peer ; <nl> tsi_peer rpeer ; <nl> const char * expected_cn = " cn1 " ; <nl> const char * expected_pem_cert = " pem_cert1 " ; <nl> - GPR_ASSERT ( tsi_construct_peer ( 3 , & peer ) = = TSI_OK ) ; <nl> + const char * expected_pem_cert_chain = " pem_cert1_chain " ; <nl> + GPR_ASSERT ( tsi_construct_peer ( 4 , & peer ) = = TSI_OK ) ; <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_CERTIFICATE_TYPE_PEER_PROPERTY , TSI_X509_CERTIFICATE_TYPE , <nl> & peer . properties [ 0 ] ) = = TSI_OK ) ; <nl> static void test_cn_only_ssl_peer_to_auth_context ( void ) { <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_X509_PEM_CERT_PROPERTY , expected_pem_cert , <nl> & peer . properties [ 2 ] ) = = TSI_OK ) ; <nl> + GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> + TSI_X509_PEM_CERT_CHAIN_PROPERTY , expected_pem_cert_chain , <nl> + & peer . properties [ 3 ] ) = = TSI_OK ) ; <nl> grpc_core : : RefCountedPtr < grpc_auth_context > ctx = <nl> grpc_ssl_peer_to_auth_context ( & peer , GRPC_SSL_TRANSPORT_SECURITY_TYPE ) ; <nl> GPR_ASSERT ( ctx ! = nullptr ) ; <nl> static void test_cn_only_ssl_peer_to_auth_context ( void ) { <nl> GPR_ASSERT ( check_transport_security_type ( ctx . get ( ) ) ) ; <nl> GPR_ASSERT ( check_x509_cn ( ctx . get ( ) , expected_cn ) ) ; <nl> GPR_ASSERT ( check_x509_pem_cert ( ctx . get ( ) , expected_pem_cert ) ) ; <nl> + GPR_ASSERT ( check_x509_pem_cert_chain ( ctx . get ( ) , expected_pem_cert_chain ) ) ; <nl> <nl> rpeer = grpc_shallow_peer_from_ssl_auth_context ( ctx . get ( ) ) ; <nl> GPR_ASSERT ( check_ssl_peer_equivalence ( & peer , & rpeer ) ) ; <nl> static void test_cn_and_one_san_ssl_peer_to_auth_context ( void ) { <nl> const char * expected_cn = " cn1 " ; <nl> const char * expected_san = " san1 " ; <nl> const char * expected_pem_cert = " pem_cert1 " ; <nl> - GPR_ASSERT ( tsi_construct_peer ( 4 , & peer ) = = TSI_OK ) ; <nl> + const char * expected_pem_cert_chain = " pem_cert1_chain " ; <nl> + GPR_ASSERT ( tsi_construct_peer ( 5 , & peer ) = = TSI_OK ) ; <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_CERTIFICATE_TYPE_PEER_PROPERTY , TSI_X509_CERTIFICATE_TYPE , <nl> & peer . properties [ 0 ] ) = = TSI_OK ) ; <nl> static void test_cn_and_one_san_ssl_peer_to_auth_context ( void ) { <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_X509_PEM_CERT_PROPERTY , expected_pem_cert , <nl> & peer . properties [ 3 ] ) = = TSI_OK ) ; <nl> + GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> + TSI_X509_PEM_CERT_CHAIN_PROPERTY , expected_pem_cert_chain , <nl> + & peer . properties [ 4 ] ) = = TSI_OK ) ; <nl> <nl> grpc_core : : RefCountedPtr < grpc_auth_context > ctx = <nl> grpc_ssl_peer_to_auth_context ( & peer , GRPC_SSL_TRANSPORT_SECURITY_TYPE ) ; <nl> static void test_cn_and_one_san_ssl_peer_to_auth_context ( void ) { <nl> GPR_ASSERT ( check_transport_security_type ( ctx . get ( ) ) ) ; <nl> GPR_ASSERT ( check_x509_cn ( ctx . get ( ) , expected_cn ) ) ; <nl> GPR_ASSERT ( check_x509_pem_cert ( ctx . get ( ) , expected_pem_cert ) ) ; <nl> + GPR_ASSERT ( check_x509_pem_cert_chain ( ctx . get ( ) , expected_pem_cert_chain ) ) ; <nl> <nl> rpeer = grpc_shallow_peer_from_ssl_auth_context ( ctx . get ( ) ) ; <nl> GPR_ASSERT ( check_ssl_peer_equivalence ( & peer , & rpeer ) ) ; <nl> static void test_cn_and_multiple_sans_ssl_peer_to_auth_context ( void ) { <nl> const char * expected_cn = " cn1 " ; <nl> const char * expected_sans [ ] = { " san1 " , " san2 " , " san3 " } ; <nl> const char * expected_pem_cert = " pem_cert1 " ; <nl> + const char * expected_pem_cert_chain = " pem_cert1_chain " ; <nl> size_t i ; <nl> - GPR_ASSERT ( tsi_construct_peer ( 3 + GPR_ARRAY_SIZE ( expected_sans ) , & peer ) = = <nl> + GPR_ASSERT ( tsi_construct_peer ( 4 + GPR_ARRAY_SIZE ( expected_sans ) , & peer ) = = <nl> TSI_OK ) ; <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_CERTIFICATE_TYPE_PEER_PROPERTY , TSI_X509_CERTIFICATE_TYPE , <nl> static void test_cn_and_multiple_sans_ssl_peer_to_auth_context ( void ) { <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_X509_PEM_CERT_PROPERTY , expected_pem_cert , <nl> & peer . properties [ 2 ] ) = = TSI_OK ) ; <nl> + GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> + TSI_X509_PEM_CERT_CHAIN_PROPERTY , expected_pem_cert_chain , <nl> + & peer . properties [ 3 ] ) = = TSI_OK ) ; <nl> for ( i = 0 ; i < GPR_ARRAY_SIZE ( expected_sans ) ; i + + ) { <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY , <nl> - expected_sans [ i ] , & peer . properties [ 3 + i ] ) = = TSI_OK ) ; <nl> + expected_sans [ i ] , & peer . properties [ 4 + i ] ) = = TSI_OK ) ; <nl> } <nl> grpc_core : : RefCountedPtr < grpc_auth_context > ctx = <nl> grpc_ssl_peer_to_auth_context ( & peer , GRPC_SSL_TRANSPORT_SECURITY_TYPE ) ; <nl> static void test_cn_and_multiple_sans_ssl_peer_to_auth_context ( void ) { <nl> GPR_ASSERT ( check_transport_security_type ( ctx . get ( ) ) ) ; <nl> GPR_ASSERT ( check_x509_cn ( ctx . get ( ) , expected_cn ) ) ; <nl> GPR_ASSERT ( check_x509_pem_cert ( ctx . get ( ) , expected_pem_cert ) ) ; <nl> + GPR_ASSERT ( check_x509_pem_cert_chain ( ctx . get ( ) , expected_pem_cert_chain ) ) ; <nl> <nl> rpeer = grpc_shallow_peer_from_ssl_auth_context ( ctx . get ( ) ) ; <nl> GPR_ASSERT ( check_ssl_peer_equivalence ( & peer , & rpeer ) ) ; <nl> static void test_cn_and_multiple_sans_and_others_ssl_peer_to_auth_context ( <nl> tsi_peer rpeer ; <nl> const char * expected_cn = " cn1 " ; <nl> const char * expected_pem_cert = " pem_cert1 " ; <nl> + const char * expected_pem_cert_chain = " pem_cert1_chain " ; <nl> const char * expected_sans [ ] = { " san1 " , " san2 " , " san3 " } ; <nl> size_t i ; <nl> - GPR_ASSERT ( tsi_construct_peer ( 5 + GPR_ARRAY_SIZE ( expected_sans ) , & peer ) = = <nl> + GPR_ASSERT ( tsi_construct_peer ( 6 + GPR_ARRAY_SIZE ( expected_sans ) , & peer ) = = <nl> TSI_OK ) ; <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_CERTIFICATE_TYPE_PEER_PROPERTY , TSI_X509_CERTIFICATE_TYPE , <nl> static void test_cn_and_multiple_sans_and_others_ssl_peer_to_auth_context ( <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_X509_PEM_CERT_PROPERTY , expected_pem_cert , <nl> & peer . properties [ 4 ] ) = = TSI_OK ) ; <nl> + GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> + TSI_X509_PEM_CERT_CHAIN_PROPERTY , expected_pem_cert_chain , <nl> + & peer . properties [ 5 ] ) = = TSI_OK ) ; <nl> for ( i = 0 ; i < GPR_ARRAY_SIZE ( expected_sans ) ; i + + ) { <nl> GPR_ASSERT ( tsi_construct_string_peer_property_from_cstring ( <nl> TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY , <nl> - expected_sans [ i ] , & peer . properties [ 5 + i ] ) = = TSI_OK ) ; <nl> + expected_sans [ i ] , & peer . properties [ 6 + i ] ) = = TSI_OK ) ; <nl> } <nl> grpc_core : : RefCountedPtr < grpc_auth_context > ctx = <nl> grpc_ssl_peer_to_auth_context ( & peer , GRPC_SSL_TRANSPORT_SECURITY_TYPE ) ; <nl> static void test_cn_and_multiple_sans_and_others_ssl_peer_to_auth_context ( <nl> GPR_ASSERT ( check_transport_security_type ( ctx . get ( ) ) ) ; <nl> GPR_ASSERT ( check_x509_cn ( ctx . get ( ) , expected_cn ) ) ; <nl> GPR_ASSERT ( check_x509_pem_cert ( ctx . get ( ) , expected_pem_cert ) ) ; <nl> + GPR_ASSERT ( check_x509_pem_cert_chain ( ctx . get ( ) , expected_pem_cert_chain ) ) ; <nl> <nl> rpeer = grpc_shallow_peer_from_ssl_auth_context ( ctx . get ( ) ) ; <nl> GPR_ASSERT ( check_ssl_peer_equivalence ( & peer , & rpeer ) ) ; <nl> static void test_peer_alpn_check ( void ) { <nl> int main ( int argc , char * * argv ) { <nl> grpc : : testing : : TestEnvironment env ( argc , argv ) ; <nl> grpc_init ( ) ; <nl> - <nl> test_unauthenticated_ssl_peer ( ) ; <nl> test_cn_only_ssl_peer_to_auth_context ( ) ; <nl> test_cn_and_one_san_ssl_peer_to_auth_context ( ) ; <nl> mmm a / test / core / security / tls_security_connector_test . cc <nl> ppp b / test / core / security / tls_security_connector_test . cc <nl> class TlsSecurityConnectorTest : public : : testing : : Test { <nl> TEST_F ( TlsSecurityConnectorTest , NoKeysAndConfig ) { <nl> grpc_ssl_certificate_config_reload_status reload_status ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_FAILED_PRECONDITION ) ; <nl> options_ - > Unref ( ) ; <nl> } <nl> TEST_F ( TlsSecurityConnectorTest , NoKeySuccessReload ) { <nl> grpc_ssl_certificate_config_reload_status reload_status ; <nl> SetOptions ( SUCCESS ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , NoKeyFailReload ) { <nl> grpc_ssl_certificate_config_reload_status reload_status ; <nl> SetOptions ( FAIL ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_INTERNAL ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , NoKeyAsyncReload ) { <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> SetOptions ( ASYNC ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_UNIMPLEMENTED ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , NoKeyUnchangedReload ) { <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> SetOptions ( UNCHANGED ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , WithKeyNoReload ) { <nl> GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ; <nl> SetKeyMaterialsConfig ( ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> options_ - > Unref ( ) ; <nl> } <nl> TEST_F ( TlsSecurityConnectorTest , WithKeySuccessReload ) { <nl> SetOptions ( SUCCESS ) ; <nl> SetKeyMaterialsConfig ( ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , WithKeyFailReload ) { <nl> SetOptions ( FAIL ) ; <nl> SetKeyMaterialsConfig ( ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , WithKeyAsyncReload ) { <nl> SetOptions ( ASYNC ) ; <nl> SetKeyMaterialsConfig ( ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ) ; <nl> options_ - > Unref ( ) ; <nl> TEST_F ( TlsSecurityConnectorTest , WithKeyUnchangedReload ) { <nl> SetOptions ( UNCHANGED ) ; <nl> SetKeyMaterialsConfig ( ) ; <nl> grpc_status_code status = <nl> - TlsFetchKeyMaterials ( config_ , * options_ , & reload_status ) ; <nl> + TlsFetchKeyMaterials ( config_ , * options_ , true , & reload_status ) ; <nl> EXPECT_EQ ( status , GRPC_STATUS_OK ) ; <nl> EXPECT_EQ ( reload_status , GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED ) ; <nl> options_ - > Unref ( ) ; <nl> mmm a / test / core / tsi / ssl_transport_security_test . cc <nl> ppp b / test / core / tsi / ssl_transport_security_test . cc <nl> <nl> <nl> extern " C " { <nl> # include < openssl / crypto . h > <nl> + # include < openssl / pem . h > <nl> } <nl> <nl> # define SSL_TSI_TEST_ALPN1 " foo " <nl> void ssl_tsi_test_extract_x509_subject_names ( ) { <nl> tsi_peer_destruct ( & peer ) ; <nl> } <nl> <nl> + void ssl_tsi_test_extract_cert_chain ( ) { <nl> + gpr_log ( GPR_INFO , " ssl_tsi_test_extract_cert_chain " ) ; <nl> + char * cert = load_file ( SSL_TSI_TEST_CREDENTIALS_DIR , " server1 . pem " ) ; <nl> + char * ca = load_file ( SSL_TSI_TEST_CREDENTIALS_DIR , " ca . pem " ) ; <nl> + char * chain = static_cast < char * > ( <nl> + gpr_zalloc ( sizeof ( char ) * ( strlen ( cert ) + strlen ( ca ) + 1 ) ) ) ; <nl> + memcpy ( chain , cert , strlen ( cert ) ) ; <nl> + memcpy ( chain + strlen ( cert ) , ca , strlen ( ca ) ) ; <nl> + STACK_OF ( X509 ) * cert_chain = sk_X509_new_null ( ) ; <nl> + GPR_ASSERT ( cert_chain ! = nullptr ) ; <nl> + BIO * bio = BIO_new_mem_buf ( chain , strlen ( chain ) ) ; <nl> + GPR_ASSERT ( bio ! = nullptr ) ; <nl> + STACK_OF ( X509_INFO ) * certInfos = <nl> + PEM_X509_INFO_read_bio ( bio , nullptr , nullptr , nullptr ) ; <nl> + GPR_ASSERT ( certInfos ! = nullptr ) ; <nl> + for ( int i = 0 ; i < sk_X509_INFO_num ( certInfos ) ; i + + ) { <nl> + X509_INFO * certInfo = sk_X509_INFO_value ( certInfos , i ) ; <nl> + if ( certInfo - > x509 ! = nullptr ) { <nl> + GPR_ASSERT ( sk_X509_push ( cert_chain , certInfo - > x509 ) ! = 0 ) ; <nl> + X509_up_ref ( certInfo - > x509 ) ; <nl> + } <nl> + } <nl> + tsi_peer_property chain_property ; <nl> + GPR_ASSERT ( tsi_ssl_get_cert_chain_contents ( cert_chain , & chain_property ) = = <nl> + TSI_OK ) ; <nl> + GPR_ASSERT ( memcmp ( chain , chain_property . value . data , <nl> + chain_property . value . length ) = = 0 ) ; <nl> + gpr_free ( chain ) ; <nl> + } <nl> + <nl> int main ( int argc , char * * argv ) { <nl> grpc : : testing : : TestEnvironment env ( argc , argv ) ; <nl> grpc_init ( ) ; <nl> int main ( int argc , char * * argv ) { <nl> ssl_tsi_test_handshaker_factory_internals ( ) ; <nl> ssl_tsi_test_duplicate_root_certificates ( ) ; <nl> ssl_tsi_test_extract_x509_subject_names ( ) ; <nl> + ssl_tsi_test_extract_cert_chain ( ) ; <nl> grpc_shutdown ( ) ; <nl> return 0 ; <nl> } <nl> mmm a / test / cpp / client / credentials_test . cc <nl> ppp b / test / cpp / client / credentials_test . cc <nl> TEST_F ( CredentialsTest , TlsCredentialsOptionsCppToC ) { <nl> test_server_authorization_check ) ) ; <nl> <nl> TlsCredentialsOptions options = TlsCredentialsOptions ( <nl> - GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY , key_materials_config , <nl> + GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY , <nl> + GRPC_TLS_SERVER_VERIFICATION , key_materials_config , <nl> credential_reload_config , server_authorization_check_config ) ; <nl> grpc_tls_credentials_options * c_options = options . c_credentials_options ( ) ; <nl> EXPECT_EQ ( c_options - > cert_request_type ( ) , <nl> TEST_F ( CredentialsTest , LoadTlsChannelCredentials ) { <nl> test_server_authorization_check ) ) ; <nl> <nl> TlsCredentialsOptions options = TlsCredentialsOptions ( <nl> - GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY , nullptr , <nl> - credential_reload_config , server_authorization_check_config ) ; <nl> + GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY , <nl> + GRPC_TLS_SERVER_VERIFICATION , nullptr , credential_reload_config , <nl> + server_authorization_check_config ) ; <nl> std : : shared_ptr < grpc_impl : : ChannelCredentials > channel_credentials = <nl> grpc : : experimental : : TlsCredentials ( options ) ; <nl> GPR_ASSERT ( channel_credentials ! = nullptr ) ; <nl>
FullChainExperimental - 01 - 200103
grpc/grpc
db11b94f255ac15596f4feee77485a443d74859e
2020-01-04T06:37:18Z
mmm a / doc / program_model . md <nl> ppp b / doc / program_model . md <nl> generate generic kernels from expression tree at compile time . You can refer to <nl> for more details . CXXNet is a library that makes extensive use of expression template , this enables much shorter and more readable code , with matched <nl> performance with hand crafted kernels . <nl> <nl> - The difference between expression template and python kernel generation is that the expression evaluation is done at compile time of c + + , with a existing type , <nl> + The difference between expression template and python kernel generation is that the expression evaluation is done at compile time of c + + , with an existing type , <nl> so there is no additional runtime overhead . This is also in principle possible with other statically typed language that support template , <nl> however we have only seen this trick in C + + so far . <nl> <nl>
fix typo in doc / program_model . md
apache/incubator-mxnet
ff787ef055f9b0c7d0cfc7435a04a8a92dc84240
2015-11-22T07:13:18Z
mmm a / include / swift / ABI / Metadata . h <nl> ppp b / include / swift / ABI / Metadata . h <nl> struct TargetProtocolRequirement { <nl> ProtocolRequirementFlags Flags ; <nl> / / TODO : name , type <nl> <nl> - / / / A function pointer to a global symbol which is used by client code <nl> - / / / to invoke the protocol requirement from a witness table . This pointer <nl> - / / / is also to uniquely identify the requirement in resilient witness <nl> - / / / tables , which is why it appears here . <nl> - / / / <nl> - / / / This allows clients to call protocol requirements without depending <nl> - / / / on the witness table offset of the requirement . <nl> - / / / <nl> - / / / Will be null if the protocol is not resilient . <nl> - RelativeDirectPointer < void , / * nullable * / true > Function ; <nl> - <nl> / / / The optional default implementation of the protocol . <nl> RelativeDirectPointer < void , / * nullable * / true > DefaultImplementation ; <nl> } ; <nl> mmm a / lib / IRGen / GenMeta . cpp <nl> ppp b / lib / IRGen / GenMeta . cpp <nl> namespace { <nl> <nl> struct RequirementInfo { <nl> ProtocolRequirementFlags Flags ; <nl> - llvm : : Constant * Thunk ; <nl> llvm : : Constant * DefaultImpl ; <nl> } ; <nl> <nl> namespace { <nl> if ( entry . isBase ( ) ) { <nl> assert ( entry . isOutOfLineBase ( ) ) ; <nl> auto flags = Flags ( Flags : : Kind : : BaseProtocol ) ; <nl> - return { flags , nullptr , nullptr } ; <nl> + return { flags , nullptr } ; <nl> } <nl> <nl> if ( entry . isAssociatedType ( ) ) { <nl> auto flags = Flags ( Flags : : Kind : : AssociatedTypeAccessFunction ) ; <nl> - return { flags , nullptr , nullptr } ; <nl> + return { flags , nullptr } ; <nl> } <nl> <nl> if ( entry . isAssociatedConformance ( ) ) { <nl> auto flags = Flags ( Flags : : Kind : : AssociatedConformanceAccessFunction ) ; <nl> - return { flags , nullptr , nullptr } ; <nl> + return { flags , nullptr } ; <nl> } <nl> <nl> assert ( entry . isFunction ( ) ) ; <nl> SILDeclRef func ( entry . getFunction ( ) ) ; <nl> <nl> - / / Look up the dispatch thunk if the protocol is resilient . <nl> - llvm : : Constant * thunk = nullptr ; <nl> + / / Emit the dispatch thunk . <nl> if ( Resilient ) <nl> - thunk = IGM . emitDispatchThunk ( func ) ; <nl> + IGM . emitDispatchThunk ( func ) ; <nl> <nl> / / Classify the function . <nl> auto flags = getMethodDescriptorFlags < Flags > ( func . getDecl ( ) ) ; <nl> namespace { <nl> / / Look for a default witness . <nl> llvm : : Constant * defaultImpl = findDefaultWitness ( func ) ; <nl> <nl> - return { flags , thunk , defaultImpl } ; <nl> + return { flags , defaultImpl } ; <nl> } <nl> <nl> void addRequirements ( ) { <nl> namespace { <nl> / / Flags . <nl> reqt . addInt32 ( info . Flags . getIntValue ( ) ) ; <nl> <nl> - / / Dispatch thunk . <nl> - reqt . addRelativeAddressOrNull ( info . Thunk ) ; <nl> - <nl> / / Default implementation . <nl> reqt . addRelativeAddressOrNull ( info . DefaultImpl ) ; <nl> <nl> mmm a / lib / IRGen / GenThunk . cpp <nl> ppp b / lib / IRGen / GenThunk . cpp <nl> static FunctionPointer lookupMethod ( IRGenFunction & IGF , <nl> return emitVirtualMethodValue ( IGF , metadata , declRef , funcTy ) ; <nl> } <nl> <nl> - llvm : : Function * IRGenModule : : emitDispatchThunk ( SILDeclRef declRef ) { <nl> + void IRGenModule : : emitDispatchThunk ( SILDeclRef declRef ) { <nl> auto * f = getAddrOfDispatchThunk ( declRef , ForDefinition ) ; <nl> <nl> IRGenFunction IGF ( * this , f ) ; <nl> llvm : : Function * IRGenModule : : emitDispatchThunk ( SILDeclRef declRef ) { <nl> IGF . Builder . CreateRetVoid ( ) ; <nl> else <nl> IGF . Builder . CreateRet ( result ) ; <nl> - <nl> - return f ; <nl> } <nl> <nl> llvm : : GlobalValue * IRGenModule : : defineMethodDescriptor ( SILDeclRef declRef , <nl> mmm a / lib / IRGen / IRGenModule . cpp <nl> ppp b / lib / IRGen / IRGenModule . cpp <nl> IRGenModule : : IRGenModule ( IRGenerator & irgen , <nl> ProtocolRequirementStructTy = <nl> createStructType ( * this , " swift . protocol_requirement " , { <nl> Int32Ty , / / flags <nl> - Int32Ty , / / thunk <nl> Int32Ty / / default implementation <nl> } ) ; <nl> <nl> mmm a / lib / IRGen / IRGenModule . h <nl> ppp b / lib / IRGen / IRGenModule . h <nl> private : \ <nl> llvm : : Function * getAddrOfDispatchThunk ( SILDeclRef declRef , <nl> ForDefinition_t forDefinition ) ; <nl> <nl> - llvm : : Function * emitDispatchThunk ( SILDeclRef declRef ) ; <nl> + void emitDispatchThunk ( SILDeclRef declRef ) ; <nl> <nl> llvm : : GlobalValue * defineAlias ( LinkEntity entity , <nl> llvm : : Constant * definition ) ; <nl> mmm a / test / IRGen / protocol_metadata . swift <nl> ppp b / test / IRGen / protocol_metadata . swift <nl> protocol Comprehensive { <nl> / / CHECK - SAME : i32 11 , <nl> / / CHECK - SAME : i32 trunc <nl> / / CHECK - SAME : [ 6 x i8 ] * [ [ COMPREHENSIVE_ASSOC_NAME ] ] <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 7 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 8 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 2 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 17 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 1 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 19 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 20 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 22 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 3 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 4 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 6 , i32 0 , i32 0 } <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 7 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 8 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 2 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 17 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 1 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 19 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 20 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 22 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 3 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 4 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 6 , i32 0 } <nl> <nl> <nl> func reify_metadata < T > ( _ x : T ) { } <nl> mmm a / test / IRGen / protocol_resilience . sil <nl> ppp b / test / IRGen / protocol_resilience . sil <nl> import resilient_protocol <nl> / / CHECK - SAME : @ " $ S19protocol_resilience17ResilientProtocolMp " <nl> <nl> / / Protocol requirements <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 7 , i32 0 , i32 0 } , <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 8 , i32 0 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 7 , i32 0 } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 8 , i32 0 } , <nl> <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 17 , <nl> - / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . opaque * , % swift . type * , i8 * * ) * @ " $ S19protocol_resilience17ResilientProtocolP10noDefaultAyyFTj " to [ [ INT ] ] ) , <nl> - / / CHECK - SAME : i32 0 <nl> - / / CHECK - SAME : } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 17 , i32 0 } , <nl> <nl> - / / CHECK - SAME : % swift . protocol_requirement { i32 17 , <nl> - / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . opaque * , % swift . type * , i8 * * ) * @ " $ S19protocol_resilience17ResilientProtocolP10noDefaultByyFTj " to [ [ INT ] ] ) , <nl> - / / CHECK - SAME : i32 0 <nl> - / / CHECK - SAME : } , <nl> + / / CHECK - SAME : % swift . protocol_requirement { i32 17 , i32 0 } , <nl> <nl> / / CHECK - SAME : % swift . protocol_requirement { i32 17 , <nl> - / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . opaque * , % swift . type * , i8 * * ) * @ " $ S19protocol_resilience17ResilientProtocolP8defaultCyyFTj " to [ [ INT ] ] ) , <nl> / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . opaque * , % swift . type * , i8 * * ) * @ defaultC to [ [ INT ] ] ) , <nl> / / CHECK - SAME : } , <nl> <nl> / / CHECK - SAME : % swift . protocol_requirement { i32 17 , <nl> - / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . opaque * , % swift . type * , i8 * * ) * @ " $ S19protocol_resilience17ResilientProtocolP8defaultDyyFTj " to [ [ INT ] ] ) , <nl> / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . opaque * , % swift . type * , i8 * * ) * @ defaultD to [ [ INT ] ] ) , <nl> / / CHECK - SAME : } , <nl> <nl> / / CHECK - SAME : % swift . protocol_requirement { i32 1 , <nl> - / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . type * , % swift . type * , i8 * * ) * @ " $ S19protocol_resilience17ResilientProtocolP8defaultEyyFZTj " to [ [ INT ] ] ) , <nl> / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . type * , % swift . type * , i8 * * ) * @ defaultE to [ [ INT ] ] ) , <nl> / / CHECK - SAME : } , <nl> <nl> / / CHECK - SAME : % swift . protocol_requirement { i32 1 , <nl> - / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . type * , % swift . type * , i8 * * ) * @ " $ S19protocol_resilience17ResilientProtocolP8defaultFyyFZTj " to [ [ INT ] ] ) , <nl> / / CHECK - SAME : i32 { { | trunc \ ( i64 } } sub ( [ [ INT ] ] ptrtoint ( void ( % swift . type * , % swift . type * , i8 * * ) * @ defaultF to [ [ INT ] ] ) , <nl> / / CHECK - SAME : } <nl> / / CHECK - SAME : } <nl>
IRGen / Runtime : Protocol requirement descriptors don ' t need to reference the dispatch thunk
apple/swift
44c4497ac52f72ba79095e3476cf4b6c172af767
2018-08-31T07:16:22Z
mmm a / src / heap / incremental - marking . cc <nl> ppp b / src / heap / incremental - marking . cc <nl> void IncrementalMarking : : UpdateMarkingWorklistAfterScavenge ( ) { <nl> } <nl> <nl> void IncrementalMarking : : UpdateWeakReferencesAfterScavenge ( ) { <nl> + Heap * heap = heap_ ; <nl> weak_objects_ - > weak_references . Update ( <nl> - [ ] ( std : : pair < HeapObject * , HeapObjectReference * * > slot_in , <nl> - std : : pair < HeapObject * , HeapObjectReference * * > * slot_out ) - > bool { <nl> + [ heap ] ( std : : pair < HeapObject * , HeapObjectReference * * > slot_in , <nl> + std : : pair < HeapObject * , HeapObjectReference * * > * slot_out ) - > bool { <nl> HeapObject * heap_obj = slot_in . first ; <nl> MapWord map_word = heap_obj - > map_word ( ) ; <nl> if ( map_word . IsForwardingAddress ( ) ) { <nl> void IncrementalMarking : : UpdateWeakReferencesAfterScavenge ( ) { <nl> slot_out - > second = reinterpret_cast < HeapObjectReference * * > ( new_slot ) ; <nl> return true ; <nl> } <nl> - if ( heap_obj - > GetHeap ( ) - > InNewSpace ( heap_obj ) ) { <nl> + if ( heap - > InNewSpace ( heap_obj ) ) { <nl> / / The new space object containing the weak reference died . <nl> return false ; <nl> } <nl> void IncrementalMarking : : UpdateWeakReferencesAfterScavenge ( ) { <nl> return true ; <nl> } ) ; <nl> weak_objects_ - > weak_objects_in_code . Update ( <nl> - [ ] ( std : : pair < HeapObject * , Code * > slot_in , <nl> - std : : pair < HeapObject * , Code * > * slot_out ) - > bool { <nl> + [ heap ] ( std : : pair < HeapObject * , Code * > slot_in , <nl> + std : : pair < HeapObject * , Code * > * slot_out ) - > bool { <nl> HeapObject * heap_obj = slot_in . first ; <nl> MapWord map_word = heap_obj - > map_word ( ) ; <nl> if ( map_word . IsForwardingAddress ( ) ) { <nl> slot_out - > first = map_word . ToForwardingAddress ( ) ; <nl> slot_out - > second = slot_in . second ; <nl> - } else { <nl> - * slot_out = slot_in ; <nl> + return true ; <nl> } <nl> + if ( heap - > InNewSpace ( heap_obj ) ) { <nl> + / / The new space object which is referred weakly is dead ( i . e . , didn ' t <nl> + / / get scavenged ) . Drop references to it . <nl> + return false ; <nl> + } <nl> + * slot_out = slot_in ; <nl> return true ; <nl> } ) ; <nl> } <nl> mmm a / test / cctest / heap / heap - tester . h <nl> ppp b / test / cctest / heap / heap - tester . h <nl> class HeapTester { <nl> static AllocationResult AllocateMapForTest ( v8 : : internal : : Isolate * isolate ) ; <nl> static AllocationResult AllocateFixedArrayForTest ( Heap * heap , int length , <nl> PretenureFlag pretenure ) ; <nl> + <nl> + static void UncommitFromSpace ( Heap * heap ) ; <nl> } ; <nl> <nl> } / / namespace heap <nl> mmm a / test / cctest / heap / test - heap . cc <nl> ppp b / test / cctest / heap / test - heap . cc <nl> UNINITIALIZED_TEST ( OutOfMemoryLargeObjects ) { <nl> reinterpret_cast < v8 : : Isolate * > ( isolate ) - > Dispose ( ) ; <nl> } <nl> <nl> + void HeapTester : : UncommitFromSpace ( Heap * heap ) { <nl> + heap - > UncommitFromSpace ( ) ; <nl> + heap - > memory_allocator ( ) - > unmapper ( ) - > EnsureUnmappingCompleted ( ) ; <nl> + } <nl> + <nl> } / / namespace heap <nl> } / / namespace internal <nl> } / / namespace v8 <nl> mmm a / test / cctest / heap / test - weak - references . cc <nl> ppp b / test / cctest / heap / test - weak - references . cc <nl> <nl> # include " src / heap / factory . h " <nl> # include " src / isolate . h " <nl> # include " test / cctest / cctest . h " <nl> + # include " test / cctest / heap / heap - tester . h " <nl> # include " test / cctest / heap / heap - utils . h " <nl> <nl> namespace v8 { <nl> TEST ( WeakArrayListBasic ) { <nl> CHECK_EQ ( Smi : : ToInt ( array - > Get ( 7 ) - > ToSmi ( ) ) , 7 ) ; <nl> } <nl> <nl> + TEST ( Regress7768 ) { <nl> + i : : FLAG_allow_natives_syntax = true ; <nl> + i : : FLAG_turbo_inlining = false ; <nl> + if ( ! FLAG_incremental_marking ) { <nl> + return ; <nl> + } <nl> + ManualGCScope manual_gc_scope ; <nl> + CcTest : : InitializeVM ( ) ; <nl> + LocalContext context ; <nl> + Isolate * isolate = CcTest : : i_isolate ( ) ; <nl> + Heap * heap = isolate - > heap ( ) ; <nl> + HandleScope outer_scope ( isolate ) ; <nl> + / / Create an optimized code which will contain a weak reference to another <nl> + / / function ( " f " ) . The weak reference is the only reference to the function . <nl> + CompileRun ( <nl> + " function myfunc ( f ) { f ( ) ; } " <nl> + " ( function wrapper ( ) { " <nl> + " function f ( ) { } ; myfunc ( f ) ; myfunc ( f ) ; " <nl> + " % OptimizeFunctionOnNextCall ( myfunc ) ; myfunc ( f ) ; " <nl> + " % ClearFunctionFeedback ( wrapper ) ; " <nl> + " } ) ( ) ; " <nl> + " % ClearFunctionFeedback ( myfunc ) ; " ) ; <nl> + <nl> + / / Do marking steps ; this will store the objects pointed by myfunc for later <nl> + / / processing . <nl> + SimulateIncrementalMarking ( heap , true ) ; <nl> + <nl> + / / Deoptimize the code ; now the pointers inside it will be replaced with <nl> + / / undefined , and the weak_objects_in_code is the only place pointing to the <nl> + / / function f . <nl> + CompileRun ( " % DeoptimizeFunction ( myfunc ) ; " ) ; <nl> + <nl> + / / The object pointed to by the weak reference won ' t be scavenged . <nl> + CcTest : : CollectGarbage ( NEW_SPACE ) ; <nl> + <nl> + / / Make sure the memory where it ' s stored is invalidated , so that we ' ll crash <nl> + / / if we try to access it . <nl> + HeapTester : : UncommitFromSpace ( heap ) ; <nl> + <nl> + / / This used to crash when processing the dead weak reference . <nl> + CcTest : : CollectAllGarbage ( ) ; <nl> + } <nl> + <nl> } / / namespace heap <nl> } / / namespace internal <nl> } / / namespace v8 <nl>
[ in - place weak refs ] Fix weak_objects_in_code handling .
v8/v8
131866fb708c1a623aa7cf685ee44438411d106d
2018-05-22T16:46:22Z
mmm a / test / functional / mining_basic . py <nl> ppp b / test / functional / mining_basic . py <nl> def assert_submitblock ( block , result_str_1 , result_str_2 = None ) : <nl> self . log . info ( ' submitheader tests ' ) <nl> assert_raises_rpc_error ( - 22 , ' Block header decode failed ' , lambda : node . submitheader ( hexdata = ' xx ' * BLOCK_HEADER_SIZE ) ) <nl> assert_raises_rpc_error ( - 22 , ' Block header decode failed ' , lambda : node . submitheader ( hexdata = ' ff ' * ( BLOCK_HEADER_SIZE - 2 ) ) ) <nl> - assert_raises_rpc_error ( - 25 , ' Must submit previous header ' , lambda : node . submitheader ( hexdata = ' ff ' * BLOCK_HEADER_SIZE ) ) <nl> + assert_raises_rpc_error ( - 25 , ' Must submit previous header ' , lambda : node . submitheader ( hexdata = super ( CBlock , bad_block ) . serialize ( ) . hex ( ) ) ) <nl> <nl> block . nTime + = 1 <nl> block . solve ( ) <nl>
submitheader : more directly test missing prev block header
bitcoin/bitcoin
b651ef7e1c39a820089695b29d14a07d910a385a
2019-01-24T14:48:34Z
mmm a / src / core / hle / service / hid / hid . cpp <nl> ppp b / src / core / hle / service / hid / hid . cpp <nl> <nl> / / Licensed under GPLv2 or any later version <nl> / / Refer to the license . txt file included . <nl> <nl> - # include < atomic > <nl> # include " common / logging / log . h " <nl> # include " core / core . h " <nl> # include " core / core_timing . h " <nl> class IAppletResource final : public ServiceFramework < IAppletResource > { <nl> SharedMemory mem { } ; <nl> std : : memcpy ( & mem , shared_mem - > GetPointer ( ) , sizeof ( SharedMemory ) ) ; <nl> <nl> - if ( is_device_reload_pending . exchange ( false ) ) <nl> + if ( Settings : : values . is_device_reload_pending . exchange ( false ) ) <nl> LoadInputDevices ( ) ; <nl> <nl> / / Set up controllers as neon red + blue Joy - Con attached to console <nl> class IAppletResource final : public ServiceFramework < IAppletResource > { <nl> CoreTiming : : EventType * pad_update_event ; <nl> <nl> / / Stored input state info <nl> - std : : atomic < bool > is_device_reload_pending { true } ; <nl> std : : array < std : : unique_ptr < Input : : ButtonDevice > , Settings : : NativeButton : : NUM_BUTTONS_HID > <nl> buttons ; <nl> std : : array < std : : unique_ptr < Input : : AnalogDevice > , Settings : : NativeAnalog : : NUM_STICKS_HID > sticks ; <nl> class HidBus final : public ServiceFramework < HidBus > { <nl> } <nl> } ; <nl> <nl> - void ReloadInputDevices ( ) { } <nl> + void ReloadInputDevices ( ) { <nl> + Settings : : values . is_device_reload_pending . store ( true ) ; <nl> + } <nl> <nl> void InstallInterfaces ( SM : : ServiceManager & service_manager ) { <nl> std : : make_shared < Hid > ( ) - > InstallAsService ( service_manager ) ; <nl> mmm a / src / core / settings . h <nl> ppp b / src / core / settings . h <nl> <nl> # pragma once <nl> <nl> # include < array > <nl> + # include < atomic > <nl> # include < string > <nl> # include " common / common_types . h " <nl> <nl> struct Values { <nl> std : : array < std : : string , NativeAnalog : : NumAnalogs > analogs ; <nl> std : : string motion_device ; <nl> std : : string touch_device ; <nl> + std : : atomic_bool is_device_reload_pending { true } ; <nl> <nl> / / Core <nl> bool use_cpu_jit ; <nl>
hid : Implement ReloadInputDevices
yuzu-emu/yuzu
500e81429a883a4721e19158f0c4059fd5e216f6
2018-09-08T22:57:41Z
mmm a / Code / Sandbox / Plugins / MeshImporter / SceneModel . cpp <nl> ppp b / Code / Sandbox / Plugins / MeshImporter / SceneModel . cpp <nl> QVariant CSceneModel : : GetToolTipForColumn ( int column ) <nl> return tr ( " Name of the node in the scene " ) ; <nl> case eColumnType_Type : <nl> return tr ( " Type of this node " ) ; <nl> + case eColumnType_SourceNodeAttribute : <nl> + return tr ( " Attributes of this node " ) ; <nl> default : <nl> assert ( false ) ; <nl> break ; <nl>
! XB ( CE - 12289 ) ( Sandbox ) Add missing tooltip string . ( Approved by samuelk )
CRYTEK/CRYENGINE
7d95ed6f19a2531dc2f82420ef2f0038928a7c0b
2017-05-11T12:19:17Z
mmm a / src / core / ext / client_channel / client_channel . c <nl> ppp b / src / core / ext / client_channel / client_channel . c <nl> static void on_resolver_result_changed_locked ( grpc_exec_ctx * exec_ctx , <nl> / / resolver actually specified . <nl> channel_arg = <nl> grpc_channel_args_find ( chand - > resolver_result , GRPC_ARG_LB_ADDRESSES ) ; <nl> - if ( channel_arg ! = NULL ) { <nl> - GPR_ASSERT ( channel_arg - > type = = GRPC_ARG_POINTER ) ; <nl> + if ( channel_arg ! = NULL & & channel_arg - > type ! = GRPC_ARG_POINTER ) { <nl> grpc_lb_addresses * addresses = channel_arg - > value . pointer . p ; <nl> bool found_backend_address = false ; <nl> for ( size_t i = 0 ; i < addresses - > num_addresses ; + + i ) { <nl> static grpc_error * cc_init_channel_elem ( grpc_exec_ctx * exec_ctx , <nl> / / Record client channel factory . <nl> const grpc_arg * arg = grpc_channel_args_find ( args - > channel_args , <nl> GRPC_ARG_CLIENT_CHANNEL_FACTORY ) ; <nl> - GPR_ASSERT ( arg ! = NULL ) ; <nl> - GPR_ASSERT ( arg - > type = = GRPC_ARG_POINTER ) ; <nl> + if ( arg = = NULL ) { <nl> + return GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Missing client channel factory in args for client channel filter " ) ; <nl> + } <nl> + if ( arg - > type ! = GRPC_ARG_POINTER ) { <nl> + return GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " client channel factory arg must be a pointer " ) ; <nl> + } <nl> grpc_client_channel_factory_ref ( arg - > value . pointer . p ) ; <nl> chand - > client_channel_factory = arg - > value . pointer . p ; <nl> / / Get server name to resolve , using proxy mapper if needed . <nl> arg = grpc_channel_args_find ( args - > channel_args , GRPC_ARG_SERVER_URI ) ; <nl> - GPR_ASSERT ( arg ! = NULL ) ; <nl> - GPR_ASSERT ( arg - > type = = GRPC_ARG_STRING ) ; <nl> + if ( arg = = NULL ) { <nl> + return GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " Missing server uri in args for client channel filter " ) ; <nl> + } <nl> + if ( arg - > type ! = GRPC_ARG_STRING ) { <nl> + return GRPC_ERROR_CREATE_FROM_STATIC_STRING ( <nl> + " server uri arg must be a string " ) ; <nl> + } <nl> char * proxy_name = NULL ; <nl> grpc_channel_args * new_args = NULL ; <nl> grpc_proxy_mappers_map_name ( exec_ctx , arg - > value . string , args - > channel_args , <nl> mmm a / src / core / ext / client_channel / subchannel . c <nl> ppp b / src / core / ext / client_channel / subchannel . c <nl> grpc_subchannel * grpc_subchannel_create ( grpc_exec_ctx * exec_ctx , <nl> for ( size_t i = 0 ; i < c - > args - > num_args ; i + + ) { <nl> if ( 0 = = strcmp ( c - > args - > args [ i ] . key , <nl> " grpc . testing . fixed_reconnect_backoff_ms " ) ) { <nl> - GPR_ASSERT ( c - > args - > args [ i ] . type = = GRPC_ARG_INTEGER ) ; <nl> fixed_reconnect_backoff = true ; <nl> initial_backoff_ms = min_backoff_ms = max_backoff_ms = <nl> grpc_channel_arg_get_integer ( <nl> mmm a / src / core / ext / lb_policy / grpclb / grpclb . c <nl> ppp b / src / core / ext / lb_policy / grpclb / grpclb . c <nl> static grpc_lb_policy * glb_create ( grpc_exec_ctx * exec_ctx , <nl> * this is the right LB policy to use . * / <nl> const grpc_arg * arg = <nl> grpc_channel_args_find ( args - > args , GRPC_ARG_LB_ADDRESSES ) ; <nl> - GPR_ASSERT ( arg ! = NULL & & arg - > type = = GRPC_ARG_POINTER ) ; <nl> + if ( arg = = NULL | | arg - > type ! = GRPC_ARG_POINTER ) { <nl> + return NULL ; <nl> + } <nl> grpc_lb_addresses * addresses = arg - > value . pointer . p ; <nl> size_t num_grpclb_addrs = 0 ; <nl> for ( size_t i = 0 ; i < addresses - > num_addresses ; + + i ) { <nl> mmm a / src / core / ext / lb_policy / pick_first / pick_first . c <nl> ppp b / src / core / ext / lb_policy / pick_first / pick_first . c <nl> static grpc_lb_policy * create_pick_first ( grpc_exec_ctx * exec_ctx , <nl> * addresses , since we don ' t know how to handle them . * / <nl> const grpc_arg * arg = <nl> grpc_channel_args_find ( args - > args , GRPC_ARG_LB_ADDRESSES ) ; <nl> - GPR_ASSERT ( arg ! = NULL & & arg - > type = = GRPC_ARG_POINTER ) ; <nl> + if ( arg = = NULL | | arg - > type ! = GRPC_ARG_POINTER ) { <nl> + return NULL ; <nl> + } <nl> grpc_lb_addresses * addresses = arg - > value . pointer . p ; <nl> size_t num_addrs = 0 ; <nl> for ( size_t i = 0 ; i < addresses - > num_addresses ; i + + ) { <nl> mmm a / src / core / ext / lb_policy / round_robin / round_robin . c <nl> ppp b / src / core / ext / lb_policy / round_robin / round_robin . c <nl> static grpc_lb_policy * round_robin_create ( grpc_exec_ctx * exec_ctx , <nl> * addresses , since we don ' t know how to handle them . * / <nl> const grpc_arg * arg = <nl> grpc_channel_args_find ( args - > args , GRPC_ARG_LB_ADDRESSES ) ; <nl> - GPR_ASSERT ( arg ! = NULL & & arg - > type = = GRPC_ARG_POINTER ) ; <nl> + if ( arg = = NULL | | arg - > type ! = GRPC_ARG_POINTER ) { <nl> + return NULL ; <nl> + } <nl> grpc_lb_addresses * addresses = arg - > value . pointer . p ; <nl> size_t num_addrs = 0 ; <nl> for ( size_t i = 0 ; i < addresses - > num_addresses ; i + + ) { <nl> mmm a / src / core / lib / surface / channel . c <nl> ppp b / src / core / lib / surface / channel . c <nl> grpc_channel * grpc_channel_create_with_builder ( <nl> } else if ( 0 = = strcmp ( args - > args [ i ] . key , <nl> GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL ) ) { <nl> channel - > compression_options . default_level . is_set = true ; <nl> - GPR_ASSERT ( args - > args [ i ] . value . integer > = 0 & & <nl> - args - > args [ i ] . value . integer < GRPC_COMPRESS_LEVEL_COUNT ) ; <nl> channel - > compression_options . default_level . level = <nl> - ( grpc_compression_level ) args - > args [ i ] . value . integer ; <nl> + ( grpc_compression_level ) grpc_channel_arg_get_integer ( <nl> + & args - > args [ i ] , <nl> + ( grpc_integer_options ) { GRPC_COMPRESS_LEVEL_NONE , <nl> + GRPC_COMPRESS_LEVEL_NONE , <nl> + GRPC_COMPRESS_LEVEL_COUNT - 1 } ) ; <nl> } else if ( 0 = = strcmp ( args - > args [ i ] . key , <nl> GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM ) ) { <nl> channel - > compression_options . default_algorithm . is_set = true ; <nl> - GPR_ASSERT ( args - > args [ i ] . value . integer > = 0 & & <nl> - args - > args [ i ] . value . integer < GRPC_COMPRESS_ALGORITHMS_COUNT ) ; <nl> channel - > compression_options . default_algorithm . algorithm = <nl> - ( grpc_compression_algorithm ) args - > args [ i ] . value . integer ; <nl> + ( grpc_compression_algorithm ) grpc_channel_arg_get_integer ( <nl> + & args - > args [ i ] , <nl> + ( grpc_integer_options ) { GRPC_COMPRESS_NONE , GRPC_COMPRESS_NONE , <nl> + GRPC_COMPRESS_ALGORITHMS_COUNT - 1 } ) ; <nl> } else if ( 0 = = <nl> strcmp ( args - > args [ i ] . key , <nl> GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET ) ) { <nl> new file mode 100644 <nl> index 00000000000 . . 95a0b013c0d <nl> Binary files / dev / null and b / test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 5242554383597568 differ <nl> new file mode 100644 <nl> index 00000000000 . . 139fc1cf3f1 <nl> Binary files / dev / null and b / test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 6499902139924480 differ <nl> new file mode 100644 <nl> index 00000000000 . . 74f189b87f7 <nl> Binary files / dev / null and b / test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 6699208922890240 differ <nl> mmm a / tools / run_tests / generated / tests . json <nl> ppp b / tools / run_tests / generated / tests . json <nl> <nl> ] , <nl> " uses_polling " : false <nl> } , <nl> + { <nl> + " args " : [ <nl> + " test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 5242554383597568 " <nl> + ] , <nl> + " ci_platforms " : [ <nl> + " linux " <nl> + ] , <nl> + " cpu_cost " : 0 . 1 , <nl> + " exclude_configs " : [ <nl> + " tsan " <nl> + ] , <nl> + " exclude_iomgrs " : [ <nl> + " uv " <nl> + ] , <nl> + " flaky " : false , <nl> + " language " : " c " , <nl> + " name " : " api_fuzzer_one_entry " , <nl> + " platforms " : [ <nl> + " mac " , <nl> + " linux " <nl> + ] , <nl> + " uses_polling " : false <nl> + } , <nl> { <nl> " args " : [ <nl> " test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 5834320218423296 " <nl> <nl> ] , <nl> " uses_polling " : false <nl> } , <nl> + { <nl> + " args " : [ <nl> + " test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 6499902139924480 " <nl> + ] , <nl> + " ci_platforms " : [ <nl> + " linux " <nl> + ] , <nl> + " cpu_cost " : 0 . 1 , <nl> + " exclude_configs " : [ <nl> + " tsan " <nl> + ] , <nl> + " exclude_iomgrs " : [ <nl> + " uv " <nl> + ] , <nl> + " flaky " : false , <nl> + " language " : " c " , <nl> + " name " : " api_fuzzer_one_entry " , <nl> + " platforms " : [ <nl> + " mac " , <nl> + " linux " <nl> + ] , <nl> + " uses_polling " : false <nl> + } , <nl> { <nl> " args " : [ <nl> " test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 6520142139752448 " <nl> <nl> ] , <nl> " uses_polling " : false <nl> } , <nl> + { <nl> + " args " : [ <nl> + " test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 6699208922890240 " <nl> + ] , <nl> + " ci_platforms " : [ <nl> + " linux " <nl> + ] , <nl> + " cpu_cost " : 0 . 1 , <nl> + " exclude_configs " : [ <nl> + " tsan " <nl> + ] , <nl> + " exclude_iomgrs " : [ <nl> + " uv " <nl> + ] , <nl> + " flaky " : false , <nl> + " language " : " c " , <nl> + " name " : " api_fuzzer_one_entry " , <nl> + " platforms " : [ <nl> + " mac " , <nl> + " linux " <nl> + ] , <nl> + " uses_polling " : false <nl> + } , <nl> { <nl> " args " : [ <nl> " test / core / end2end / fuzzers / api_fuzzer_corpus / clusterfuzz - testcase - 6723650944237568 " <nl>
Don ' t assert over invalid channel args
grpc/grpc
228a5142c198be0e29908776e57260ef661e3dc5
2017-03-31T02:43:00Z
mmm a / xbmc / cores / DllLoader / exports / emu_msvcrt . cpp <nl> ppp b / xbmc / cores / DllLoader / exports / emu_msvcrt . cpp <nl> extern " C " void __stdcall update_emu_environ ( ) <nl> / / Should we check for valid strings here ? should HTTPS_PROXY use https : / / ? <nl> dll_putenv ( " HTTP_PROXY = http : / / " + strProxyServer + " : " + strProxyPort ) ; <nl> dll_putenv ( " HTTPS_PROXY = http : / / " + strProxyServer + " : " + strProxyPort ) ; <nl> + # ifdef _WIN32 <nl> + SetEnvironmentVariable ( " HTTP_PROXY " , " http : / / " + strProxyServer + " : " + strProxyPort ) ; <nl> + SetEnvironmentVariable ( " HTTPS_PROXY " , " http : / / " + strProxyServer + " : " + strProxyPort ) ; <nl> + # endif <nl> + if ( ! g_guiSettings . GetString ( " network . httpproxyusername " ) . IsEmpty ( ) ) <nl> + { <nl> + dll_putenv ( " PROXY_USER = " + g_guiSettings . GetString ( " network . httpproxyusername " ) ) ; <nl> + dll_putenv ( " PROXY_PASS = " + g_guiSettings . GetString ( " network . httpproxypassword " ) ) ; <nl> + # ifdef _WIN32 <nl> + SetEnvironmentVariable ( " PROXY_USER " , g_guiSettings . GetString ( " network . httpproxyusername " ) ) ; <nl> + SetEnvironmentVariable ( " PROXY_PASS " , g_guiSettings . GetString ( " network . httpproxypassword " ) ) ; <nl> + # endif <nl> + } <nl> } <nl> else <nl> { <nl>
fixed : update_emu_environ both was ineffectual on win32 in some instances ( getenv may not be used ) and did not include proxy user and pass .
xbmc/xbmc
676c33556f20359b1ebe75ac9be2b837ae757a4e
2010-07-29T04:14:00Z
mmm a / src / compiler / wasm - compiler . cc <nl> ppp b / src / compiler / wasm - compiler . cc <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> Node * if_not_smi = graph ( ) - > NewNode ( common - > IfTrue ( ) , branch ) ; <nl> <nl> Node * vnot_smi ; <nl> - Node * check_undefined = graph ( ) - > NewNode ( machine - > WordEqual ( ) , value , <nl> - jsgraph ( ) - > UndefinedConstant ( ) ) ; <nl> + Node * undefined_node = <nl> + LOAD_INSTANCE_FIELD ( UndefinedValue , MachineType : : TaggedPointer ( ) ) ; <nl> + Node * check_undefined = <nl> + graph ( ) - > NewNode ( machine - > WordEqual ( ) , value , undefined_node ) ; <nl> Node * branch_undefined = graph ( ) - > NewNode ( <nl> common - > Branch ( BranchHint : : kFalse ) , check_undefined , if_not_smi ) ; <nl> <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> return BuildChangeFloat64ToTagged ( node ) ; <nl> case wasm : : kWasmAnyRef : <nl> return node ; <nl> - case wasm : : kWasmStmt : <nl> - return jsgraph ( ) - > UndefinedConstant ( ) ; <nl> default : <nl> UNREACHABLE ( ) ; <nl> } <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> / / js_context independent . <nl> BuildCallToRuntimeWithContext ( Runtime : : kWasmThrowTypeError , js_context , <nl> nullptr , 0 ) ; <nl> - Return ( jsgraph ( ) - > UndefinedConstant ( ) ) ; <nl> + Return ( jsgraph ( ) - > SmiConstant ( 0 ) ) ; <nl> return ; <nl> } <nl> <nl> class WasmWrapperGraphBuilder : public WasmGraphBuilder { <nl> Node * callables_node = LOAD_INSTANCE_FIELD ( ImportedFunctionCallables , <nl> MachineType : : TaggedPointer ( ) ) ; <nl> Node * callable_node = LOAD_FIXED_ARRAY_SLOT ( callables_node , index ) ; <nl> - Node * undefined_node = jsgraph ( ) - > UndefinedConstant ( ) ; <nl> + Node * undefined_node = <nl> + LOAD_INSTANCE_FIELD ( UndefinedValue , MachineType : : TaggedPointer ( ) ) ; <nl> Node * native_context = <nl> LOAD_INSTANCE_FIELD ( NativeContext , MachineType : : TaggedPointer ( ) ) ; <nl> <nl> void ValidateImportWrapperReferencesImmovables ( Handle < Code > wrapper ) { <nl> / / we didn ' t link yet . <nl> target = Code : : GetCodeFromTargetAddress ( it . rinfo ( ) - > target_address ( ) ) ; <nl> break ; <nl> - case RelocInfo : : EMBEDDED_OBJECT : <nl> - target = it . rinfo ( ) - > target_object ( ) ; <nl> - break ; <nl> default : <nl> UNREACHABLE ( ) ; <nl> } <nl> mmm a / src / wasm / wasm - code - manager . cc <nl> ppp b / src / wasm / wasm - code - manager . cc <nl> void WasmCode : : Validate ( ) const { <nl> case RelocInfo : : VENEER_POOL : <nl> / / These are OK to appear . <nl> break ; <nl> - case RelocInfo : : EMBEDDED_OBJECT : { <nl> - HeapObject * o = it . rinfo ( ) - > target_object ( ) ; <nl> - DCHECK ( o - > IsUndefined ( o - > GetIsolate ( ) ) ) ; <nl> - break ; <nl> - } <nl> default : <nl> FATAL ( " Unexpected mode : % d " , mode ) ; <nl> } <nl> WasmCode * NativeModule : : AddAnonymousCode ( Handle < Code > code , <nl> std : : move ( protected_instructions ) , / / protected_instructions <nl> WasmCode : : kOther , / / kind <nl> WasmCode : : kNoFlushICache ) ; / / flush_icache <nl> - intptr_t delta = ret - > instruction_start ( ) - code - > InstructionStart ( ) ; <nl> - int mask = RelocInfo : : kApplyMask | RelocInfo : : kCodeTargetMask | <nl> - RelocInfo : : ModeMask ( RelocInfo : : EMBEDDED_OBJECT ) ; <nl> <nl> + / / Apply the relocation delta by iterating over the RelocInfo . <nl> + intptr_t delta = ret - > instruction_start ( ) - code - > InstructionStart ( ) ; <nl> + int mask = RelocInfo : : kApplyMask | RelocInfo : : kCodeTargetMask ; <nl> RelocIterator orig_it ( * code , mask ) ; <nl> for ( RelocIterator it ( ret - > instructions ( ) , ret - > reloc_info ( ) , <nl> ret - > constant_pool ( ) , mask ) ; <nl> WasmCode * NativeModule : : AddAnonymousCode ( Handle < Code > code , <nl> it . rinfo ( ) - > set_target_address ( GetLocalAddressFor ( handle ( call_target ) ) , <nl> SKIP_WRITE_BARRIER , SKIP_ICACHE_FLUSH ) ; <nl> } else { <nl> - if ( RelocInfo : : IsEmbeddedObject ( it . rinfo ( ) - > rmode ( ) ) ) { <nl> - DCHECK ( Heap : : IsImmovable ( it . rinfo ( ) - > target_object ( ) ) ) ; <nl> - } else { <nl> - it . rinfo ( ) - > apply ( delta ) ; <nl> - } <nl> + it . rinfo ( ) - > apply ( delta ) ; <nl> } <nl> } <nl> + <nl> / / Flush the i - cache here instead of in AddOwnedCode , to include the changes <nl> / / made while iterating over the RelocInfo above . <nl> Assembler : : FlushICache ( ret - > instructions ( ) . start ( ) , <nl> WasmCode * NativeModule : : AddCode ( <nl> std : : move ( protected_instructions ) , tier , WasmCode : : kNoFlushICache ) ; <nl> <nl> code_table_ [ index ] = ret ; <nl> - / / TODO ( mtrofin ) : this is a copy and paste from Code : : CopyFrom . <nl> - int mode_mask = RelocInfo : : kCodeTargetMask | <nl> - RelocInfo : : ModeMask ( RelocInfo : : EMBEDDED_OBJECT ) | <nl> - RelocInfo : : kApplyMask ; <nl> - / / Needed to find target_object and runtime_entry on X64 <nl> <nl> + / / Apply the relocation delta by iterating over the RelocInfo . <nl> AllowDeferredHandleDereference embedding_raw_address ; <nl> + intptr_t delta = ret - > instructions ( ) . start ( ) - desc . buffer ; <nl> + int mode_mask = RelocInfo : : kApplyMask | RelocInfo : : kCodeTargetMask ; <nl> for ( RelocIterator it ( ret - > instructions ( ) , ret - > reloc_info ( ) , <nl> ret - > constant_pool ( ) , mode_mask ) ; <nl> ! it . done ( ) ; it . next ( ) ) { <nl> RelocInfo : : Mode mode = it . rinfo ( ) - > rmode ( ) ; <nl> - if ( mode = = RelocInfo : : EMBEDDED_OBJECT ) { <nl> - Handle < HeapObject > p = it . rinfo ( ) - > target_object_handle ( origin ) ; <nl> - DCHECK ( p - > IsUndefined ( p - > GetIsolate ( ) ) | | p - > IsNull ( p - > GetIsolate ( ) ) ) ; <nl> - it . rinfo ( ) - > set_target_object ( * p , SKIP_WRITE_BARRIER , SKIP_ICACHE_FLUSH ) ; <nl> - } else if ( RelocInfo : : IsCodeTarget ( mode ) ) { <nl> + if ( RelocInfo : : IsCodeTarget ( mode ) ) { <nl> / / rewrite code handles to direct pointers to the first instruction in the <nl> / / code object <nl> Handle < Object > p = it . rinfo ( ) - > target_object_handle ( origin ) ; <nl> WasmCode * NativeModule : : AddCode ( <nl> it . rinfo ( ) - > set_target_address ( GetLocalAddressFor ( handle ( code ) ) , <nl> SKIP_WRITE_BARRIER , SKIP_ICACHE_FLUSH ) ; <nl> } else { <nl> - intptr_t delta = ret - > instructions ( ) . start ( ) - desc . buffer ; <nl> it . rinfo ( ) - > apply ( delta ) ; <nl> } <nl> } <nl> + <nl> / / Flush the i - cache here instead of in AddOwnedCode , to include the changes <nl> / / made while iterating over the RelocInfo above . <nl> Assembler : : FlushICache ( ret - > instructions ( ) . start ( ) , <nl> mmm a / src / wasm / wasm - objects - inl . h <nl> ppp b / src / wasm / wasm - objects - inl . h <nl> OPTIONAL_ACCESSORS ( WasmInstanceObject , managed_native_allocations , Foreign , <nl> kManagedNativeAllocationsOffset ) <nl> OPTIONAL_ACCESSORS ( WasmInstanceObject , managed_indirect_patcher , Foreign , <nl> kManagedIndirectPatcherOffset ) <nl> + ACCESSORS ( WasmInstanceObject , undefined_value , Oddball , kUndefinedValueOffset ) <nl> ACCESSORS ( WasmInstanceObject , null_value , Oddball , kNullValueOffset ) <nl> <nl> inline bool WasmInstanceObject : : has_indirect_function_table ( ) { <nl> mmm a / src / wasm / wasm - objects . cc <nl> ppp b / src / wasm / wasm - objects . cc <nl> Handle < WasmInstanceObject > WasmInstanceObject : : New ( <nl> instance - > set_compiled_module ( * compiled_module ) ; <nl> instance - > set_native_context ( * isolate - > native_context ( ) ) ; <nl> instance - > set_module_object ( * module_object ) ; <nl> + instance - > set_undefined_value ( isolate - > heap ( ) - > undefined_value ( ) ) ; <nl> instance - > set_null_value ( isolate - > heap ( ) - > null_value ( ) ) ; <nl> <nl> return instance ; <nl> mmm a / src / wasm / wasm - objects . h <nl> ppp b / src / wasm / wasm - objects . h <nl> class WasmInstanceObject : public JSObject { <nl> DECL_OPTIONAL_ACCESSORS ( indirect_function_table_instances , FixedArray ) <nl> DECL_OPTIONAL_ACCESSORS ( managed_native_allocations , Foreign ) <nl> DECL_OPTIONAL_ACCESSORS ( managed_indirect_patcher , Foreign ) <nl> + DECL_ACCESSORS ( undefined_value , Oddball ) <nl> DECL_ACCESSORS ( null_value , Oddball ) <nl> DECL_PRIMITIVE_ACCESSORS ( memory_start , byte * ) <nl> DECL_PRIMITIVE_ACCESSORS ( memory_size , uint32_t ) <nl> class WasmInstanceObject : public JSObject { <nl> V ( kIndirectFunctionTableInstancesOffset , kPointerSize ) \ <nl> V ( kManagedNativeAllocationsOffset , kPointerSize ) \ <nl> V ( kManagedIndirectPatcherOffset , kPointerSize ) \ <nl> + V ( kUndefinedValueOffset , kPointerSize ) \ <nl> V ( kNullValueOffset , kPointerSize ) \ <nl> V ( kFirstUntaggedOffset , 0 ) / * marker * / \ <nl> V ( kMemoryStartOffset , kPointerSize ) / * untagged * / \ <nl> mmm a / src / wasm / wasm - serialization . cc <nl> ppp b / src / wasm / wasm - serialization . cc <nl> bool NativeModuleDeserializer : : ReadCode ( uint32_t fn_index , Reader * reader ) { <nl> WasmCode : : kNoFlushICache ) ; <nl> native_module_ - > code_table_ [ fn_index ] = ret ; <nl> <nl> - / / now relocate the code <nl> - int mask = RelocInfo : : ModeMask ( RelocInfo : : EMBEDDED_OBJECT ) | <nl> - RelocInfo : : ModeMask ( RelocInfo : : CODE_TARGET ) | <nl> + / / Relocate the code . <nl> + int mask = RelocInfo : : ModeMask ( RelocInfo : : CODE_TARGET ) | <nl> RelocInfo : : ModeMask ( RelocInfo : : EXTERNAL_REFERENCE ) | <nl> RelocInfo : : ModeMask ( RelocInfo : : WASM_CODE_TABLE_ENTRY ) ; <nl> for ( RelocIterator iter ( ret - > instructions ( ) , ret - > reloc_info ( ) , <nl> bool NativeModuleDeserializer : : ReadCode ( uint32_t fn_index , Reader * reader ) { <nl> ! iter . done ( ) ; iter . next ( ) ) { <nl> RelocInfo : : Mode mode = iter . rinfo ( ) - > rmode ( ) ; <nl> switch ( mode ) { <nl> - case RelocInfo : : EMBEDDED_OBJECT : { <nl> - / / We only expect { undefined } . We check for that when we add code . <nl> - iter . rinfo ( ) - > set_target_object ( isolate_ - > heap ( ) - > undefined_value ( ) , <nl> - SKIP_WRITE_BARRIER , SKIP_ICACHE_FLUSH ) ; <nl> - break ; <nl> - } <nl> case RelocInfo : : CODE_TARGET : { <nl> uint32_t tag = GetWasmCalleeTag ( iter . rinfo ( ) ) ; <nl> Address target = GetBuiltinTrampolineFromTag ( tag ) ; <nl>
[ wasm ] Avoid embedding { undefined } into { WasmCode } .
v8/v8
502fc4068eff44dbb82bd2357a64050545f741d2
2018-05-29T12:18:03Z
mmm a / cocos / base / CCData . h <nl> ppp b / cocos / base / CCData . h <nl> NS_CC_BEGIN <nl> <nl> class CC_DLL Data <nl> { <nl> + friend class Properties ; <nl> + <nl> public : <nl> / * * <nl> * This parameter is defined for convenient reference if a null Data object is needed . <nl> mmm a / cocos / base / CCProperties . cpp <nl> ppp b / cocos / base / CCProperties . cpp <nl> <nl> <nl> <nl> # include " CCProperties . h " <nl> + <nl> + # include < string . h > <nl> + <nl> # include " platform / CCPlatformMacros . h " <nl> # include " platform / CCFileUtils . h " <nl> # include " math / Vec2 . h " <nl> <nl> # include " deprecated / CCString . h " <nl> <nl> <nl> - <nl> USING_NS_CC ; <nl> <nl> - static void printProperties ( Properties * properties ) <nl> - { <nl> - / / Print the name and ID of the current namespace . <nl> - const char * spacename = properties - > getNamespace ( ) ; <nl> - const char * id = properties - > getId ( ) ; <nl> - CCLOG ( " Namespace : % s ID : % s \ n { " , spacename , id ) ; <nl> - <nl> - / / Print all properties in this namespace . <nl> - const char * name = properties - > getNextProperty ( ) ; <nl> - const char * value = NULL ; <nl> - while ( name ! = NULL ) <nl> - { <nl> - value = properties - > getString ( name ) ; <nl> - CCLOG ( " % s = % s " , name , value ) ; <nl> - name = properties - > getNextProperty ( ) ; <nl> - } <nl> - <nl> - / / Print the properties of every namespace within this one . <nl> - Properties * space = properties - > getNextNamespace ( ) ; <nl> - while ( space ! = NULL ) <nl> - { <nl> - printProperties ( space ) ; <nl> - space = properties - > getNextNamespace ( ) ; <nl> - } <nl> - <nl> - CCLOG ( " } \ n " ) ; <nl> - } <nl> - <nl> / / Utility functions ( shared with SceneLoader ) . <nl> / * * @ script { ignore } * / <nl> void calculateNamespacePath ( const std : : string & urlString , std : : string & fileString , std : : vector < std : : string > & namespacePath ) ; <nl> Properties * getPropertiesFromNamespacePath ( Properties * properties , const std : : ve <nl> Properties : : Properties ( ) <nl> : _variables ( nullptr ) , _dirPath ( nullptr ) , _parent ( nullptr ) , _dataIdx ( nullptr ) , _data ( nullptr ) <nl> { <nl> + _properties . reserve ( 32 ) ; <nl> } <nl> <nl> Properties : : Properties ( const Properties & copy ) <nl> Properties : : Properties ( const Properties & copy ) <nl> _dataIdx ( copy . _dataIdx ) , _data ( copy . _data ) <nl> { <nl> setDirectoryPath ( copy . _dirPath ) ; <nl> - _namespaces = std : : vector < Properties * > ( ) ; <nl> - std : : vector < Properties * > : : const_iterator it ; <nl> - for ( it = copy . _namespaces . begin ( ) ; it < copy . _namespaces . end ( ) ; + + it ) <nl> + <nl> + for ( const auto space : copy . _namespaces ) <nl> { <nl> - GP_ASSERT ( * it ) ; <nl> - _namespaces . push_back ( new ( std : : nothrow ) Properties ( * * it ) ) ; <nl> + _namespaces . push_back ( new ( std : : nothrow ) Properties ( * space ) ) ; <nl> } <nl> rewind ( ) ; <nl> } <nl> Properties : : Properties ( Data * data , ssize_t * dataIdx , const std : : string & name , co <nl> rewind ( ) ; <nl> } <nl> <nl> - Properties * Properties : : create ( const std : : string & url ) <nl> + Properties * Properties : : createWithoutAutorelease ( const std : : string & url ) <nl> { <nl> if ( url . size ( ) = = 0 ) <nl> { <nl> void Properties : : readProperties ( ) <nl> else <nl> { <nl> trimWhiteSpace ( line ) ; <nl> - const int len = strlen ( line ) ; <nl> + const auto len = strlen ( line ) ; <nl> if ( len > = 2 & & strncmp ( line + ( len - 2 ) , " * / " , 2 ) = = 0 ) <nl> comment = false ; <nl> } <nl> signed char Properties : : readChar ( ) <nl> { <nl> if ( eof ( ) ) <nl> return EOF ; <nl> - return _data - > getBytes ( ) [ ( * _dataIdx ) + + ] ; <nl> + return _data - > _bytes [ ( * _dataIdx ) + + ] ; <nl> } <nl> <nl> char * Properties : : readLine ( char * output , int num ) <nl> char * Properties : : readLine ( char * output , int num ) <nl> if ( eof ( ) ) <nl> return nullptr ; <nl> <nl> - auto c = readChar ( ) ; <nl> - while ( c ! = EOF & & c ! = ' \ n ' & & idx - 1 < num ) <nl> - { <nl> - output [ idx + + ] = c ; <nl> - c = readChar ( ) ; <nl> + / / little optimization : avoid uneeded dereferences <nl> + ssize_t dataIdx = * _dataIdx ; <nl> <nl> + while ( dataIdx < _data - > _size & & _data - > _bytes [ dataIdx ] ! = ' \ n ' & & idx - 1 < num ) <nl> + { <nl> + dataIdx + + ; idx + + ; <nl> } <nl> + <nl> + memcpy ( output , & _data - > _bytes [ * _dataIdx ] , idx ) ; <nl> output [ idx ] = ' \ 0 ' ; <nl> <nl> + / / restore value <nl> + * _dataIdx = dataIdx ; <nl> + <nl> return output ; <nl> } <nl> <nl> bool Properties : : seekFromCurrent ( int offset ) <nl> <nl> bool Properties : : eof ( ) <nl> { <nl> - return ( * _dataIdx > = _data - > getSize ( ) ) ; <nl> + return ( * _dataIdx > = _data - > _size ) ; <nl> } <nl> <nl> void Properties : : skipWhiteSpace ( ) <nl> void Properties : : resolveInheritance ( const char * id ) <nl> derived - > _properties = parent - > _properties ; <nl> derived - > _namespaces = std : : vector < Properties * > ( ) ; <nl> std : : vector < Properties * > : : const_iterator itt ; <nl> - for ( itt = parent - > _namespaces . begin ( ) ; itt < parent - > _namespaces . end ( ) ; + + itt ) <nl> + for ( const auto space : parent - > _namespaces ) <nl> { <nl> - GP_ASSERT ( * itt ) ; <nl> - derived - > _namespaces . push_back ( new ( std : : nothrow ) Properties ( * * itt ) ) ; <nl> + derived - > _namespaces . push_back ( new ( std : : nothrow ) Properties ( * space ) ) ; <nl> } <nl> derived - > rewind ( ) ; <nl> <nl> void Properties : : resolveInheritance ( const char * id ) <nl> <nl> void Properties : : mergeWith ( Properties * overrides ) <nl> { <nl> - GP_ASSERT ( overrides ) ; <nl> + CCASSERT ( overrides , " Invalid overrides " ) ; <nl> <nl> / / Overwrite or add each property found in child . <nl> overrides - > rewind ( ) ; <nl> void Properties : : rewind ( ) <nl> <nl> Properties * Properties : : getNamespace ( const char * id , bool searchNames , bool recurse ) const <nl> { <nl> - GP_ASSERT ( id ) ; <nl> + CCASSERT ( id , " invalid id " ) ; <nl> <nl> for ( std : : vector < Properties * > : : const_iterator it = _namespaces . begin ( ) ; it < _namespaces . end ( ) ; + + it ) <nl> { <nl> bool Properties : : exists ( const char * name ) const <nl> if ( name = = NULL ) <nl> return false ; <nl> <nl> - for ( std : : list < Property > : : const_iterator itr = _properties . begin ( ) ; itr ! = _properties . end ( ) ; + + itr ) <nl> + for ( std : : vector < Property > : : const_iterator itr = _properties . begin ( ) ; itr ! = _properties . end ( ) ; + + itr ) <nl> { <nl> if ( itr - > name = = name ) <nl> return true ; <nl> bool Properties : : exists ( const char * name ) const <nl> <nl> static const bool isStringNumeric ( const char * str ) <nl> { <nl> - GP_ASSERT ( str ) ; <nl> + CCASSERT ( str , " invalid str " ) ; <nl> <nl> / / The first character may be ' - ' <nl> if ( * str = = ' - ' ) <nl> const char * Properties : : getString ( const char * name , const char * defaultValue ) co <nl> return getVariable ( variable , defaultValue ) ; <nl> } <nl> <nl> - for ( std : : list < Property > : : const_iterator itr = _properties . begin ( ) ; itr ! = _properties . end ( ) ; + + itr ) <nl> + for ( std : : vector < Property > : : const_iterator itr = _properties . begin ( ) ; itr ! = _properties . end ( ) ; + + itr ) <nl> { <nl> if ( itr - > name = = name ) <nl> { <nl> bool Properties : : setString ( const char * name , const char * value ) <nl> { <nl> if ( name ) <nl> { <nl> - for ( std : : list < Property > : : iterator itr = _properties . begin ( ) ; itr ! = _properties . end ( ) ; + + itr ) <nl> + for ( std : : vector < Property > : : iterator itr = _properties . begin ( ) ; itr ! = _properties . end ( ) ; + + itr ) <nl> { <nl> if ( itr - > name = = name ) <nl> { <nl> long Properties : : getLong ( const char * name ) const <nl> <nl> bool Properties : : getMat4 ( const char * name , Mat4 * out ) const <nl> { <nl> - GP_ASSERT ( out ) ; <nl> + CCASSERT ( out , " Invalid out " ) ; <nl> <nl> const char * valueString = getString ( name ) ; <nl> if ( valueString ) <nl> bool Properties : : getColor ( const char * name , Vec4 * out ) const <nl> <nl> bool Properties : : getPath ( const char * name , std : : string * path ) const <nl> { <nl> - GP_ASSERT ( name & & path ) ; <nl> + CCASSERT ( name & & path , " Invalid name or path " ) ; <nl> const char * valueString = getString ( name ) ; <nl> if ( valueString ) <nl> { <nl> const char * Properties : : getVariable ( const char * name , const char * defaultValue ) <nl> <nl> void Properties : : setVariable ( const char * name , const char * value ) <nl> { <nl> - GP_ASSERT ( name ) ; <nl> + CCASSERT ( name , " Invalid name " ) ; <nl> <nl> Property * prop = NULL ; <nl> <nl> Properties * Properties : : clone ( ) <nl> <nl> for ( size_t i = 0 , count = _namespaces . size ( ) ; i < count ; i + + ) <nl> { <nl> - GP_ASSERT ( _namespaces [ i ] ) ; <nl> + CCASSERT ( _namespaces [ i ] , " Invalid namespace " ) ; <nl> Properties * child = _namespaces [ i ] - > clone ( ) ; <nl> p - > _namespaces . push_back ( child ) ; <nl> child - > _parent = p ; <nl> mmm a / cocos / base / CCProperties . h <nl> ppp b / cocos / base / CCProperties . h <nl> <nl> # include < string > <nl> # include < functional > <nl> # include < cstdint > <nl> - # include < list > <nl> + # include < vector > <nl> <nl> # include " renderer / CCTexture2D . h " <nl> # include " platform / CCPlatformMacros . h " <nl> class Data ; <nl> <nl> @ verbatim <nl> / / Create the top - level Properties object . <nl> - Properties * properties = Properties : : create ( " example . properties " ) ; <nl> + Properties * properties = Properties : : createWithoutAutorelease ( " example . properties " ) ; <nl> / / Retrieve the " spriteTexture " namespace . <nl> Properties * spriteTexture = properties - > getNamespace ( " spriteTexture " ) ; <nl> <nl> class CC_DLL Properties <nl> * @ return The created Properties or NULL if there was an error . <nl> * @ script { create } <nl> * / <nl> - static Properties * create ( const std : : string & url ) ; <nl> + static Properties * createWithoutAutorelease ( const std : : string & url ) ; <nl> <nl> / * * <nl> * Destructor . <nl> class CC_DLL Properties <nl> bool seekFromCurrent ( int offset ) ; <nl> bool eof ( ) ; <nl> <nl> - / / Called after create ( ) ; copies info from parents into derived namespaces . <nl> + / / Called after createWithoutAutorelease ( ) ; copies info from parents into derived namespaces . <nl> void resolveInheritance ( const char * id = NULL ) ; <nl> <nl> / / Called by resolveInheritance ( ) . <nl> class CC_DLL Properties <nl> std : : string _namespace ; <nl> std : : string _id ; <nl> std : : string _parentID ; <nl> - std : : list < Property > _properties ; <nl> - std : : list < Property > : : iterator _propertiesItr ; <nl> + std : : vector < Property > _properties ; <nl> + std : : vector < Property > : : iterator _propertiesItr ; <nl> std : : vector < Properties * > _namespaces ; <nl> std : : vector < Properties * > : : const_iterator _namespacesItr ; <nl> std : : vector < Property > * _variables ; <nl> mmm a / cocos / platform / CCFileUtils . cpp <nl> ppp b / cocos / platform / CCFileUtils . cpp <nl> static Data getData ( const std : : string & filename , bool forString ) <nl> mode = " rt " ; <nl> else <nl> mode = " rb " ; <nl> - <nl> + <nl> + auto fileutils = FileUtils : : getInstance ( ) ; <nl> do <nl> { <nl> / / Read the file from hardware <nl> - std : : string fullPath = FileUtils : : getInstance ( ) - > fullPathForFilename ( filename ) ; <nl> - FILE * fp = fopen ( FileUtils : : getInstance ( ) - > getSuitableFOpen ( fullPath ) . c_str ( ) , mode ) ; <nl> + std : : string fullPath = fileutils - > fullPathForFilename ( filename ) ; <nl> + FILE * fp = fopen ( fileutils - > getSuitableFOpen ( fullPath ) . c_str ( ) , mode ) ; <nl> CC_BREAK_IF ( ! fp ) ; <nl> fseek ( fp , 0 , SEEK_END ) ; <nl> size = ftell ( fp ) ; <nl> static Data getData ( const std : : string & filename , bool forString ) <nl> <nl> if ( nullptr = = buffer | | 0 = = readsize ) <nl> { <nl> - std : : string msg = " Get data from file ( " ; <nl> - msg . append ( filename ) . append ( " ) failed ! " ) ; <nl> - CCLOG ( " % s " , msg . c_str ( ) ) ; <nl> + CCLOG ( " Get data from file % s failed " , filename . c_str ( ) ) ; <nl> } <nl> else <nl> { <nl> mmm a / cocos / renderer / CCMaterial . cpp <nl> ppp b / cocos / renderer / CCMaterial . cpp <nl> bool Material : : initWithFile ( const std : : string & validfilename ) <nl> char * bytes = ( char * ) data . getBytes ( ) ; <nl> bytes [ data . getSize ( ) - 1 ] = ' \ 0 ' ; <nl> <nl> - Properties * properties = Properties : : create ( validfilename ) ; <nl> + / / Warning : properties is not a " Ref " object , must be manually deleted <nl> + Properties * properties = Properties : : createWithoutAutorelease ( validfilename ) ; <nl> <nl> / / get the first material <nl> parseProperties ( ( strlen ( properties - > getNamespace ( ) ) > 0 ) ? properties : properties - > getNextNamespace ( ) ) ; <nl> + <nl> + CC_SAFE_DELETE ( properties ) ; <nl> return true ; <nl> } <nl> <nl> mmm a / tests / cpp - tests / Classes / MaterialSystemTest / MaterialSystemTest . cpp <nl> ppp b / tests / cpp - tests / Classes / MaterialSystemTest / MaterialSystemTest . cpp <nl> <nl> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / <nl> <nl> # include " MaterialSystemTest . h " <nl> + <nl> + # include < ctime > <nl> + <nl> # include " . . / testResource . h " <nl> # include " cocos2d . h " <nl> <nl> MaterialSystemTest : : MaterialSystemTest ( ) <nl> ADD_TEST_CASE ( Material_clone ) ; <nl> ADD_TEST_CASE ( Material_MultipleSprite3D ) ; <nl> ADD_TEST_CASE ( Material_Sprite3DTest ) ; <nl> + ADD_TEST_CASE ( Material_parsePerformance ) ; <nl> } <nl> <nl> std : : string MaterialSystemBaseTest : : title ( ) const <nl> void Material_2DEffects : : onEnter ( ) <nl> { <nl> MaterialSystemBaseTest : : onEnter ( ) ; <nl> <nl> - auto properties = Properties : : create ( " Materials / 2d_effects . material # sample " ) ; <nl> + auto properties = Properties : : createWithoutAutorelease ( " Materials / 2d_effects . material # sample " ) ; <nl> <nl> / / Print the properties of every namespace within this one . <nl> printProperties ( properties , 0 ) ; <nl> void Material_2DEffects : : onEnter ( ) <nl> spriteEdgeDetect - > setNormalizedPosition ( Vec2 ( 0 . 8 , 0 . 5 ) ) ; <nl> this - > addChild ( spriteEdgeDetect ) ; <nl> spriteEdgeDetect - > setGLProgramState ( mat1 - > getTechniqueByName ( " edge_detect " ) - > getPassByIndex ( 0 ) - > getGLProgramState ( ) ) ; <nl> + <nl> + / / properties is not a " Ref " object <nl> + CC_SAFE_DELETE ( properties ) ; <nl> } <nl> <nl> std : : string Material_2DEffects : : subtitle ( ) const <nl> std : : string Material_clone : : subtitle ( ) const <nl> return " Testing material - > clone ( ) " ; <nl> } <nl> <nl> + / / <nl> + / / <nl> + / / <nl> + void Material_parsePerformance : : onEnter ( ) <nl> + { <nl> + MaterialSystemBaseTest : : onEnter ( ) ; <nl> + <nl> + std : : clock_t begin = std : : clock ( ) ; <nl> + <nl> + for ( int i = 0 ; i < 5000 ; i + + ) <nl> + { <nl> + Material : : createWithFilename ( " Materials / 2d_effects . material " ) ; <nl> + Material : : createWithFilename ( " Materials / 3d_effects . material " ) ; <nl> + } <nl> + <nl> + std : : clock_t end = std : : clock ( ) ; <nl> + double elapsed_secs = double ( end - begin ) / CLOCKS_PER_SEC ; <nl> + <nl> + log ( " Parsing took : % f " , elapsed_secs ) ; <nl> + } <nl> + <nl> + std : : string Material_parsePerformance : : subtitle ( ) const <nl> + { <nl> + return " Testing parsing performance " ; <nl> + } <nl> + <nl> / / MARK : Helper functions <nl> <nl> static void printProperties ( Properties * properties , int indent ) <nl> static void printProperties ( Properties * properties , int indent ) <nl> chindent [ i ] = ' ' ; <nl> chindent [ i ] = ' \ 0 ' ; <nl> <nl> - CCLOG ( " % sNamespace : % s ID : % s \ n % s { " , chindent , spacename , id , chindent ) ; <nl> + log ( " % sNamespace : % s ID : % s \ n % s { " , chindent , spacename , id , chindent ) ; <nl> <nl> / / Print all properties in this namespace . <nl> const char * name = properties - > getNextProperty ( ) ; <nl> static void printProperties ( Properties * properties , int indent ) <nl> while ( name ! = NULL ) <nl> { <nl> value = properties - > getString ( name ) ; <nl> - CCLOG ( " % s % s = % s " , chindent , name , value ) ; <nl> + log ( " % s % s = % s " , chindent , name , value ) ; <nl> name = properties - > getNextProperty ( ) ; <nl> } <nl> <nl> static void printProperties ( Properties * properties , int indent ) <nl> space = properties - > getNextNamespace ( ) ; <nl> } <nl> <nl> - CCLOG ( " % s } \ n " , chindent ) ; <nl> + log ( " % s } \ n " , chindent ) ; <nl> } <nl> mmm a / tests / cpp - tests / Classes / MaterialSystemTest / MaterialSystemTest . h <nl> ppp b / tests / cpp - tests / Classes / MaterialSystemTest / MaterialSystemTest . h <nl> class Material_clone : public MaterialSystemBaseTest <nl> virtual std : : string subtitle ( ) const override ; <nl> } ; <nl> <nl> + class Material_parsePerformance : public MaterialSystemBaseTest <nl> + { <nl> + public : <nl> + CREATE_FUNC ( Material_parsePerformance ) ; <nl> + <nl> + virtual void onEnter ( ) override ; <nl> + virtual std : : string subtitle ( ) const override ; <nl> + } ; <nl> + <nl> <nl>
Merge pull request from ricardoquesada / perf_fixes
cocos2d/cocos2d-x
e14643afb2763614f9eb7484617ba4ee3031144a
2015-05-15T01:06:27Z
mmm a / src / lib / libkrbn / include / libkrbn / impl / libkrbn_hid_value_monitor . hpp <nl> ppp b / src / lib / libkrbn / include / libkrbn / impl / libkrbn_hid_value_monitor . hpp <nl> class libkrbn_hid_value_monitor final { <nl> } <nl> } <nl> } <nl> - } else if ( auto v = entry . get_event ( ) . get_if < krbn : : consumer_key_code : : value_t > ( ) ) { <nl> - if ( auto usage_page = krbn : : make_hid_usage_page ( * v ) ) { <nl> - if ( auto usage = krbn : : make_hid_usage ( * v ) ) { <nl> - if ( callback ) { <nl> - callback ( type_safe : : get ( entry . get_device_id ( ) ) , <nl> - type_safe : : get ( * usage_page ) , <nl> - type_safe : : get ( * usage ) , <nl> - event_type , <nl> - refcon ) ; <nl> - } <nl> - } <nl> - } <nl> } else if ( auto e = entry . get_event ( ) . get_if < krbn : : momentary_switch_event > ( ) ) { <nl> if ( auto usage_pair = e - > make_usage_pair ( ) ) { <nl> if ( callback ) { <nl> mmm a / src / share / event_queue / event . hpp <nl> ppp b / src / share / event_queue / event . hpp <nl> class event { <nl> enum class type { <nl> none , <nl> key_code , <nl> - consumer_key_code , <nl> momentary_switch_event , <nl> pointing_motion , <nl> / / virtual events <nl> class event { <nl> } ; <nl> <nl> using value_t = std : : variant < key_code : : value_t , / / For type : : key_code <nl> - consumer_key_code : : value_t , / / For type : : consumer_key_code <nl> momentary_switch_event , / / For type : : momentary_switch_event <nl> pointing_motion , / / For type : : pointing_motion <nl> int64_t , / / For type : : caps_lock_state_changed <nl> class event { <nl> result . type_ = to_type ( value . get < std : : string > ( ) ) ; <nl> } else if ( key = = " key_code " ) { <nl> result . value_ = value . get < key_code : : value_t > ( ) ; <nl> - } else if ( key = = " consumer_key_code " ) { <nl> - result . value_ = value . get < consumer_key_code : : value_t > ( ) ; <nl> } else if ( key = = " momentary_switch_event " ) { <nl> result . value_ = value . get < momentary_switch_event > ( ) ; <nl> } else if ( key = = " pointing_motion " ) { <nl> class event { <nl> } <nl> break ; <nl> <nl> - case type : : consumer_key_code : <nl> - if ( auto v = get_consumer_key_code ( ) ) { <nl> - json [ " consumer_key_code " ] = make_consumer_key_code_name ( * v ) ; <nl> - } <nl> - break ; <nl> - <nl> case type : : momentary_switch_event : <nl> if ( auto v = get_if < momentary_switch_event > ( ) ) { <nl> json [ " momentary_switch_event " ] = * v ; <nl> class event { <nl> value_ ( key_code ) { <nl> } <nl> <nl> - explicit event ( consumer_key_code : : value_t consumer_key_code ) : type_ ( type : : consumer_key_code ) , <nl> - value_ ( consumer_key_code ) { <nl> - } <nl> - <nl> explicit event ( momentary_switch_event momentary_switch_event ) : type_ ( type : : momentary_switch_event ) , <nl> value_ ( momentary_switch_event ) { <nl> } <nl> class event { <nl> return std : : nullopt ; <nl> } <nl> <nl> - std : : optional < consumer_key_code : : value_t > get_consumer_key_code ( void ) const { <nl> - try { <nl> - if ( type_ = = type : : consumer_key_code ) { <nl> - return std : : get < consumer_key_code : : value_t > ( value_ ) ; <nl> - } <nl> - } catch ( std : : bad_variant_access & ) { <nl> - } <nl> - return std : : nullopt ; <nl> - } <nl> - <nl> std : : optional < pointing_motion > get_pointing_motion ( void ) const { <nl> try { <nl> if ( type_ = = type : : pointing_motion ) { <nl> class event { <nl> if ( auto value = get_if < key_code : : value_t > ( ) ) { <nl> return std : : make_shared < momentary_switch_event > ( * value ) ; <nl> <nl> - } else if ( auto value = get_if < consumer_key_code : : value_t > ( ) ) { <nl> - return std : : make_shared < momentary_switch_event > ( * value ) ; <nl> - <nl> } else if ( auto value = get_if < momentary_switch_event > ( ) ) { <nl> return std : : make_shared < momentary_switch_event > ( * value ) ; <nl> } <nl> class event { <nl> switch ( t ) { <nl> TO_C_STRING ( none ) ; <nl> TO_C_STRING ( key_code ) ; <nl> - TO_C_STRING ( consumer_key_code ) ; <nl> TO_C_STRING ( momentary_switch_event ) ; <nl> TO_C_STRING ( pointing_motion ) ; <nl> TO_C_STRING ( shell_command ) ; <nl> class event { <nl> } <nl> <nl> TO_TYPE ( key_code ) ; <nl> - TO_TYPE ( consumer_key_code ) ; <nl> TO_TYPE ( momentary_switch_event ) ; <nl> TO_TYPE ( pointing_motion ) ; <nl> TO_TYPE ( shell_command ) ; <nl> mmm a / src / share / event_queue / utility . hpp <nl> ppp b / src / share / event_queue / utility . hpp <nl> static inline std : : shared_ptr < queue > make_queue ( device_id device_id , <nl> state : : original ) ; <nl> <nl> } else if ( auto consumer_key_code = make_consumer_key_code ( * usage_page , * usage ) ) { <nl> - event_queue : : event event ( * consumer_key_code ) ; <nl> + event_queue : : event event ( momentary_switch_event ( * usage_page , * usage ) ) ; <nl> result - > emplace_back_entry ( device_id , <nl> event_time_stamp ( v . get_time_stamp ( ) ) , <nl> event , <nl> mmm a / src / share / manipulator / manipulator_manager . hpp <nl> ppp b / src / share / manipulator / manipulator_manager . hpp <nl> class manipulator_manager final { <nl> break ; <nl> <nl> case event_queue : : event : : type : : key_code : <nl> - case event_queue : : event : : type : : consumer_key_code : <nl> case event_queue : : event : : type : : momentary_switch_event : <nl> case event_queue : : event : : type : : pointing_motion : <nl> case event_queue : : event : : type : : shell_command : <nl> mmm a / src / share / manipulator / manipulators / basic / basic . hpp <nl> ppp b / src / share / manipulator / manipulators / basic / basic . hpp <nl> class basic final : public base , public pqrs : : dispatcher : : extra : : dispatcher_clie <nl> <nl> void unset_alone_if_needed ( const event_queue : : event & event , <nl> event_type event_type ) { <nl> - if ( event . get_type ( ) = = event_queue : : event : : type : : key_code | | <nl> - event . get_type ( ) = = event_queue : : event : : type : : consumer_key_code ) { <nl> + if ( event . get_type ( ) = = event_queue : : event : : type : : key_code ) { <nl> if ( event_type = = event_type : : key_down ) { <nl> goto run ; <nl> } <nl> mmm a / src / share / manipulator / manipulators / basic / from_event_definition . hpp <nl> ppp b / src / share / manipulator / manipulators / basic / from_event_definition . hpp <nl> class from_event_definition final { <nl> } <nl> } <nl> <nl> - if ( auto consumer_key_code = event . get_consumer_key_code ( ) ) { <nl> - if ( event_definition . get_consumer_key_code ( ) = = consumer_key_code ) { <nl> - return true ; <nl> - } <nl> - } <nl> - <nl> if ( auto event_momentary_switch_event = event . get_if < momentary_switch_event > ( ) ) { <nl> if ( auto event_definition_momentary_switch_event = event_definition . get_if < momentary_switch_event > ( ) ) { <nl> if ( * event_momentary_switch_event = = * event_definition_momentary_switch_event ) { <nl> inline void from_json ( const nlohmann : : json & json , from_event_definition & d ) { <nl> for ( const auto & d : event_definitions ) { <nl> switch ( d . get_type ( ) ) { <nl> case event_definition : : type : : key_code : <nl> - case event_definition : : type : : consumer_key_code : <nl> case event_definition : : type : : momentary_switch_event : <nl> case event_definition : : type : : any : <nl> break ; <nl> mmm a / src / share / manipulator / manipulators / post_event_to_virtual_devices / post_event_to_virtual_devices . hpp <nl> ppp b / src / share / manipulator / manipulators / post_event_to_virtual_devices / post_event_to_virtual_devices . hpp <nl> class post_event_to_virtual_devices final : public base , public pqrs : : dispatcher <nl> <nl> switch ( front_input_event . get_event ( ) . get_type ( ) ) { <nl> case event_queue : : event : : type : : key_code : <nl> - case event_queue : : event : : type : : consumer_key_code : <nl> case event_queue : : event : : type : : momentary_switch_event : <nl> if ( auto e = front_input_event . get_event ( ) . make_momentary_switch_event ( ) ) { <nl> if ( e - > pointing_button ( ) ) { <nl> mmm a / src / share / manipulator / types / event_definition . hpp <nl> ppp b / src / share / manipulator / types / event_definition . hpp <nl> class event_definition final { <nl> enum class type { <nl> none , <nl> key_code , <nl> - consumer_key_code , <nl> momentary_switch_event , <nl> any , <nl> shell_command , <nl> class event_definition final { <nl> <nl> using value_t = std : : variant < std : : monostate , <nl> key_code : : value_t , <nl> - consumer_key_code : : value_t , <nl> momentary_switch_event , <nl> any_type , / / For any <nl> std : : string , / / For shell_command <nl> class event_definition final { <nl> return std : : nullopt ; <nl> } <nl> <nl> - std : : optional < consumer_key_code : : value_t > get_consumer_key_code ( void ) const { <nl> - if ( type_ = = type : : consumer_key_code ) { <nl> - return std : : get < consumer_key_code : : value_t > ( value_ ) ; <nl> - } <nl> - return std : : nullopt ; <nl> - } <nl> - <nl> std : : optional < std : : string > get_shell_command ( void ) const { <nl> if ( type_ = = type : : shell_command ) { <nl> return std : : get < std : : string > ( value_ ) ; <nl> class event_definition final { <nl> return std : : nullopt ; <nl> case type : : key_code : <nl> return event_queue : : event ( std : : get < key_code : : value_t > ( value_ ) ) ; <nl> - case type : : consumer_key_code : <nl> - return event_queue : : event ( std : : get < consumer_key_code : : value_t > ( value_ ) ) ; <nl> case type : : momentary_switch_event : <nl> return event_queue : : event ( std : : get < momentary_switch_event > ( value_ ) ) ; <nl> case type : : any : <nl> class event_definition final { <nl> return true ; <nl> } <nl> <nl> - / / mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - <nl> + / / <nl> / / consumer_key_code <nl> + / / <nl> <nl> if ( key = = " consumer_key_code " ) { <nl> check_type ( json ) ; <nl> <nl> try { <nl> - type_ = type : : consumer_key_code ; <nl> - value_ = value . get < consumer_key_code : : value_t > ( ) ; <nl> + type_ = type : : momentary_switch_event ; <nl> + value_ = momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + * ( make_hid_usage ( value . get < consumer_key_code : : value_t > ( ) ) ) ) ; <nl> } catch ( const pqrs : : json : : unmarshal_error & e ) { <nl> throw pqrs : : json : : unmarshal_error ( fmt : : format ( " ` { 0 } ` error : { 1 } " , key , e . what ( ) ) ) ; <nl> } <nl> mmm a / src / share / manipulator / types / to_event_definition . hpp <nl> ppp b / src / share / manipulator / types / to_event_definition . hpp <nl> inline void from_json ( const nlohmann : : json & json , to_event_definition & d ) { <nl> <nl> switch ( d . get_event_definition ( ) . get_type ( ) ) { <nl> case event_definition : : type : : key_code : <nl> - case event_definition : : type : : consumer_key_code : <nl> case event_definition : : type : : momentary_switch_event : <nl> case event_definition : : type : : shell_command : <nl> case event_definition : : type : : select_input_source : <nl> mmm a / tests / src / core_configuration / src / core_configuration_test . cpp <nl> ppp b / tests / src / core_configuration / src / core_configuration_test . cpp <nl> TEST_CASE ( " simple_modifications . to_json " ) { <nl> { <nl> krbn : : manipulator : : manipulators : : basic : : from_event_definition from_event_definition ( krbn : : json_utility : : parse_jsonc ( simple_modifications . get_pairs ( ) [ 0 ] . first ) ) ; <nl> REQUIRE ( from_event_definition . get_event_definitions ( ) . size ( ) = = 1 ) ; <nl> - REQUIRE ( from_event_definition . get_event_definitions ( ) . front ( ) . get_consumer_key_code ( ) = = krbn : : consumer_key_code : : mute ) ; <nl> + REQUIRE ( from_event_definition . get_event_definitions ( ) . front ( ) . get_if < krbn : : momentary_switch_event > ( ) - > make_usage_pair ( ) - > get_usage_page ( ) = = pqrs : : hid : : usage_page : : consumer ) ; <nl> + REQUIRE ( from_event_definition . get_event_definitions ( ) . front ( ) . get_if < krbn : : momentary_switch_event > ( ) - > make_usage_pair ( ) - > get_usage ( ) = = pqrs : : hid : : usage : : consumer : : mute ) ; <nl> } <nl> { <nl> krbn : : manipulator : : to_event_definition to_event_definition ( krbn : : json_utility : : parse_jsonc ( simple_modifications . get_pairs ( ) [ 0 ] . second ) ) ; <nl> mmm a / tests / src / event_queue / src / event_queue_test . cpp <nl> ppp b / tests / src / event_queue / src / event_queue_test . cpp <nl> krbn : : event_queue : : event right_shift_event ( krbn : : key_code : : keyboard_right_shift ) <nl> krbn : : event_queue : : event spacebar_event ( krbn : : key_code : : keyboard_spacebar ) ; <nl> krbn : : event_queue : : event tab_event ( krbn : : key_code : : keyboard_tab ) ; <nl> <nl> - krbn : : event_queue : : event mute_event ( krbn : : consumer_key_code : : mute ) ; <nl> + krbn : : event_queue : : event mute_event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) ; <nl> <nl> krbn : : event_queue : : event button2_event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : button , <nl> pqrs : : hid : : usage : : button : : button_2 ) ) ; <nl> TEST_CASE ( " json " ) { <nl> REQUIRE ( json = = event_from_json . to_json ( ) ) ; <nl> } <nl> { <nl> - nlohmann : : json expected ; <nl> - expected [ " type " ] = " consumer_key_code " ; <nl> - expected [ " consumer_key_code " ] = " mute " ; <nl> + auto expected = nlohmann : : json : : object ( { <nl> + { " type " , " momentary_switch_event " } , <nl> + { " momentary_switch_event " , nlohmann : : json : : object ( { <nl> + { " consumer_key_code " , " mute " } , <nl> + } ) } , <nl> + } ) ; <nl> auto json = mute_event . to_json ( ) ; <nl> REQUIRE ( json = = expected ) ; <nl> auto event_from_json = krbn : : event_queue : : event : : make_from_json ( json ) ; <nl> TEST_CASE ( " get_key_code " ) { <nl> } <nl> <nl> TEST_CASE ( " get_consumer_key_code " ) { <nl> - REQUIRE ( spacebar_event . get_consumer_key_code ( ) = = std : : nullopt ) ; <nl> - REQUIRE ( mute_event . get_consumer_key_code ( ) = = krbn : : consumer_key_code : : mute ) ; <nl> + REQUIRE ( mute_event . get_if < krbn : : momentary_switch_event > ( ) - > make_usage_pair ( ) = = <nl> + pqrs : : hid : : usage_pair ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) ; <nl> } <nl> <nl> TEST_CASE ( " get_frontmost_application_bundle_identifier " ) { <nl> mmm a / tests / src / event_queue / src / event_queue_utility_test . cpp <nl> ppp b / tests / src / event_queue / src / event_queue_utility_test . cpp <nl> TEST_CASE ( " utility : : make_queue " ) { <nl> auto & e = queue - > get_entries ( ) [ 2 ] ; <nl> REQUIRE ( e . get_device_id ( ) = = krbn : : device_id ( 1 ) ) ; <nl> REQUIRE ( e . get_event_time_stamp ( ) . get_time_stamp ( ) = = krbn : : absolute_time_point ( 3000 ) ) ; <nl> - REQUIRE ( e . get_event ( ) . get_consumer_key_code ( ) = = krbn : : consumer_key_code : : mute ) ; <nl> + REQUIRE ( e . get_event ( ) . get_if < krbn : : momentary_switch_event > ( ) - > make_usage_pair ( ) = = <nl> + pqrs : : hid : : usage_pair ( pqrs : : hid : : usage_page : : consumer , pqrs : : hid : : usage : : consumer : : mute ) ) ; <nl> REQUIRE ( e . get_event_type ( ) = = krbn : : event_type : : key_down ) ; <nl> } <nl> { <nl> auto & e = queue - > get_entries ( ) [ 3 ] ; <nl> REQUIRE ( e . get_device_id ( ) = = krbn : : device_id ( 1 ) ) ; <nl> REQUIRE ( e . get_event_time_stamp ( ) . get_time_stamp ( ) = = krbn : : absolute_time_point ( 4000 ) ) ; <nl> - REQUIRE ( e . get_event ( ) . get_consumer_key_code ( ) = = krbn : : consumer_key_code : : mute ) ; <nl> + REQUIRE ( e . get_event ( ) . get_if < krbn : : momentary_switch_event > ( ) - > make_usage_pair ( ) = = <nl> + pqrs : : hid : : usage_pair ( pqrs : : hid : : usage_page : : consumer , pqrs : : hid : : usage : : consumer : : mute ) ) ; <nl> REQUIRE ( e . get_event_type ( ) = = krbn : : event_type : : key_up ) ; <nl> } <nl> { <nl> TEST_CASE ( " utility : : make_queue " ) { <nl> TEST_CASE ( " utility : : insert_device_keys_and_pointing_buttons_are_released_event " ) { <nl> krbn : : event_queue : : event a_event ( krbn : : key_code : : keyboard_a ) ; <nl> krbn : : event_queue : : event b_event ( krbn : : key_code : : keyboard_b ) ; <nl> - krbn : : event_queue : : event mute_event ( krbn : : consumer_key_code : : mute ) ; <nl> + krbn : : event_queue : : event mute_event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) ; <nl> krbn : : event_queue : : event button2_event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : button , <nl> pqrs : : hid : : usage : : button : : button_2 ) ) ; <nl> <nl> mmm a / tests / src / manipulator_basic / src / manipulator_basic_test . cpp <nl> ppp b / tests / src / manipulator_basic / src / manipulator_basic_test . cpp <nl> TEST_CASE ( " basic : : from_event_definition . test_event " ) { <nl> REQUIRE ( basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_spacebar ) , d ) ) ; <nl> <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_a ) , d ) ) ; <nl> - REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : mute ) , d ) ) ; <nl> + REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) , <nl> + d ) ) ; <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : button , <nl> pqrs : : hid : : usage : : button : : button_1 ) ) , <nl> d ) ) ; <nl> TEST_CASE ( " basic : : from_event_definition . test_event " ) { <nl> { " consumer_key_code " , " rewind " } , <nl> } ) ) ; <nl> <nl> - REQUIRE ( basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : rewind ) , d ) ) ; <nl> + REQUIRE ( basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : rewind ) ) , <nl> + d ) ) ; <nl> <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_a ) , d ) ) ; <nl> - REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : mute ) , d ) ) ; <nl> + REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) , <nl> + d ) ) ; <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : button , <nl> pqrs : : hid : : usage : : button : : button_1 ) ) , <nl> d ) ) ; <nl> TEST_CASE ( " basic : : from_event_definition . test_event " ) { <nl> d ) ) ; <nl> <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_a ) , d ) ) ; <nl> - REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : mute ) , d ) ) ; <nl> + REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) , <nl> + d ) ) ; <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : button , <nl> pqrs : : hid : : usage : : button : : button_1 ) ) , <nl> d ) ) ; <nl> TEST_CASE ( " basic : : from_event_definition . test_event " ) { <nl> } ) ) ; <nl> <nl> REQUIRE ( basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_a ) , d ) ) ; <nl> - REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : mute ) , d ) ) ; <nl> + REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) , <nl> + d ) ) ; <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( <nl> krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : apple_vendor_keyboard , <nl> pqrs : : hid : : usage : : apple_vendor_keyboard : : expose_all ) ) , <nl> TEST_CASE ( " basic : : from_event_definition . test_event " ) { <nl> } ) ) ; <nl> <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_a ) , d ) ) ; <nl> - REQUIRE ( basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : mute ) , d ) ) ; <nl> + REQUIRE ( basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) , <nl> + d ) ) ; <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( <nl> krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : apple_vendor_keyboard , <nl> pqrs : : hid : : usage : : apple_vendor_keyboard : : expose_all ) ) , <nl> TEST_CASE ( " basic : : from_event_definition . test_event " ) { <nl> } ) ) ; <nl> <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : key_code : : keyboard_a ) , d ) ) ; <nl> - REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : consumer_key_code : : mute ) , d ) ) ; <nl> + REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : consumer , <nl> + pqrs : : hid : : usage : : consumer : : mute ) ) , <nl> + d ) ) ; <nl> REQUIRE ( ! basic : : from_event_definition : : test_event ( krbn : : event_queue : : event ( <nl> krbn : : momentary_switch_event ( pqrs : : hid : : usage_page : : apple_vendor_keyboard , <nl> pqrs : : hid : : usage : : apple_vendor_keyboard : : expose_all ) ) , <nl> mmm a / tests / src / post_event_to_virtual_devices / json / input_event_queue / from_any_1 . json <nl> ppp b / tests / src / post_event_to_virtual_devices / json / input_event_queue / from_any_1 . json <nl> <nl> " device_id " : 1 , <nl> " event " : { <nl> " consumer_key_code " : " mute " , <nl> - " type " : " consumer_key_code " <nl> + " type " : " momentary_switch_event " , <nl> + " momentary_switch_event " : { <nl> + " consumer_key_code " : " mute " <nl> + } <nl> } , <nl> " event_type " : " key_down " , <nl> " lazy " : false , <nl> <nl> " device_id " : 1 , <nl> " event " : { <nl> " consumer_key_code " : " mute " , <nl> - " type " : " consumer_key_code " <nl> + " type " : " momentary_switch_event " , <nl> + " momentary_switch_event " : { <nl> + " consumer_key_code " : " mute " <nl> + } <nl> } , <nl> " event_type " : " key_up " , <nl> " lazy " : false , <nl> <nl> " device_id " : 1 , <nl> " event " : { <nl> " consumer_key_code " : " mute " , <nl> - " type " : " consumer_key_code " <nl> + " type " : " momentary_switch_event " , <nl> + " momentary_switch_event " : { <nl> + " consumer_key_code " : " mute " <nl> + } <nl> } , <nl> " event_type " : " key_down " , <nl> " lazy " : false , <nl> <nl> " device_id " : 1 , <nl> " event " : { <nl> " consumer_key_code " : " mute " , <nl> - " type " : " consumer_key_code " <nl> + " type " : " momentary_switch_event " , <nl> + " momentary_switch_event " : { <nl> + " consumer_key_code " : " mute " <nl> + } <nl> } , <nl> " event_type " : " key_up " , <nl> " lazy " : false , <nl> <nl> " device_id " : 1 , <nl> " event " : { <nl> " consumer_key_code " : " mute " , <nl> - " type " : " consumer_key_code " <nl> + " type " : " momentary_switch_event " , <nl> + " momentary_switch_event " : { <nl> + " consumer_key_code " : " mute " <nl> + } <nl> } , <nl> " event_type " : " key_down " , <nl> " lazy " : false , <nl> <nl> " device_id " : 1 , <nl> " event " : { <nl> " consumer_key_code " : " mute " , <nl> - " type " : " consumer_key_code " <nl> + " type " : " momentary_switch_event " , <nl> + " momentary_switch_event " : { <nl> + " consumer_key_code " : " mute " <nl> + } <nl> } , <nl> " event_type " : " key_up " , <nl> " lazy " : false , <nl>
Remove event_queue : : event : : type : : consumer_key_code
pqrs-org/Karabiner-Elements
093f664c27886f22dd69d161c60f5d7510b9a6c4
2020-11-30T00:32:43Z
deleted file mode 100644 <nl> index e3c3e5ccc8f9 . . 000000000000 <nl> mmm a / test / Constraints / disjunction_ordering_failures . swift <nl> ppp / dev / null <nl> <nl> - / / RUN : % target - typecheck - verify - swift <nl> - / / REQUIRES : objc_interop <nl> - <nl> - import Foundation <nl> - <nl> - / / rdar : / / problem / 32186599 <nl> - public protocol P { } <nl> - extension CGFloat : P { } <nl> - <nl> - func rdar32186599 ( ) { <nl> - let h : CGFloat = 0 <nl> - let _ : P = - ( h / 2 ) <nl> - } <nl>
Merge remote - tracking branch ' origin / master ' into master - next
apple/swift
6eb9c677db5c5099d6e2c9b70da8d533322ba908
2017-05-16T04:29:04Z
mmm a / docs / ru / interfaces / third - party_client_libraries . rst <nl> ppp b / docs / ru / interfaces / third - party_client_libraries . rst <nl> <nl> - ` clickhouse - php - client < https : / / github . com / 8bitov / clickhouse - php - client > ` _ <nl> - ` PhpClickHouseClient < https : / / github . com / SevaCode / PhpClickHouseClient > ` _ <nl> - ` phpClickHouse < https : / / github . com / smi2 / phpClickHouse > ` _ <nl> + - ` clickhouse - client < https : / / github . com / bozerkins / clickhouse - client > ` _ <nl> * Go <nl> - ` clickhouse < https : / / github . com / kshvakov / clickhouse / > ` _ <nl> - ` go - clickhouse < https : / / github . com / roistat / go - clickhouse > ` _ <nl>
added another php clickhouse client ( ru version )
ClickHouse/ClickHouse
40a4ef7a83280a473f30b80973c9600e91727307
2017-09-19T22:20:48Z
mmm a / src / bridge / bridgemain . h <nl> ppp b / src / bridge / bridgemain . h <nl> typedef enum <nl> GUI_REF_GETCELLCONTENT , / / param1 = int row , param2 = int col <nl> GUI_REF_RELOADDATA , / / param1 = unused , param2 = unused <nl> GUI_REF_SETSINGLESELECTION , / / param1 = int index , param2 = bool scroll <nl> - GUI_REF_SETPROGRESS , / / param1 = int progress , param2 = unused <nl> + GUI_REF_SETPROGRESS , / / param1 = int progress , param2 = unused <nl> GUI_REF_SETSEARCHSTARTCOL , / / param1 = int col param2 = unused <nl> GUI_STACK_DUMP_AT , / / param1 = duint addr , param2 = duint csp <nl> GUI_UPDATE_DUMP_VIEW , / / param1 = unused , param2 = unused <nl> typedef enum <nl> GUI_GETLINE_WINDOW , / / param1 = const char * title , param2 = char * text <nl> GUI_AUTOCOMPLETE_ADDCMD , / / param1 = const char * cmd , param2 = ununsed <nl> GUI_AUTOCOMPLETE_DELCMD , / / param1 = const char * cmd , param2 = ununsed <nl> - GUI_AUTOCOMPLETE_CLEARALL , / / param1 = unused , param2 = unused <nl> + GUI_AUTOCOMPLETE_CLEARALL , / / param1 = unused , param2 = unused <nl> GUI_SCRIPT_ENABLEHIGHLIGHTING , / / param1 = bool enable , param2 = unused <nl> GUI_ADD_MSG_TO_STATUSBAR , / / param1 = const char * msg , param2 = unused <nl> GUI_UPDATE_SIDEBAR , / / param1 = unused , param2 = unused <nl> mmm a / src / dbg / commandline . cpp <nl> ppp b / src / dbg / commandline . cpp <nl> void CmdLineCacheLoad ( JSON Root ) <nl> <nl> / / Return if there was nothing to load <nl> if ( ! jsonCmdLine ) <nl> + { <nl> + json_decref ( jsonCmdLine ) ; <nl> return ; <nl> + } <nl> <nl> const char * cmdLine = json_string_value ( json_object_get ( jsonCmdLine , " cmdLine " ) ) ; <nl> <nl> strcpy_s ( commandLine , cmdLine ) ; <nl> + <nl> + json_decref ( jsonCmdLine ) ; <nl> } <nl> <nl> void copyCommandLine ( const char * cmdLine ) <nl> mmm a / src / dbg / debugger . cpp <nl> ppp b / src / dbg / debugger . cpp <nl> static bool isDetachedByUser = false ; <nl> static bool bIsAttached = false ; <nl> static bool bSkipExceptions = false ; <nl> static bool bBreakOnNextDll = false ; <nl> + static bool bFreezeStack = false ; <nl> static int ecount = 0 ; <nl> static std : : vector < ExceptionRange > ignoredExceptionRange ; <nl> static HANDLE hEvent = 0 ; <nl> void dbgsetisdetachedbyuser ( bool b ) <nl> isDetachedByUser = b ; <nl> } <nl> <nl> + void dbgsetfreezestack ( bool freeze ) <nl> + { <nl> + bFreezeStack = freeze ; <nl> + } <nl> + <nl> void dbgclearignoredexceptions ( ) <nl> { <nl> ignoredExceptionRange . clear ( ) ; <nl> void DebugUpdateGui ( duint disasm_addr , bool stack ) <nl> } <nl> duint csp = GetContextDataEx ( hActiveThread , UE_CSP ) ; <nl> if ( stack ) <nl> - GuiStackDumpAt ( csp , csp ) ; <nl> + DebugUpdateStack ( csp , csp ) ; <nl> static duint cacheCsp = 0 ; <nl> if ( csp ! = cacheCsp ) <nl> { <nl> void DebugUpdateGui ( duint disasm_addr , bool stack ) <nl> GuiUpdateAllViews ( ) ; <nl> } <nl> <nl> + void DebugUpdateStack ( duint dumpAddr , duint csp , bool forceDump ) <nl> + { <nl> + if ( ! forceDump & & bFreezeStack ) <nl> + { <nl> + SELECTIONDATA selection ; <nl> + if ( GuiSelectionGet ( GUI_STACK , & selection ) ) <nl> + dumpAddr = selection . start ; <nl> + } <nl> + GuiStackDumpAt ( dumpAddr , csp ) ; <nl> + } <nl> + <nl> void cbUserBreakpoint ( ) <nl> { <nl> hActiveThread = ThreadGetHandle ( ( ( DEBUG_EVENT * ) GetDebugData ( ) ) - > dwThreadId ) ; <nl> DWORD WINAPI threadDebugLoop ( void * lpParameter ) <nl> bIsAttached = false ; <nl> bSkipExceptions = false ; <nl> bBreakOnNextDll = false ; <nl> + bFreezeStack = false ; <nl> INIT_STRUCT * init = ( INIT_STRUCT * ) lpParameter ; <nl> bFileIsDll = IsFileDLLW ( StringUtils : : Utf8ToUtf16 ( init - > exe ) . c_str ( ) , 0 ) ; <nl> pDebuggedEntry = GetPE32DataW ( StringUtils : : Utf8ToUtf16 ( init - > exe ) . c_str ( ) , 0 , UE_OEP ) ; <nl> DWORD WINAPI threadAttachLoop ( void * lpParameter ) <nl> lock ( WAITID_STOP ) ; <nl> bIsAttached = true ; <nl> bSkipExceptions = false ; <nl> + bFreezeStack = false ; <nl> DWORD pid = ( DWORD ) lpParameter ; <nl> static PROCESS_INFORMATION pi_attached ; <nl> fdProcessInfo = & pi_attached ; <nl> mmm a / src / dbg / debugger . h <nl> ppp b / src / dbg / debugger . h <nl> bool dbgisrunning ( ) ; <nl> bool dbgisdll ( ) ; <nl> void dbgsetattachevent ( HANDLE handle ) ; <nl> void DebugUpdateGui ( duint disasm_addr , bool stack ) ; <nl> + void DebugUpdateStack ( duint dumpAddr , duint csp , bool forceDump = false ) ; <nl> void dbgsetskipexceptions ( bool skip ) ; <nl> void dbgsetstepping ( bool stepping ) ; <nl> void dbgsetispausedbyuser ( bool b ) ; <nl> void dbgsetisdetachedbyuser ( bool b ) ; <nl> + void dbgsetfreezestack ( bool freeze ) ; <nl> void dbgclearignoredexceptions ( ) ; <nl> void dbgaddignoredexception ( ExceptionRange range ) ; <nl> bool dbgisignoredexception ( unsigned int exception ) ; <nl> mmm a / src / dbg / debugger_commands . cpp <nl> ppp b / src / dbg / debugger_commands . cpp <nl> CMDRESULT cbDebugStackDump ( int argc , char * argv [ ] ) <nl> duint size = 0 ; <nl> duint base = MemFindBaseAddr ( csp , & size ) ; <nl> if ( base & & addr > = base & & addr < ( base + size ) ) <nl> - GuiStackDumpAt ( addr , csp ) ; <nl> + DebugUpdateStack ( addr , csp , true ) ; <nl> else <nl> dputs ( " Invalid stack address ! " ) ; <nl> return STATUS_CONTINUE ; <nl> CMDRESULT cbDebugSkip ( int argc , char * argv [ ] ) <nl> DebugUpdateGui ( cip , false ) ; / / update GUI <nl> return STATUS_CONTINUE ; <nl> } <nl> + <nl> + CMDRESULT cbDebugSetfreezestack ( int argc , char * argv [ ] ) <nl> + { <nl> + if ( argc < 2 ) <nl> + { <nl> + dputs ( " Not enough arguments ! " ) ; <nl> + return STATUS_ERROR ; <nl> + } <nl> + bool freeze = * argv [ 1 ] ! = ' 0 ' ; <nl> + dbgsetfreezestack ( freeze ) ; <nl> + dprintf ( " Stack is now % s \ n " , freeze ? " freezed " : " unfreezed " ) ; <nl> + return STATUS_CONTINUE ; <nl> + } <nl> \ No newline at end of file <nl> mmm a / src / dbg / debugger_commands . h <nl> ppp b / src / dbg / debugger_commands . h <nl> CMDRESULT cbDebugDownloadSymbol ( int argc , char * argv [ ] ) ; <nl> CMDRESULT cbDebugGetPageRights ( int argc , char * argv [ ] ) ; <nl> CMDRESULT cbDebugSetPageRights ( int argc , char * argv [ ] ) ; <nl> CMDRESULT cbDebugSkip ( int argc , char * argv [ ] ) ; <nl> + CMDRESULT cbDebugSetfreezestack ( int argc , char * argv [ ] ) ; <nl> <nl> / / misc <nl> void showcommandlineerror ( cmdline_error_t * cmdline_error ) ; <nl> mmm a / src / dbg / instruction . cpp <nl> ppp b / src / dbg / instruction . cpp <nl> CMDRESULT cbInstrPush ( int argc , char * argv [ ] ) <nl> } <nl> Script : : Stack : : Push ( value ) ; <nl> duint csp = GetContextDataEx ( hActiveThread , UE_CSP ) ; <nl> - GuiStackDumpAt ( csp , csp ) ; <nl> + DebugUpdateStack ( csp , csp ) ; <nl> GuiUpdateRegisterView ( ) ; <nl> return STATUS_CONTINUE ; <nl> } <nl> CMDRESULT cbInstrPop ( int argc , char * argv [ ] ) <nl> { <nl> duint value = Script : : Stack : : Pop ( ) ; <nl> duint csp = GetContextDataEx ( hActiveThread , UE_CSP ) ; <nl> - GuiStackDumpAt ( csp , csp ) ; <nl> + DebugUpdateStack ( csp , csp ) ; <nl> GuiUpdateRegisterView ( ) ; <nl> if ( argc > 1 ) <nl> { <nl> mmm a / src / dbg / value . cpp <nl> ppp b / src / dbg / value . cpp <nl> bool valtostring ( const char * string , duint value , bool silent ) <nl> else if ( strstr ( regName ( ) , " sp " ) ) / / update stack <nl> { <nl> duint csp = GetContextDataEx ( hActiveThread , UE_CSP ) ; <nl> - GuiStackDumpAt ( csp , csp ) ; <nl> + DebugUpdateStack ( csp , csp ) ; <nl> GuiUpdateRegisterView ( ) ; <nl> } <nl> else <nl> mmm a / src / dbg / x64_dbg . cpp <nl> ppp b / src / dbg / x64_dbg . cpp <nl> static void registercommands ( ) <nl> dbgcmdnew ( " setcmdline \ 1setcommandline " , cbDebugSetCmdline , true ) ; / / Set CmdLine <nl> dbgcmdnew ( " loadlib " , cbDebugLoadLib , true ) ; / / Load DLL <nl> dbgcmdnew ( " skip " , cbDebugSkip , true ) ; / / skip one instruction <nl> + dbgcmdnew ( " setfreezestack " , cbDebugSetfreezestack , false ) ; / / freeze the stack from auto updates <nl> <nl> / / breakpoints <nl> dbgcmdnew ( " bplist " , cbDebugBplist , true ) ; / / breakpoint list <nl> mmm a / src / gui / Src / BasicView / Disassembly . cpp <nl> ppp b / src / gui / Src / BasicView / Disassembly . cpp <nl> <nl> # include " Disassembly . h " <nl> # include " Configuration . h " <nl> # include " Bridge . h " <nl> + # include " MainWindow . h " <nl> <nl> Disassembly : : Disassembly ( QWidget * parent ) : AbstractTableView ( parent ) <nl> { <nl> void Disassembly : : disassembleAt ( dsint parVA , dsint parCIP , bool history , dsint n <nl> { <nl> dsint wBase = DbgMemFindBaseAddr ( parVA , 0 ) ; <nl> dsint wSize = DbgMemGetPageSize ( wBase ) ; <nl> + <nl> if ( ! wBase | | ! wSize ) <nl> return ; <nl> dsint wRVA = parVA - wBase ; <nl> void Disassembly : : disassembleAt ( dsint parVA , dsint parCIP , bool history , dsint n <nl> mCurrentVa + + ; <nl> newHistory . va = selectionVA ; <nl> newHistory . tableOffset = selectionTableOffset ; <nl> + newHistory . windowTitle = MainWindow : : windowTitle ; <nl> mVaHistory . push_back ( newHistory ) ; <nl> } <nl> } <nl> void Disassembly : : disassembleAt ( dsint parVA , dsint parCIP , bool history , dsint n <nl> / / new disassembled address <nl> newHistory . va = parVA ; <nl> newHistory . tableOffset = getTableOffset ( ) ; <nl> + newHistory . windowTitle = MainWindow : : windowTitle ; <nl> if ( mVaHistory . size ( ) ) <nl> { <nl> if ( mVaHistory . last ( ) . va ! = parVA ) / / not 2x the same va in history <nl> void Disassembly : : historyPrevious ( ) <nl> return ; <nl> mCurrentVa - - ; <nl> disassembleAt ( mVaHistory . at ( mCurrentVa ) . va , rvaToVa ( mCipRva ) , false , mVaHistory . at ( mCurrentVa ) . tableOffset ) ; <nl> + <nl> + / / Update window title <nl> + emit updateWindowTitle ( mVaHistory . at ( mCurrentVa ) . windowTitle ) ; <nl> } <nl> <nl> void Disassembly : : historyNext ( ) <nl> void Disassembly : : historyNext ( ) <nl> return ; <nl> mCurrentVa + + ; <nl> disassembleAt ( mVaHistory . at ( mCurrentVa ) . va , rvaToVa ( mCipRva ) , false , mVaHistory . at ( mCurrentVa ) . tableOffset ) ; <nl> + <nl> + / / Update window title <nl> + emit updateWindowTitle ( mVaHistory . at ( mCurrentVa ) . windowTitle ) ; <nl> } <nl> <nl> bool Disassembly : : historyHasPrevious ( ) <nl> mmm a / src / gui / Src / BasicView / Disassembly . h <nl> ppp b / src / gui / Src / BasicView / Disassembly . h <nl> class Disassembly : public AbstractTableView <nl> signals : <nl> void selectionChanged ( dsint parVA ) ; <nl> void disassembledAt ( dsint parVA , dsint parCIP , bool history , dsint newTableOffset ) ; <nl> + void updateWindowTitle ( QString title ) ; <nl> <nl> public slots : <nl> void disassembleAt ( dsint parVA , dsint parCIP ) ; <nl> public slots : <nl> { <nl> dsint va ; <nl> dsint tableOffset ; <nl> + QString windowTitle ; <nl> } HistoryData_t ; <nl> <nl> QList < HistoryData_t > mVaHistory ; <nl> mmm a / src / gui / Src / Gui / CPUStack . cpp <nl> ppp b / src / gui / Src / Gui / CPUStack . cpp <nl> CPUStack : : CPUStack ( QWidget * parent ) : HexDump ( parent ) <nl> int charwidth = getCharWidth ( ) ; <nl> ColumnDescriptor_t wColDesc ; <nl> DataDescriptor_t dDesc ; <nl> + bStackFrozen = false ; <nl> <nl> mForceColumn = 1 ; <nl> <nl> CPUStack : : CPUStack ( QWidget * parent ) : HexDump ( parent ) <nl> connect ( Bridge : : getBridge ( ) , SIGNAL ( stackDumpAt ( duint , duint ) ) , this , SLOT ( stackDumpAt ( duint , duint ) ) ) ; <nl> connect ( Bridge : : getBridge ( ) , SIGNAL ( selectionStackGet ( SELECTIONDATA * ) ) , this , SLOT ( selectionGet ( SELECTIONDATA * ) ) ) ; <nl> connect ( Bridge : : getBridge ( ) , SIGNAL ( selectionStackSet ( const SELECTIONDATA * ) ) , this , SLOT ( selectionSet ( const SELECTIONDATA * ) ) ) ; <nl> + connect ( Bridge : : getBridge ( ) , SIGNAL ( dbgStateChanged ( DBGSTATE ) ) , this , SLOT ( dbgStateChangedSlot ( DBGSTATE ) ) ) ; <nl> + <nl> <nl> Initialize ( ) ; <nl> } <nl> void CPUStack : : setupContextMenu ( ) <nl> connect ( mGotoSp , SIGNAL ( triggered ( ) ) , this , SLOT ( gotoSpSlot ( ) ) ) ; <nl> connect ( mGotoBp , SIGNAL ( triggered ( ) ) , this , SLOT ( gotoBpSlot ( ) ) ) ; <nl> <nl> + mFreezeStack = new QAction ( " Freeze stack " , this ) ; <nl> + this - > addAction ( mFreezeStack ) ; <nl> + connect ( mFreezeStack , SIGNAL ( triggered ( ) ) , this , SLOT ( freezeStackSlot ( ) ) ) ; <nl> + <nl> / / Find Pattern <nl> mFindPatternAction = new QAction ( " & Find Pattern . . . " , this ) ; <nl> mFindPatternAction - > setShortcutContext ( Qt : : WidgetShortcut ) ; <nl> void CPUStack : : setupContextMenu ( ) <nl> connect ( Config ( ) , SIGNAL ( shortcutsUpdated ( ) ) , this , SLOT ( refreshShortcutsSlot ( ) ) ) ; <nl> } <nl> <nl> + void CPUStack : : updateFreezeStackAction ( ) <nl> + { <nl> + QFont font = mFreezeStack - > font ( ) ; <nl> + <nl> + if ( bStackFrozen ) <nl> + { <nl> + font . setBold ( true ) ; <nl> + mFreezeStack - > setFont ( font ) ; <nl> + mFreezeStack - > setText ( " Unfreeze the stack " ) ; <nl> + } <nl> + else <nl> + { <nl> + font . setBold ( false ) ; <nl> + mFreezeStack - > setFont ( font ) ; <nl> + mFreezeStack - > setText ( " Freeze the stack " ) ; <nl> + } <nl> + } <nl> + <nl> void CPUStack : : refreshShortcutsSlot ( ) <nl> { <nl> mBinaryEditAction - > setShortcut ( ConfigShortcut ( " ActionBinaryEdit " ) ) ; <nl> QString CPUStack : : paintContent ( QPainter * painter , dsint rowBase , int rowOffset , <nl> dsint wRva = ( rowBase + rowOffset ) * wBytePerRowCount - mByteOffset ; <nl> duint wVa = rvaToVa ( wRva ) ; <nl> <nl> + / / This sets the first visible row to be selected when stack is frozen , so that we can scroll the stack without it being reset to first selection <nl> + if ( bStackFrozen & & rowOffset = = 0 ) <nl> + setSingleSelection ( wRva ) ; <nl> + <nl> bool wIsSelected = isSelected ( wRva ) ; <nl> if ( wIsSelected ) / / highlight if selected <nl> painter - > fillRect ( QRect ( x , y , w , h ) , QBrush ( selectionColor ) ) ; <nl> void CPUStack : : contextMenuEvent ( QContextMenuEvent * event ) <nl> wMenu - > addAction ( mFindPatternAction ) ; <nl> wMenu - > addAction ( mGotoSp ) ; <nl> wMenu - > addAction ( mGotoBp ) ; <nl> + wMenu - > addAction ( mFreezeStack ) ; <nl> wMenu - > addAction ( mGotoExpression ) ; <nl> <nl> duint selectedData ; <nl> void CPUStack : : modifySlot ( ) <nl> mMemPage - > write ( & value , addr , sizeof ( dsint ) ) ; <nl> reloadData ( ) ; <nl> } <nl> + <nl> + void CPUStack : : freezeStackSlot ( ) <nl> + { <nl> + if ( bStackFrozen ) <nl> + DbgCmdExec ( QString ( " setfreezestack 0 " ) . toUtf8 ( ) . constData ( ) ) ; <nl> + else <nl> + DbgCmdExec ( QString ( " setfreezestack 1 " ) . toUtf8 ( ) . constData ( ) ) ; <nl> + <nl> + bStackFrozen = ! bStackFrozen ; <nl> + <nl> + updateFreezeStackAction ( ) ; <nl> + } <nl> + <nl> + void CPUStack : : dbgStateChangedSlot ( DBGSTATE state ) <nl> + { <nl> + if ( state = = initialized ) <nl> + bStackFrozen = false ; <nl> + <nl> + updateFreezeStackAction ( ) ; <nl> + } <nl> mmm a / src / gui / Src / Gui / CPUStack . h <nl> ppp b / src / gui / Src / Gui / CPUStack . h <nl> class CPUStack : public HexDump <nl> void contextMenuEvent ( QContextMenuEvent * event ) ; <nl> void mouseDoubleClickEvent ( QMouseEvent * event ) ; <nl> void setupContextMenu ( ) ; <nl> + void updateFreezeStackAction ( ) ; <nl> <nl> signals : <nl> void displayReferencesWidget ( ) ; <nl> public slots : <nl> void binaryPasteIgnoreSizeSlot ( ) ; <nl> void undoSelectionSlot ( ) ; <nl> void modifySlot ( ) ; <nl> + void freezeStackSlot ( ) ; <nl> + void dbgStateChangedSlot ( DBGSTATE state ) ; <nl> <nl> private : <nl> duint mCsp ; <nl> + bool bStackFrozen ; <nl> <nl> QMenu * mBinaryMenu ; <nl> QAction * mBinaryEditAction ; <nl> public slots : <nl> QAction * mUndoSelection ; <nl> QAction * mGotoSp ; <nl> QAction * mGotoBp ; <nl> + QAction * mFreezeStack ; <nl> QAction * mGotoExpression ; <nl> QAction * mFindPatternAction ; <nl> QAction * mFollowDisasm ; <nl> mmm a / src / gui / Src / Gui / MainWindow . cpp <nl> ppp b / src / gui / Src / Gui / MainWindow . cpp <nl> <nl> # include " AttachDialog . h " <nl> # include " LineEditDialog . h " <nl> <nl> + QString MainWindow : : windowTitle = " " ; <nl> + <nl> MainWindow : : MainWindow ( QWidget * parent ) : QMainWindow ( parent ) , ui ( new Ui : : MainWindow ) <nl> { <nl> ui - > setupUi ( this ) ; <nl> MainWindow : : MainWindow ( QWidget * parent ) : QMainWindow ( parent ) , ui ( new Ui : : MainWi <nl> connect ( ui - > actionChangeCommandLine , SIGNAL ( triggered ( ) ) , this , SLOT ( changeCommandLine ( ) ) ) ; <nl> connect ( ui - > actionManual , SIGNAL ( triggered ( ) ) , this , SLOT ( displayManual ( ) ) ) ; <nl> <nl> + connect ( mCpuWidget - > getDisasmWidget ( ) , SIGNAL ( updateWindowTitle ( QString ) ) , this , SLOT ( updateWindowTitleSlot ( QString ) ) ) ; <nl> connect ( mCpuWidget - > getDisasmWidget ( ) , SIGNAL ( displayReferencesWidget ( ) ) , this , SLOT ( displayReferencesWidget ( ) ) ) ; <nl> connect ( mCpuWidget - > getDisasmWidget ( ) , SIGNAL ( displaySourceManagerWidget ( ) ) , this , SLOT ( displaySourceViewWidget ( ) ) ) ; <nl> connect ( mCpuWidget - > getDisasmWidget ( ) , SIGNAL ( displaySnowmanWidget ( ) ) , this , SLOT ( displaySnowmanWidget ( ) ) ) ; <nl> void MainWindow : : dropEvent ( QDropEvent * pEvent ) <nl> void MainWindow : : updateWindowTitleSlot ( QString filename ) <nl> { <nl> if ( filename . length ( ) ) <nl> + { <nl> setWindowTitle ( QString ( mWindowMainTitle ) + QString ( " - " ) + filename ) ; <nl> + windowTitle = filename ; <nl> + } <nl> else <nl> + { <nl> setWindowTitle ( QString ( mWindowMainTitle ) ) ; <nl> + windowTitle = QString ( mWindowMainTitle ) ; <nl> + } <nl> } <nl> <nl> void MainWindow : : execeStepOver ( ) <nl> mmm a / src / gui / Src / Gui / MainWindow . h <nl> ppp b / src / gui / Src / Gui / MainWindow . h <nl> public slots : <nl> protected : <nl> void dragEnterEvent ( QDragEnterEvent * pEvent ) ; <nl> void dropEvent ( QDropEvent * pEvent ) ; <nl> + <nl> + public : <nl> + static QString windowTitle ; <nl> } ; <nl> <nl> # endif / / MAINWINDOW_H <nl>
DBG / GUI : Added back setfreezestack command to lock the stack with ability to freely scroll in the stack when its frozen without it resetting back to first selection ( hard to explain lol )
x64dbg/x64dbg
c152a420e6051db8395c3d540ae554591b207a96
2015-12-02T14:42:11Z
mmm a / tests / test_import_all . py <nl> ppp b / tests / test_import_all . py <nl> <nl> # flake8 : noqa <nl> - import unittest <nl> import platform <nl> + import unittest <nl> <nl> <nl> - # noinspection PyUnresolvedReferences <nl> - class ImportTest ( unittest . TestCase ) : <nl> + # noinspection PyUnresolvedReferences , PyMethodMayBeStatic <nl> + class CoreImportTest ( unittest . TestCase ) : <nl> <nl> - # noinspection PyUnresolvedReferences <nl> - def test_import_all ( self ) : <nl> + def test_import_event_engine ( self ) : <nl> from vnpy . event import EventEngine <nl> <nl> def test_import_main_engine ( self ) : <nl> def test_import_main_engine ( self ) : <nl> def test_import_ui ( self ) : <nl> from vnpy . trader . ui import MainWindow , create_qapp <nl> <nl> - def test_import_bitmex_gateway ( self ) : <nl> + <nl> + # noinspection PyUnresolvedReferences , PyMethodMayBeStatic <nl> + class GatewayImportTest ( unittest . TestCase ) : <nl> + <nl> + def test_import_binance ( self ) : <nl> + from vnpy . gateway . binance import BinanceGateway <nl> + <nl> + def test_import_bitfinex ( self ) : <nl> + from vnpy . gateway . bitfinex import BitfinexGateway <nl> + <nl> + def test_import_bitmex ( self ) : <nl> from vnpy . gateway . bitmex import BitmexGateway <nl> <nl> - def test_import_futu_gateway ( self ) : <nl> + @ unittest . skipIf ( platform . system ( ) = = " Darwin " , " Not supported yet under osx " ) <nl> + def test_import_ctp ( self ) : <nl> + from vnpy . gateway . ctp import CtpGateway <nl> + <nl> + @ unittest . skipIf ( platform . system ( ) = = " Darwin " , " Not supported yet under osx " ) <nl> + def test_import_ctptest ( self ) : <nl> + from vnpy . gateway . ctptest import CtptestGateway <nl> + <nl> + @ unittest . skipIf ( platform . system ( ) = = " Darwin " , " Not supported yet under osx " ) <nl> + @ unittest . skipIf ( platform . system ( ) = = " Linux " , " Not supported yet under Linux " ) <nl> + def test_import_femas ( self ) : <nl> + from vnpy . gateway . femas import FemasGateway <nl> + <nl> + def test_import_futu ( self ) : <nl> from vnpy . gateway . futu import FutuGateway <nl> <nl> - def test_import_ib_gateway ( self ) : <nl> + def test_import_hbdm ( self ) : <nl> + from vnpy . gateway . hbdm import HbdmGateway <nl> + <nl> + def test_import_huobi ( self ) : <nl> + from vnpy . gateway . huobi import HuobiGateway <nl> + <nl> + def test_import_ib ( self ) : <nl> from vnpy . gateway . ib import IbGateway <nl> <nl> @ unittest . skipIf ( platform . system ( ) = = " Darwin " , " Not supported yet under osx " ) <nl> - def test_import_ctp_gateway ( self ) : <nl> - from vnpy . gateway . ctp import CtpGateway <nl> + def test_import_oes ( self ) : <nl> + from vnpy . gateway . oes import OesGateway <nl> + <nl> + def test_import_okex ( self ) : <nl> + from vnpy . gateway . okex import OkexGateway <nl> + <nl> + def test_import_okexf ( self ) : <nl> + from vnpy . gateway . okexf import OkexfGateway <nl> + <nl> + def test_import_onetoken ( self ) : <nl> + from vnpy . gateway . onetoken import OnetokenGateway <nl> <nl> - def test_import_tiger_gateway ( self ) : <nl> + @ unittest . skipIf ( platform . system ( ) = = " Darwin " , " Not supported yet under osx " ) <nl> + @ unittest . skipIf ( platform . system ( ) = = " Linux " , " Not supported yet under Linux " ) <nl> + def test_import_tap ( self ) : <nl> + from vnpy . gateway . tap import TapGateway <nl> + <nl> + def test_import_tiger ( self ) : <nl> from vnpy . gateway . tiger import TigerGateway <nl> <nl> @ unittest . skipIf ( platform . system ( ) = = " Darwin " , " Not supported yet under osx " ) <nl> - def test_import_oes_gateway ( self ) : <nl> - from vnpy . gateway . oes import OesGateway <nl> + def test_import_tora ( self ) : <nl> + from vnpy . gateway . tora import ToraGateway <nl> + <nl> + def test_import_xtp ( self ) : <nl> + from vnpy . gateway . xtp import XtpGateway <nl> + <nl> + <nl> + # noinspection PyUnresolvedReferences , PyMethodMayBeStatic <nl> + class AppImportTest ( unittest . TestCase ) : <nl> <nl> def test_import_cta_strategy_app ( self ) : <nl> from vnpy . app . cta_strategy import CtaStrategyApp <nl>
[ Add ] added import test for new gateways
vnpy/vnpy
b168bd1e39a63389a16bfa7a584d7f2f57d2e3d2
2019-06-25T08:59:56Z
mmm a / cmake / Modules_CUDA_fix / upstream / FindCUDA / select_compute_arch . cmake <nl> ppp b / cmake / Modules_CUDA_fix / upstream / FindCUDA / select_compute_arch . cmake <nl> if ( CUDA_VERSION VERSION_GREATER " 10 . 5 " ) <nl> list ( APPEND CUDA_ALL_GPU_ARCHITECTURES " 8 . 0 " ) <nl> <nl> if ( CUDA_VERSION VERSION_LESS " 11 . 1 " ) <nl> - set ( CUDA_LIMIT_GPU_ARCHITECTURE " 8 . 6 " ) <nl> + set ( CUDA_LIMIT_GPU_ARCHITECTURE " 8 . 0 " ) <nl> list ( APPEND CUDA_COMMON_GPU_ARCHITECTURES " 8 . 0 + PTX " ) <nl> endif ( ) <nl> endif ( ) <nl> <nl> - if ( CUDA_VERSION VERSION_GREATER " 11 . 0 " ) <nl> + if ( NOT CUDA_VERSION VERSION_LESS " 11 . 1 " ) <nl> list ( APPEND CUDA_COMMON_GPU_ARCHITECTURES " 8 . 6 " " 8 . 6 + PTX " ) <nl> list ( APPEND CUDA_ALL_GPU_ARCHITECTURES " 8 . 6 " ) <nl> + set ( CUDA_LIMIT_GPU_ARCHITECUTRE " 8 . 6 " ) <nl> <nl> if ( CUDA_VERSION VERSION_LESS " 12 . 0 " ) <nl> set ( CUDA_LIMIT_GPU_ARCHITECTURE " 9 . 0 " ) <nl>
[ hot fix ] cuda 11 . 0 . x doesn ' t support sm86 . ( )
pytorch/pytorch
611080a118fff166c85f3200d860f3b059abac6f
2020-11-06T18:34:25Z
mmm a / hphp / hack / src / emitter / emitter . ml <nl> ppp b / hphp / hack / src / emitter / emitter . ml <nl> let emit_fun nenv x = <nl> get_output env <nl> <nl> ( * XXX : * lots * of duplication from emit_fun * ) <nl> - let emit_method_ env m name = <nl> + let emit_method_ env ~ is_static m name = <nl> let env = start_new_function env in <nl> let nb = assert_named_body m . m_body in <nl> <nl> let emit_method_ env m name = <nl> <nl> let options = bool_option " abstract " m . m_abstract @ <nl> bool_option " final " m . m_final @ <nl> + bool_option " static " is_static @ <nl> [ fmt_visibility m . m_visibility ; " mayusevv " ] in <nl> let env = emit_enter env " . method " options name <nl> ( fmt_params m . m_params ) in <nl> let emit_method_ env m name = <nl> let env = run_cleanups env in <nl> let env = emit_exit env in <nl> env <nl> - let emit_method env m = emit_method_ env m ( snd m . m_name ) <nl> + let emit_method env ~ is_static m = emit_method_ ~ is_static env m ( snd m . m_name ) <nl> let emit_default_ctor env name abstract = <nl> let options = bool_option " abstract " abstract @ [ " public " ; " mayusevv " ] in <nl> let env = emit_enter env " . method " options name ( fmt_params [ ] ) in <nl> let fmt_extends_list classes = <nl> let emit_use env use = <nl> emit_strs env [ " . use " ; fmt_class_hint use ^ " ; " ] <nl> <nl> - let emit_pinit env = function <nl> + let emit_prop_init env ~ is_static = function <nl> | [ ] - > env <nl> | vars - > <nl> - let options = [ " public " ; " private " ; " mayusevv " ] in <nl> - let env = emit_enter env " . method " options " 86pinit " ( fmt_params [ ] ) in <nl> + let name , flag , extra_opts = <nl> + if is_static then <nl> + " 86sinit " , " Static " , [ " static " ] <nl> + else <nl> + " 86pinit " , " NonStatic " , [ ] <nl> + in <nl> + <nl> + let options = [ " private " ; " mayusevv " ] @ extra_opts in <nl> + let env = emit_enter env " . method " options name ( fmt_params [ ] ) in <nl> <nl> let fmt_var_init env ( name , expr ) = <nl> let env , skip_label = fresh_label env in <nl> let env = emit_CheckProp env name in <nl> let env = emit_cjmp env true skip_label in <nl> let env = Emitter_expr . emit_expr env expr in <nl> - let env = emit_InitProp env name " NonStatic " in <nl> + let env = emit_InitProp env name flag in <nl> emit_label env skip_label <nl> in <nl> let env = List . fold_left fmt_var_init env vars in <nl> let emit_pinit env = function <nl> <nl> ( * Returns None if the case has been handled , and Some ( name , expr ) if <nl> * it still needs to be taken care of in a pinit * ) <nl> - let emit_var env var = <nl> + let emit_var env ~ is_static var = <nl> assert ( var . cv_final = false ) ; ( * props can ' t be final * ) <nl> assert ( var . cv_is_xhp = false ) ; <nl> - let options = fmt_options [ fmt_visibility var . cv_visibility ] in <nl> + let options = bool_option " static " is_static @ <nl> + [ fmt_visibility var . cv_visibility ] in <nl> let fmt_prop v = <nl> - emit_strs env [ " . property " ; options ; snd var . cv_id ; " = " ; v ^ " ; " ] in <nl> + emit_strs env <nl> + [ " . property " ; fmt_options options ; snd var . cv_id ; " = " ; v ^ " ; " ] in <nl> match var . cv_expr with <nl> | None - > fmt_prop " \ " \ " \ " N ; \ " \ " \ " " , None <nl> | Some expr - > <nl> let emit_class nenv x = <nl> cls . c_xhp_attr_uses = [ ] & & <nl> cls . c_consts = [ ] & & <nl> cls . c_typeconsts = [ ] & & <nl> - cls . c_static_vars = [ ] & & <nl> - cls . c_static_methods = [ ] & & <nl> cls . c_user_attributes = [ ] & & <nl> cls . c_enum = None ) ; <nl> <nl> let emit_class nenv x = <nl> let extends_list = fmt_extends_list extends in <nl> let implements_list = fmt_implements_list implements in <nl> <nl> - let env = emit_enter env " . class " options ( strip_ns x ) <nl> + let name = strip_ns x in <nl> + let self_name , parent_name = match cls . c_kind with <nl> + ( * interfaces don ' t have code so we don ' t need the names ; <nl> + * traits can make self and parent calls to things that are actually <nl> + * in a class that uses them , so we don ' t use the name * ) <nl> + | Ast . Cinterface | Ast . Ctrait - > None , None <nl> + | Ast . Cabstract | Ast . Cnormal | Ast . Cenum - > <nl> + Some name , <nl> + match cls . c_extends with <nl> + | [ ] - > None <nl> + | [ x ] - > Some ( fmt_class_hint x ) <nl> + | _ - > assert false in <nl> + let env = { env with self_name ; parent_name } in <nl> + <nl> + let env = emit_enter env " . class " options name <nl> ( extends_list ^ implements_list ) in <nl> <nl> <nl> let env = List . fold_left emit_use env cls . c_uses in <nl> - let env , uninit_vars = lmap emit_var env cls . c_vars in <nl> + let env , uninit_vars = lmap ( emit_var ~ is_static : false ) env cls . c_vars in <nl> + let env , uninit_svars = <nl> + lmap ( emit_var ~ is_static : true ) env cls . c_static_vars in <nl> + let env = List . fold_left ( emit_method ~ is_static : false ) env cls . c_methods in <nl> + let env = <nl> + List . fold_left ( emit_method ~ is_static : true ) env cls . c_static_methods in <nl> + <nl> let uninit_vars = Core_list . filter_map uninit_vars ~ f : ( fun x - > x ) in <nl> - let env = List . fold_left emit_method env cls . c_methods in <nl> + let uninit_svars = Core_list . filter_map uninit_svars ~ f : ( fun x - > x ) in <nl> <nl> ( * Now for 86 * stuff * ) <nl> let env = match cls . c_constructor with <nl> | None - > emit_default_ctor env " 86ctor " <nl> ( cls . c_kind = Ast . Cinterface ) <nl> - | Some m - > emit_method_ env m " 86ctor " in <nl> + | Some m - > emit_method_ ~ is_static : false env m " 86ctor " in <nl> <nl> - let env = emit_pinit env uninit_vars in <nl> + let env = emit_prop_init env ~ is_static : false uninit_vars in <nl> + let env = emit_prop_init env ~ is_static : true uninit_svars in <nl> <nl> let env = emit_exit env in <nl> <nl> mmm a / hphp / hack / src / emitter / emitter_core . ml <nl> ppp b / hphp / hack / src / emitter / emitter_core . ml <nl> type lval = <nl> ( * Indexing and projection operations * ) <nl> ( * This list is stored reversed because ~ functional programming ~ * ) <nl> | Lmember of base * ( member_type * member ) list <nl> - ( * XXX : static props ( hack strict doesn ' t support globals , I think ) * ) <nl> + | Lsprop of Nast . class_id <nl> and base = <nl> | Blval of lval <nl> | Bexpr <nl> let fmt_base base = <nl> | Bexpr - > " C " <nl> | Bthis - > " H " <nl> | Blval ( Llocal id ) - > " L : " ^ get_lid_name id <nl> + | Blval ( Lsprop _ ) - > " SC " <nl> | Blval ( Lmember _ ) - > bug " invalid base " ; assert false <nl> <nl> ( * returns the suffix to use on opcodes operating on the lval , <nl> let fmt_base base = <nl> let fmt_lval lval = <nl> match lval with <nl> | Llocal id - > " L " , get_lid_name id , false <nl> + | Lsprop _ - > " S " , " " , false <nl> | Lmember ( base , mems ) - > <nl> " M " , <nl> " < " ^ fmt_base base ^ " " ^ <nl> and env = { <nl> next_iterator : int ; ( * iterators allocated in a stack discipline * ) <nl> nonlocal : nonlocal_actions ; <nl> cleanups : ( env - > env ) list ; <nl> + self_name : string option ; <nl> + parent_name : string option ; <nl> } <nl> <nl> let empty_nonlocal_actions = { <nl> let new_env ( ) = { <nl> next_iterator = 0 ; <nl> nonlocal = empty_nonlocal_actions ; <nl> cleanups = [ ] ; <nl> + self_name = None ; <nl> + parent_name = None ; <nl> } <nl> <nl> let start_new_function env = <nl> let nenv = new_env ( ) in <nl> { nenv with <nl> reversed_output = env . reversed_output ; <nl> - indent = env . indent <nl> + indent = env . indent ; <nl> + self_name = env . self_name ; <nl> + parent_name = env . parent_name ; <nl> } <nl> <nl> let fresh_id pre env = <nl> let emit_op2es s env arg1 arg2 = <nl> emit_op_strs env [ s ; quote_str arg1 ; arg2 ] <nl> let emit_op3ies s env arg1 arg2 arg3 = <nl> emit_op_strs env [ s ; string_of_int arg1 ; quote_str arg2 ; arg3 ] <nl> + let emit_op3iee s env arg1 arg2 arg3 = <nl> + emit_op_strs env [ s ; string_of_int arg1 ; quote_str arg2 ; quote_str arg3 ] <nl> let emit_op1l s env arg1 = <nl> let t , a , _ = fmt_lval arg1 in <nl> emit_op_strs env [ s ^ t ; a ] <nl> let emit_FPushFunc = emit_op1i " FPushFunc " <nl> let emit_FPushFuncD = emit_op2ie " FPushFuncD " <nl> let emit_FPushCtorD = emit_op2ie " FPushCtorD " <nl> let emit_FPushObjMethodD = emit_op3ies " FPushObjMethodD " <nl> + let emit_FPushClsMethod = emit_op1i " FPushClsMethod " <nl> + let emit_FPushClsMethodD = emit_op3iee " FPushClsMethodD " <nl> let emit_FPassLval = emit_op2il " FPass " <nl> let emit_FCall = emit_op1i " FCall " <nl> let emit_FCallUnpack = emit_op1i " FCallUnpack " <nl> let emit_IterNext = emit_op3iter " IterNext " <nl> let emit_IterFree = emit_op1i " IterFree " <nl> let emit_CheckProp = emit_op1e " CheckProp " <nl> let emit_InitProp = emit_op2es " InitProp " <nl> + let emit_LateBoundCls = emit_op0 " LateBoundCls " <nl> + let emit_Self = emit_op0 " Self " <nl> + let emit_Parent = emit_op0 " Parent " <nl> + let emit_AGetL = emit_op1s " AGetL " <nl> + let emit_AGetC = emit_op0 " AGetC " <nl> <nl> let emit_Switch env labels base bound = <nl> emit_op_strs env [ " Switch " ; fmt_str_vec labels ; string_of_int base ; bound ] <nl> mmm a / hphp / hack / src / emitter / emitter_expr . ml <nl> ppp b / hphp / hack / src / emitter / emitter_expr . ml <nl> open Emitter_core <nl> let is_lval expr = <nl> match expr with <nl> ( * XXX : other lvals ! * ) <nl> - | Lvar _ | Obj_get _ | Array_get _ - > true <nl> + | Lvar _ | Obj_get _ | Array_get _ | Class_get _ - > true <nl> | _ - > false <nl> <nl> + ( * Try to convert a class id into a static string ; if we can ' t , return None * ) <nl> + let fmt_class_id env cid = <nl> + match cid with <nl> + | CIparent - > env . parent_name <nl> + | CIself - > env . self_name <nl> + | CI ( _ , s ) - > Some ( strip_ns s ) <nl> + | CIstatic | CIvar _ - > None <nl> + <nl> ( * Emit a conditional branch based on an expression . jump_if indicates <nl> * whether to jump when the condition is true or false . <nl> * This is its own thing so that we can efficiently handle ! / & & / | | <nl> and emit_base env ( _ , expr_ as expr ) = <nl> match expr_ with <nl> | This - > env , Bthis <nl> | _ when is_lval expr_ - > <nl> - let env , lval = emit_lval env expr in <nl> + let env , lval = emit_lval_inner env expr in <nl> env , Blval lval <nl> | _ - > <nl> let env = emit_expr env expr in <nl> env , Bexpr <nl> <nl> - ( * emit code for an lval that we may be either reading or writing from <nl> - * and return a descriptor for the lval . <nl> - * May push values on the stack that will be consumed when the lval <nl> - * is accessed . * ) <nl> - and emit_lval env ( _ , expr_ ) = <nl> + ( * This is the main guts of lval emitting . It does all the work of <nl> + * eval emitting except for emitting the class id when operating <nl> + * on a static property . This is because for member instructions on <nl> + * static props , the class id needs to come * last * on the stack , <nl> + * after everything else . ( Argh . ) So we save it and emit it <nl> + * at the " top level " of lval emitting . * ) <nl> + and emit_lval_inner env ( _ , expr_ ) = <nl> match expr_ with <nl> | Lvar id - > env , Llocal id <nl> | Array_get ( e1 , maybe_e2 ) - > <nl> and emit_lval env ( _ , expr_ ) = <nl> | Obj_get ( e1 , ( _ , Id ( _ , id ) ) , _null_flavor_TODO ) - > <nl> let env , base = emit_base env e1 in <nl> env , lmember ( base , ( MTprop , Mstring id ) ) <nl> - <nl> | Obj_get _ - > unimpl " Obj_get with non - Id rhs ? ? ? " ; assert false <nl> <nl> + | Class_get ( cid , ( _ , field ) ) - > <nl> + let field_name = lstrip field " $ " in <nl> + let env = emit_String env field_name in <nl> + env , Lsprop cid <nl> + <nl> | _ - > bug " emit_lval : not an lvalue " ; assert false <nl> <nl> + ( * emit code for an lval that we may be either reading or writing from <nl> + * and return a descriptor for the lval . <nl> + * May push values on the stack that will be consumed when the lval <nl> + * is accessed . * ) <nl> + and emit_lval env expr = <nl> + let env , lval = emit_lval_inner env expr in <nl> + ( * If we are operating on a static prop , emit the class id now , <nl> + * which needs to come last . . . * ) <nl> + let env = match lval with <nl> + | Lsprop cid <nl> + | Lmember ( Blval ( Lsprop cid ) , _ ) - > <nl> + emit_class_id env cid <nl> + | _ - > env <nl> + in <nl> + env , lval <nl> + <nl> + <nl> + and emit_class_id env cid = <nl> + ( * if we have a static name for the class , use that * ) <nl> + match fmt_class_id env cid with <nl> + | Some s - > <nl> + let env = emit_String env s in <nl> + emit_AGetC env <nl> + ( * otherwise we need to dynamically find the class * ) <nl> + | None - > <nl> + match cid with <nl> + | CI _ - > assert false <nl> + | CIparent - > emit_Parent env <nl> + | CIself - > emit_Self env <nl> + | CIstatic - > emit_LateBoundCls env <nl> + | CIvar ( _ , Lvar id ) - > emit_AGetL env ( get_lid_name id ) <nl> + | CIvar e - > <nl> + let env = emit_expr env e in <nl> + emit_AGetC env <nl> + <nl> and emit_call_lhs env ( _ , expr_ as expr ) nargs = <nl> match expr_ with <nl> | Id ( _ , name ) <nl> and emit_call_lhs env ( _ , expr_ as expr ) nargs = <nl> | Obj_get ( obj , ( _ , Id ( _ , name ) ) , null_flavor ) - > <nl> let env = emit_method_base env obj in <nl> emit_FPushObjMethodD env nargs name ( fmt_null_flavor null_flavor ) <nl> + | Class_const ( cid , ( _ , field ) ) - > <nl> + ( match fmt_class_id env cid with <nl> + | Some class_name - > emit_FPushClsMethodD env nargs field class_name <nl> + | None - > let env = emit_String env field in <nl> + let env = emit_class_id env cid in <nl> + emit_FPushClsMethod env nargs ) <nl> + <nl> ( * what all is even allowed here ? * ) <nl> | _ - > <nl> let env = emit_expr env expr in <nl> and emit_expr env ( _ , expr_ as expr ) = <nl> ( * N . B : duplicate with is_lval but we want to exhaustiveness check * ) <nl> | Lvar _ <nl> | Obj_get _ <nl> - | Array_get _ - > <nl> + | Array_get _ <nl> + | Class_get _ - > <nl> let env , lval = emit_lval env expr in <nl> emit_CGet env lval <nl> <nl> and emit_expr env ( _ , expr_ as expr ) = <nl> | Method_id _ <nl> | Method_caller _ <nl> | Smethod_id _ <nl> - | Class_get _ <nl> | Class_const _ <nl> | Special_func _ <nl> | Yield_break <nl> new file mode 100644 <nl> index 00000000000 . . 7ecb7471bd5 <nl> mmm / dev / null <nl> ppp b / hphp / hack / test / emitter / static_props . php <nl> <nl> + < ? hh / / strict <nl> + <nl> + class A { <nl> + public static int $ parent_prop = 100 ; <nl> + <nl> + public static function static_fn ( ) : void { <nl> + echo " hi from parent \ n " ; <nl> + } <nl> + <nl> + public static function call_static ( ) : void { <nl> + self : : static_fn ( ) ; <nl> + } <nl> + public static function call_static_statically ( ) : void { <nl> + static : : static_fn ( ) ; <nl> + } <nl> + } <nl> + <nl> + class B extends A { } <nl> + <nl> + trait T { <nl> + require extends A ; <nl> + public static function trait_fn2 ( ) : void { <nl> + self : : call_static ( ) ; <nl> + parent : : call_static ( ) ; <nl> + } <nl> + public static function trait_fn ( ) : void { <nl> + self : : trait_fn2 ( ) ; <nl> + } <nl> + } <nl> + <nl> + class C extends B { <nl> + use T ; <nl> + <nl> + public static int $ static_prop = 100 ; <nl> + <nl> + public static array < int > $ array_prop = array ( ) ; <nl> + <nl> + public function get_self_prop ( ) : int { <nl> + return self : : $ static_prop ; <nl> + } <nl> + public function get_static_prop ( ) : int { <nl> + return static : : $ static_prop ; <nl> + } <nl> + public function get_parent_prop ( ) : int { <nl> + return parent : : $ parent_prop ; <nl> + } <nl> + public function get_this_prop ( ) : int { <nl> + return $ this : : $ static_prop ; <nl> + } <nl> + <nl> + public static function static_fn ( ) : void { <nl> + echo " hi from child \ n " ; <nl> + } <nl> + } <nl> + <nl> + function test ( ) : void { <nl> + $ x = C : : $ static_prop ; <nl> + var_dump ( $ x ) ; <nl> + C : : $ static_prop = 59 ; <nl> + C : : $ static_prop + + ; <nl> + var_dump ( C : : $ static_prop ) ; <nl> + <nl> + C : : $ array_prop [ 0 ] = 8 ; <nl> + C : : $ array_prop [ 1 ] = 3 ; <nl> + C : : $ array_prop [ 2 ] = 10 ; <nl> + C : : $ array_prop [ 2 ] + = ( + + C : : $ array_prop [ 0 ] ) * C : : $ array_prop [ 1 ] ; <nl> + <nl> + var_dump ( C : : $ array_prop [ 2 ] ) ; <nl> + var_dump ( C : : $ array_prop ) ; <nl> + <nl> + $ n = 0 ; <nl> + C : : $ array_prop [ $ n + 1 ] ; <nl> + C : : $ array_prop [ $ n + 1 ] = 10 ; <nl> + <nl> + var_dump ( C : : $ array_prop ) ; <nl> + <nl> + $ c = new C ( ) ; <nl> + var_dump ( $ c - > get_self_prop ( ) ) ; <nl> + var_dump ( $ c - > get_parent_prop ( ) ) ; <nl> + var_dump ( $ c - > get_static_prop ( ) ) ; <nl> + var_dump ( $ c - > get_this_prop ( ) ) ; <nl> + $ c : : static_fn ( ) ; <nl> + <nl> + C : : static_fn ( ) ; <nl> + C : : call_static ( ) ; <nl> + C : : call_static_statically ( ) ; <nl> + A : : call_static_statically ( ) ; <nl> + C : : trait_fn ( ) ; <nl> + } <nl>
Add support for static props and methods to experimental emitter
facebook/hhvm
d9607452a6b1fdb8668827bfdf8bfbf117abe180
2015-07-23T19:32:32Z
mmm a / tensorflow / contrib / learn / BUILD <nl> ppp b / tensorflow / contrib / learn / BUILD <nl> py_test ( <nl> ] , <nl> ) <nl> <nl> - py_test ( <nl> - name = " dnn_linear_combined_benchmark_test " , <nl> - size = " medium " , <nl> - srcs = [ " python / learn / estimators / dnn_linear_combined_benchmark_test . py " ] , <nl> - srcs_version = " PY2AND3 " , <nl> - tags = [ <nl> - " guitar " , <nl> - " local " , <nl> - " manual " , <nl> - " notap " , <nl> - ] , <nl> - visibility = [ <nl> - " / / learning / brain / google / guitar : __subpackages__ " , <nl> - " / / tensorflow : __subpackages__ " , <nl> - ] , <nl> - deps = [ <nl> - " : learn " , <nl> - " / / tensorflow / contrib / layers : layers_py " , <nl> - " / / tensorflow / contrib / learn / python / learn / datasets " , <nl> - " / / tensorflow / python : array_ops " , <nl> - " / / tensorflow / python : client_testlib " , <nl> - " / / tensorflow / python : framework_for_generated_wrappers " , <nl> - " / / tensorflow / python : sparse_tensor " , <nl> - " / / tensorflow / python : training " , <nl> - ] , <nl> - ) <nl> - <nl> py_test ( <nl> name = " kmeans_test " , <nl> size = " medium " , <nl> py_test ( <nl> ] , <nl> ) <nl> <nl> - py_test ( <nl> - name = " dnn_benchmark_test " , <nl> - size = " medium " , <nl> - srcs = [ " python / learn / estimators / dnn_benchmark_test . py " ] , <nl> - srcs_version = " PY2AND3 " , <nl> - tags = [ <nl> - " guitar " , <nl> - " local " , <nl> - " manual " , <nl> - " notap " , <nl> - ] , <nl> - visibility = [ <nl> - " / / learning / brain / google / guitar : __subpackages__ " , <nl> - " / / tensorflow : __subpackages__ " , <nl> - ] , <nl> - deps = [ <nl> - " : learn " , <nl> - " / / tensorflow / contrib / layers : layers_py " , <nl> - " / / tensorflow / python : client_testlib " , <nl> - " / / tensorflow / python : framework_for_generated_wrappers " , <nl> - " / / tensorflow / python : sparse_tensor " , <nl> - " / / tensorflow / python : training " , <nl> - " / / third_party / py / numpy " , <nl> - ] , <nl> - ) <nl> - <nl> py_test ( <nl> name = " dynamic_rnn_estimator_test " , <nl> size = " medium " , <nl> deleted file mode 100644 <nl> index 86b3eee6ad140 . . 0000000000000 <nl> mmm a / tensorflow / contrib / learn / python / learn / estimators / dnn_benchmark_test . py <nl> ppp / dev / null <nl> <nl> - # Copyright 2016 The TensorFlow Authors . All Rights Reserved . <nl> - # <nl> - # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - # you may not use this file except in compliance with the License . <nl> - # You may obtain a copy of the License at <nl> - # <nl> - # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - # <nl> - # Unless required by applicable law or agreed to in writing , software <nl> - # distributed under the License is distributed on an " AS IS " BASIS , <nl> - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - # See the License for the specific language governing permissions and <nl> - # limitations under the License . <nl> - # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - " " " Regression test for DNNEstimator . " " " <nl> - <nl> - from __future__ import absolute_import <nl> - from __future__ import division <nl> - from __future__ import print_function <nl> - <nl> - import functools <nl> - import numpy as np <nl> - from tensorflow . contrib . layers . python . layers import feature_column <nl> - from tensorflow . contrib . learn . python . learn . estimators import dnn <nl> - from tensorflow . contrib . learn . python . learn . estimators import estimator_test_utils <nl> - from tensorflow . contrib . learn . python . learn . estimators import run_config <nl> - from tensorflow . contrib . learn . python . learn . estimators import test_data <nl> - from tensorflow . python . framework import constant_op <nl> - from tensorflow . python . framework import dtypes <nl> - from tensorflow . python . framework import sparse_tensor <nl> - from tensorflow . python . platform import test <nl> - from tensorflow . python . training import input as input_lib <nl> - <nl> - <nl> - _METRIC_KEYS = { <nl> - ' accuracy ' , <nl> - ' auc ' , <nl> - ' accuracy / threshold_0 . 500000_mean ' , <nl> - ' loss ' , <nl> - ' precision / positive_threshold_0 . 500000_mean ' , <nl> - ' recall / positive_threshold_0 . 500000_mean ' , <nl> - } <nl> - <nl> - <nl> - class DNNClassifierBenchmark ( test . Benchmark ) : <nl> - <nl> - def _report_metrics ( self , metrics ) : <nl> - self . report_benchmark ( <nl> - iters = metrics [ ' global_step ' ] , <nl> - extras = { k : v <nl> - for k , v in metrics . items ( ) if k in _METRIC_KEYS } ) <nl> - <nl> - def _report_predictions ( self , <nl> - benchmark_name_override , <nl> - classifier , <nl> - input_fn , <nl> - iters , <nl> - n_examples , <nl> - n_classes , <nl> - expected_probabilities = None , <nl> - expected_classes = None ) : <nl> - probabilities = classifier . predict_proba ( <nl> - input_fn = input_fn , as_iterable = False ) <nl> - if expected_probabilities is not None : <nl> - np . testing . assert_allclose ( <nl> - expected_probabilities , tuple ( probabilities ) , atol = 0 . 2 ) <nl> - <nl> - classes = classifier . predict ( input_fn = input_fn , as_iterable = False ) <nl> - if expected_classes is not None : <nl> - np . testing . assert_array_equal ( expected_classes , classes ) <nl> - <nl> - self . report_benchmark ( <nl> - iters = iters , <nl> - extras = { <nl> - ' inference . example % d_class % d_prob ' % ( i , j ) : probabilities [ i ] [ j ] <nl> - for j in range ( n_classes ) for i in range ( n_examples ) <nl> - } . update ( { <nl> - ' inference . example % d_class ' % i : classes [ i ] <nl> - for i in range ( n_examples ) <nl> - } ) , <nl> - name = benchmark_name_override ) <nl> - <nl> - def benchmarkLogisticMatrixData ( self ) : <nl> - classifier = dnn . DNNClassifier ( <nl> - feature_columns = ( feature_column . real_valued_column ( <nl> - ' feature ' , dimension = 4 ) , ) , <nl> - hidden_units = ( 3 , 3 ) , <nl> - config = run_config . RunConfig ( tf_random_seed = 1 ) ) <nl> - input_fn = test_data . iris_input_logistic_fn <nl> - steps = 400 <nl> - metrics = classifier . fit ( input_fn = input_fn , steps = steps ) . evaluate ( <nl> - input_fn = input_fn , steps = 1 ) <nl> - estimator_test_utils . assert_in_range ( steps , steps + 5 , ' global_step ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , ' accuracy ' , metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 0 , 0 . 3 , ' loss ' , metrics ) <nl> - <nl> - self . _report_metrics ( metrics ) <nl> - <nl> - def benchmarkLogisticMatrixDataLabels1D ( self ) : <nl> - <nl> - def _input_fn ( ) : <nl> - iris = test_data . prepare_iris_data_for_logistic_regression ( ) <nl> - return { <nl> - ' feature ' : constant_op . constant ( <nl> - iris . data , dtype = dtypes . float32 ) <nl> - } , constant_op . constant ( <nl> - iris . target , shape = ( 100 , ) , dtype = dtypes . int32 ) <nl> - <nl> - classifier = dnn . DNNClassifier ( <nl> - feature_columns = ( feature_column . real_valued_column ( <nl> - ' feature ' , dimension = 4 ) , ) , <nl> - hidden_units = ( 3 , 3 ) , <nl> - config = run_config . RunConfig ( tf_random_seed = 1 ) ) <nl> - steps = 1000 <nl> - metrics = classifier . fit ( input_fn = _input_fn , steps = steps ) . evaluate ( <nl> - input_fn = _input_fn , steps = 1 ) <nl> - estimator_test_utils . assert_in_range ( steps , steps + 5 , ' global_step ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , ' accuracy ' , metrics ) <nl> - <nl> - self . _report_metrics ( metrics ) <nl> - <nl> - def benchmarkLogisticNpMatrixData ( self ) : <nl> - classifier = dnn . DNNClassifier ( <nl> - feature_columns = ( feature_column . real_valued_column ( <nl> - ' ' , dimension = 4 ) , ) , <nl> - hidden_units = ( 3 , 3 ) , <nl> - config = run_config . RunConfig ( tf_random_seed = 1 ) ) <nl> - iris = test_data . prepare_iris_data_for_logistic_regression ( ) <nl> - train_x = iris . data <nl> - train_y = iris . target <nl> - steps = 100 <nl> - metrics = classifier . fit ( x = train_x , y = train_y , steps = steps ) . evaluate ( <nl> - x = train_x , y = train_y , steps = 1 ) <nl> - estimator_test_utils . assert_in_range ( steps , steps + 5 , ' global_step ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 8 , 1 . 0 , ' accuracy ' , metrics ) <nl> - <nl> - self . _report_metrics ( metrics ) <nl> - <nl> - def benchmarkLogisticTensorData ( self ) : <nl> - <nl> - def _input_fn ( num_epochs = None ) : <nl> - features = { <nl> - ' age ' : <nl> - input_lib . limit_epochs ( <nl> - constant_op . constant ( ( ( . 8 , ) , ( 0 . 2 , ) , ( . 1 , ) ) ) , <nl> - num_epochs = num_epochs ) , <nl> - ' language ' : <nl> - sparse_tensor . SparseTensor ( <nl> - values = input_lib . limit_epochs ( <nl> - ( ' en ' , ' fr ' , ' zh ' ) , num_epochs = num_epochs ) , <nl> - indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 2 , 0 ) ) , <nl> - dense_shape = ( 3 , 2 ) ) <nl> - } <nl> - return features , constant_op . constant ( <nl> - ( ( 1 , ) , ( 0 , ) , ( 0 , ) ) , dtype = dtypes . int32 ) <nl> - <nl> - lang_column = feature_column . sparse_column_with_hash_bucket ( <nl> - ' language ' , hash_bucket_size = 20 ) <nl> - classifier = dnn . DNNClassifier ( <nl> - feature_columns = ( feature_column . embedding_column ( <nl> - lang_column , dimension = 1 ) , <nl> - feature_column . real_valued_column ( ' age ' ) ) , <nl> - hidden_units = ( 3 , 3 ) , <nl> - config = run_config . RunConfig ( tf_random_seed = 1 ) ) <nl> - steps = 100 <nl> - metrics = classifier . fit ( input_fn = _input_fn , steps = steps ) . evaluate ( <nl> - input_fn = _input_fn , steps = 1 ) <nl> - estimator_test_utils . assert_in_range ( steps , steps + 5 , ' global_step ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , ' accuracy ' , metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 0 , 0 . 3 , ' loss ' , metrics ) <nl> - <nl> - self . _report_metrics ( metrics ) <nl> - self . _report_predictions ( <nl> - classifier = classifier , <nl> - input_fn = functools . partial ( _input_fn , num_epochs = 1 ) , <nl> - iters = metrics [ ' global_step ' ] , <nl> - n_examples = 3 , <nl> - n_classes = 2 , <nl> - expected_classes = ( 1 , 0 , 0 ) , <nl> - benchmark_name_override = ( <nl> - ' DNNClassifierBenchmark . benchmarkLogisticTensorData_predictions ' ) ) <nl> - <nl> - def benchmarkLogisticFloatLabel ( self ) : <nl> - <nl> - def _input_fn ( num_epochs = None ) : <nl> - features = { <nl> - ' age ' : <nl> - input_lib . limit_epochs ( <nl> - constant_op . constant ( ( ( 50 , ) , ( 20 , ) , ( 10 , ) ) ) , <nl> - num_epochs = num_epochs ) , <nl> - ' language ' : <nl> - sparse_tensor . SparseTensor ( <nl> - values = input_lib . limit_epochs ( <nl> - ( ' en ' , ' fr ' , ' zh ' ) , num_epochs = num_epochs ) , <nl> - indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 2 , 0 ) ) , <nl> - dense_shape = ( 3 , 2 ) ) <nl> - } <nl> - return features , constant_op . constant ( <nl> - ( ( 0 . 8 , ) , ( 0 . , ) , ( 0 . 2 , ) ) , dtype = dtypes . float32 ) <nl> - <nl> - lang_column = feature_column . sparse_column_with_hash_bucket ( <nl> - ' language ' , hash_bucket_size = 20 ) <nl> - n_classes = 2 <nl> - classifier = dnn . DNNClassifier ( <nl> - n_classes = n_classes , <nl> - feature_columns = ( feature_column . embedding_column ( <nl> - lang_column , dimension = 1 ) , <nl> - feature_column . real_valued_column ( ' age ' ) ) , <nl> - hidden_units = ( 3 , 3 ) , <nl> - config = run_config . RunConfig ( tf_random_seed = 1 ) ) <nl> - steps = 1000 <nl> - metrics = classifier . fit ( input_fn = _input_fn , steps = steps ) . evaluate ( <nl> - input_fn = _input_fn , steps = 1 ) <nl> - estimator_test_utils . assert_in_range ( steps , steps + 5 , ' global_step ' , <nl> - metrics ) <nl> - <nl> - # Prediction probabilities mirror the labels column , which proves that the <nl> - # classifier learns from float input . <nl> - self . _report_metrics ( metrics ) <nl> - self . _report_predictions ( <nl> - classifier = classifier , <nl> - input_fn = functools . partial ( _input_fn , num_epochs = 1 ) , <nl> - iters = metrics [ ' global_step ' ] , <nl> - n_examples = 3 , <nl> - n_classes = n_classes , <nl> - expected_probabilities = ( ( 0 . 2 , 0 . 8 ) , ( 1 . , 0 . ) , ( 0 . 8 , 0 . 2 ) ) , <nl> - expected_classes = ( 1 , 0 , 0 ) , <nl> - benchmark_name_override = ( <nl> - ' DNNClassifierBenchmark . benchmarkLogisticFloatLabel_predictions ' ) ) <nl> - <nl> - def benchmarkMultiClassMatrixData ( self ) : <nl> - " " " Tests multi - class classification using matrix data as input . " " " <nl> - classifier = dnn . DNNClassifier ( <nl> - n_classes = 3 , <nl> - feature_columns = ( feature_column . real_valued_column ( <nl> - ' feature ' , dimension = 4 ) , ) , <nl> - hidden_units = ( 3 , 3 ) , <nl> - config = run_config . RunConfig ( tf_random_seed = 1 ) ) <nl> - <nl> - input_fn = test_data . iris_input_multiclass_fn <nl> - steps = 500 <nl> - metrics = classifier . fit ( input_fn = input_fn , steps = steps ) . evaluate ( <nl> - input_fn = input_fn , steps = 1 ) <nl> - estimator_test_utils . assert_in_range ( steps , steps + 5 , ' global_step ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , ' accuracy ' , metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 0 , 0 . 4 , ' loss ' , metrics ) <nl> - <nl> - self . _report_metrics ( metrics ) <nl> - <nl> - <nl> - if __name__ = = ' __main__ ' : <nl> - test . main ( ) <nl> deleted file mode 100644 <nl> index 98b7c7e95c59a . . 0000000000000 <nl> mmm a / tensorflow / contrib / learn / python / learn / estimators / dnn_linear_combined_benchmark_test . py <nl> ppp / dev / null <nl> <nl> - # Copyright 2016 The TensorFlow Authors . All Rights Reserved . <nl> - # <nl> - # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> - # you may not use this file except in compliance with the License . <nl> - # You may obtain a copy of the License at <nl> - # <nl> - # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> - # <nl> - # Unless required by applicable law or agreed to in writing , software <nl> - # distributed under the License is distributed on an " AS IS " BASIS , <nl> - # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> - # See the License for the specific language governing permissions and <nl> - # limitations under the License . <nl> - # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = <nl> - " " " Regression test for DNNLinearCombinedEstimator . " " " <nl> - <nl> - from __future__ import absolute_import <nl> - from __future__ import division <nl> - from __future__ import print_function <nl> - <nl> - import json <nl> - import tempfile <nl> - from tensorflow . contrib . layers . python . layers import feature_column <nl> - from tensorflow . contrib . learn . python . learn . datasets import base <nl> - from tensorflow . contrib . learn . python . learn . estimators import dnn_linear_combined <nl> - from tensorflow . contrib . learn . python . learn . estimators import estimator_test_utils <nl> - from tensorflow . contrib . learn . python . learn . estimators import run_config <nl> - from tensorflow . contrib . learn . python . learn . estimators import test_data <nl> - from tensorflow . python . framework import constant_op <nl> - from tensorflow . python . framework import dtypes <nl> - from tensorflow . python . framework import sparse_tensor <nl> - from tensorflow . python . ops import array_ops <nl> - from tensorflow . python . platform import test <nl> - from tensorflow . python . training import adagrad <nl> - from tensorflow . python . training import ftrl <nl> - from tensorflow . python . training import server_lib <nl> - <nl> - <nl> - # Desired training steps , reported in benchmark . Actual steps might be slightly <nl> - # more than this since supervisor training runs for a non - detrministic number of <nl> - # steps . <nl> - _ITERS = 100 <nl> - <nl> - _METRIC_KEYS = { <nl> - ' accuracy ' , <nl> - ' auc ' , <nl> - ' accuracy / threshold_0 . 500000_mean ' , <nl> - ' loss ' , <nl> - ' precision / positive_threshold_0 . 500000_mean ' , <nl> - ' recall / positive_threshold_0 . 500000_mean ' , <nl> - } <nl> - <nl> - <nl> - class DNNLinearCombinedClassifierBenchmark ( test . Benchmark ) : <nl> - <nl> - def _assertSingleClassMetrics ( self , metrics ) : <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , ' auc ' , metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , <nl> - ' accuracy / threshold_0 . 500000_mean ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( <nl> - 0 . 9 , 1 . 0 , ' precision / positive_threshold_0 . 500000_mean ' , metrics ) <nl> - estimator_test_utils . assert_in_range ( <nl> - 0 . 9 , 1 . 0 , ' recall / positive_threshold_0 . 500000_mean ' , metrics ) <nl> - self . _assertCommonMetrics ( metrics ) <nl> - <nl> - def _assertCommonMetrics ( self , metrics ) : <nl> - estimator_test_utils . assert_in_range ( _ITERS , _ITERS + 5 , ' global_step ' , <nl> - metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 9 , 1 . 0 , ' accuracy ' , metrics ) <nl> - estimator_test_utils . assert_in_range ( 0 . 0 , 0 . 2 , ' loss ' , metrics ) <nl> - self . report_benchmark ( <nl> - iters = metrics [ ' global_step ' ] , <nl> - extras = { k : v <nl> - for k , v in metrics . items ( ) if k in _METRIC_KEYS } ) <nl> - <nl> - def benchmarkMatrixData ( self ) : <nl> - iris = test_data . prepare_iris_data_for_logistic_regression ( ) <nl> - cont_feature = feature_column . real_valued_column ( ' feature ' , dimension = 4 ) <nl> - bucketized_feature = feature_column . bucketized_column ( <nl> - cont_feature , test_data . get_quantile_based_buckets ( iris . data , 10 ) ) <nl> - <nl> - classifier = dnn_linear_combined . DNNLinearCombinedClassifier ( <nl> - model_dir = tempfile . mkdtemp ( ) , <nl> - linear_feature_columns = ( bucketized_feature , ) , <nl> - dnn_feature_columns = ( cont_feature , ) , <nl> - dnn_hidden_units = ( 3 , 3 ) ) <nl> - <nl> - input_fn = test_data . iris_input_logistic_fn <nl> - metrics = classifier . fit ( input_fn = input_fn , steps = _ITERS ) . evaluate ( <nl> - input_fn = input_fn , steps = 100 ) <nl> - self . _assertSingleClassMetrics ( metrics ) <nl> - <nl> - def benchmarkTensorData ( self ) : <nl> - <nl> - def _input_fn ( ) : <nl> - iris = test_data . prepare_iris_data_for_logistic_regression ( ) <nl> - features = { } <nl> - for i in range ( 4 ) : <nl> - # The following shows how to provide the Tensor data for <nl> - # RealValuedColumns . <nl> - features . update ( { <nl> - str ( i ) : <nl> - array_ops . reshape ( <nl> - constant_op . constant ( <nl> - iris . data [ : , i ] , dtype = dtypes . float32 ) , ( - 1 , 1 ) ) <nl> - } ) <nl> - # The following shows how to provide the SparseTensor data for <nl> - # a SparseColumn . <nl> - features [ ' dummy_sparse_column ' ] = sparse_tensor . SparseTensor ( <nl> - values = ( ' en ' , ' fr ' , ' zh ' ) , <nl> - indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 60 , 0 ) ) , <nl> - dense_shape = ( len ( iris . target ) , 2 ) ) <nl> - labels = array_ops . reshape ( <nl> - constant_op . constant ( <nl> - iris . target , dtype = dtypes . int32 ) , ( - 1 , 1 ) ) <nl> - return features , labels <nl> - <nl> - iris = test_data . prepare_iris_data_for_logistic_regression ( ) <nl> - cont_features = [ <nl> - feature_column . real_valued_column ( str ( i ) ) for i in range ( 4 ) <nl> - ] <nl> - linear_features = [ <nl> - feature_column . bucketized_column ( <nl> - cont_features [ i ] , <nl> - test_data . get_quantile_based_buckets ( iris . data [ : , i ] , 10 ) ) <nl> - for i in range ( 4 ) <nl> - ] <nl> - linear_features . append ( <nl> - feature_column . sparse_column_with_hash_bucket ( <nl> - ' dummy_sparse_column ' , hash_bucket_size = 100 ) ) <nl> - <nl> - classifier = dnn_linear_combined . DNNLinearCombinedClassifier ( <nl> - model_dir = tempfile . mkdtemp ( ) , <nl> - linear_feature_columns = linear_features , <nl> - dnn_feature_columns = cont_features , <nl> - dnn_hidden_units = ( 3 , 3 ) ) <nl> - <nl> - metrics = classifier . fit ( input_fn = _input_fn , steps = _ITERS ) . evaluate ( <nl> - input_fn = _input_fn , steps = 100 ) <nl> - self . _assertSingleClassMetrics ( metrics ) <nl> - <nl> - def benchmarkCustomOptimizer ( self ) : <nl> - iris = test_data . prepare_iris_data_for_logistic_regression ( ) <nl> - cont_feature = feature_column . real_valued_column ( ' feature ' , dimension = 4 ) <nl> - bucketized_feature = feature_column . bucketized_column ( <nl> - cont_feature , test_data . get_quantile_based_buckets ( iris . data , 10 ) ) <nl> - <nl> - classifier = dnn_linear_combined . DNNLinearCombinedClassifier ( <nl> - model_dir = tempfile . mkdtemp ( ) , <nl> - linear_feature_columns = ( bucketized_feature , ) , <nl> - linear_optimizer = ftrl . FtrlOptimizer ( learning_rate = 0 . 1 ) , <nl> - dnn_feature_columns = ( cont_feature , ) , <nl> - dnn_hidden_units = ( 3 , 3 ) , <nl> - dnn_optimizer = adagrad . AdagradOptimizer ( learning_rate = 0 . 1 ) ) <nl> - <nl> - input_fn = test_data . iris_input_logistic_fn <nl> - metrics = classifier . fit ( input_fn = input_fn , steps = _ITERS ) . evaluate ( <nl> - input_fn = input_fn , steps = 100 ) <nl> - self . _assertSingleClassMetrics ( metrics ) <nl> - <nl> - def benchmarkMultiClass ( self ) : <nl> - iris = base . load_iris ( ) <nl> - cont_feature = feature_column . real_valued_column ( ' feature ' , dimension = 4 ) <nl> - bucketized_feature = feature_column . bucketized_column ( <nl> - cont_feature , test_data . get_quantile_based_buckets ( iris . data , 10 ) ) <nl> - <nl> - classifier = dnn_linear_combined . DNNLinearCombinedClassifier ( <nl> - n_classes = 3 , <nl> - linear_feature_columns = ( bucketized_feature , ) , <nl> - dnn_feature_columns = ( cont_feature , ) , <nl> - dnn_hidden_units = ( 3 , 3 ) ) <nl> - <nl> - input_fn = test_data . iris_input_multiclass_fn <nl> - metrics = classifier . fit ( input_fn = input_fn , steps = _ITERS ) . evaluate ( <nl> - input_fn = input_fn , steps = 100 ) <nl> - self . _assertCommonMetrics ( metrics ) <nl> - <nl> - def benchmarkPartitionedVariables ( self ) : <nl> - <nl> - def _input_fn ( ) : <nl> - features = { <nl> - ' language ' : <nl> - sparse_tensor . SparseTensor ( <nl> - values = ( ' en ' , ' fr ' , ' zh ' ) , <nl> - indices = ( ( 0 , 0 ) , ( 0 , 1 ) , ( 2 , 0 ) ) , <nl> - dense_shape = ( 3 , 2 ) ) <nl> - } <nl> - labels = constant_op . constant ( ( ( 1 , ) , ( 0 , ) , ( 0 , ) ) ) <nl> - return features , labels <nl> - <nl> - # The given hash_bucket_size results in variables larger than the <nl> - # default min_slice_size attribute , so the variables are partitioned . <nl> - sparse_feature = feature_column . sparse_column_with_hash_bucket ( <nl> - ' language ' , hash_bucket_size = 2e7 ) <nl> - embedding_feature = feature_column . embedding_column ( <nl> - sparse_feature , dimension = 1 ) <nl> - <nl> - tf_config = { <nl> - ' cluster ' : { <nl> - run_config . TaskType . PS : [ ' fake_ps_0 ' , ' fake_ps_1 ' ] <nl> - } <nl> - } <nl> - with test . mock . patch . dict ( ' os . environ ' , <nl> - { ' TF_CONFIG ' : json . dumps ( tf_config ) } ) : <nl> - config = run_config . RunConfig ( ) <nl> - # Because we did not start a distributed cluster , we need to pass an <nl> - # empty ClusterSpec , otherwise the device_setter will look for <nl> - # distributed jobs , such as " / job : ps " which are not present . <nl> - config . _cluster_spec = server_lib . ClusterSpec ( { } ) <nl> - <nl> - classifier = dnn_linear_combined . DNNLinearCombinedClassifier ( <nl> - linear_feature_columns = ( sparse_feature , ) , <nl> - dnn_feature_columns = ( embedding_feature , ) , <nl> - dnn_hidden_units = ( 3 , 3 ) , <nl> - config = config ) <nl> - <nl> - metrics = classifier . fit ( input_fn = _input_fn , steps = _ITERS ) . evaluate ( <nl> - input_fn = _input_fn , steps = 100 ) <nl> - self . _assertCommonMetrics ( metrics ) <nl> - <nl> - <nl> - if __name__ = = ' __main__ ' : <nl> - test . main ( ) <nl>
Deleting tf . contrib . learn . dnn benchmark tests .
tensorflow/tensorflow
c91952fc7a665523d43128bc65fb308c5af2a1b9
2017-09-06T17:50:50Z
mmm a / src / builtins / base . tq <nl> ppp b / src / builtins / base . tq <nl> const kNameDictionaryInitialCapacity : <nl> const kOrderedNameDictionaryInitialCapacity : <nl> constexpr int32 generates ' OrderedNameDictionary : : kInitialCapacity ' ; <nl> <nl> + const kWasmArrayHeaderSize : <nl> + constexpr int32 generates ' WasmArray : : kHeaderSize ' ; <nl> + <nl> const kDictModePrototypes : <nl> constexpr bool generates ' V8_DICT_MODE_PROTOTYPES_BOOL ' ; <nl> <nl> mmm a / src / builtins / builtins - definitions . h <nl> ppp b / src / builtins / builtins - definitions . h <nl> namespace internal { <nl> ASM ( WasmDebugBreak , Dummy ) \ <nl> TFC ( WasmFloat32ToNumber , WasmFloat32ToNumber ) \ <nl> TFC ( WasmFloat64ToNumber , WasmFloat64ToNumber ) \ <nl> - TFS ( WasmAllocateArrayWithRtt , kMap , kLength , kElementSize ) \ <nl> TFC ( WasmI32AtomicWait32 , WasmI32AtomicWait32 ) \ <nl> TFC ( WasmI64AtomicWait32 , WasmI64AtomicWait32 ) \ <nl> TFS ( WasmAllocatePair , kValue1 , kValue2 ) \ <nl> mmm a / src / builtins / builtins - wasm - gen . cc <nl> ppp b / src / builtins / builtins - wasm - gen . cc <nl> TF_BUILTIN ( WasmI64AtomicWait32 , WasmBuiltinsAssembler ) { <nl> Return ( Unsigned ( SmiToInt32 ( result_smi ) ) ) ; <nl> } <nl> <nl> - TF_BUILTIN ( WasmAllocateArrayWithRtt , WasmBuiltinsAssembler ) { <nl> - auto map = Parameter < Map > ( Descriptor : : kMap ) ; <nl> - auto length = Parameter < Smi > ( Descriptor : : kLength ) ; <nl> - auto element_size = Parameter < Smi > ( Descriptor : : kElementSize ) ; <nl> - TNode < IntPtrT > untagged_length = SmiUntag ( length ) ; <nl> - / / instance_size = WasmArray : : kHeaderSize <nl> - / / + RoundUp ( element_size * length , kObjectAlignment ) <nl> - TNode < IntPtrT > raw_size = IntPtrMul ( SmiUntag ( element_size ) , untagged_length ) ; <nl> - TNode < IntPtrT > rounded_size = <nl> - WordAnd ( IntPtrAdd ( raw_size , IntPtrConstant ( kObjectAlignmentMask ) ) , <nl> - IntPtrConstant ( ~ kObjectAlignmentMask ) ) ; <nl> - TNode < IntPtrT > instance_size = <nl> - IntPtrAdd ( IntPtrConstant ( WasmArray : : kHeaderSize ) , rounded_size ) ; <nl> - TNode < WasmArray > result = UncheckedCast < WasmArray > ( <nl> - Allocate ( instance_size , kAllowLargeObjectAllocation ) ) ; <nl> - StoreMap ( result , map ) ; <nl> - StoreObjectFieldNoWriteBarrier ( result , WasmArray : : kLengthOffset , <nl> - TruncateIntPtrToInt32 ( untagged_length ) ) ; <nl> - Return ( result ) ; <nl> - } <nl> - <nl> TF_BUILTIN ( WasmAllocatePair , WasmBuiltinsAssembler ) { <nl> TNode < WasmInstanceObject > instance = LoadInstanceFromFrame ( ) ; <nl> TNode < HeapObject > value1 = Parameter < HeapObject > ( Descriptor : : kValue1 ) ; <nl> mmm a / src / builtins / wasm . tq <nl> ppp b / src / builtins / wasm . tq <nl> extern runtime WasmAllocateRtt ( Context , Smi , Map ) : Map ; <nl> <nl> namespace unsafe { <nl> extern macro TimesTaggedSize ( intptr ) : intptr ; <nl> - extern macro Allocate ( intptr ) : HeapObject ; <nl> + extern macro Allocate ( intptr , constexpr AllocationFlag ) : HeapObject ; <nl> } <nl> <nl> namespace wasm { <nl> builtin WasmAllocateRtt ( implicit context : Context ) ( <nl> builtin WasmAllocateStructWithRtt ( rtt : Map ) : HeapObject { <nl> const instanceSize : intptr = <nl> unsafe : : TimesTaggedSize ( Convert < intptr > ( rtt . instance_size_in_words ) ) ; <nl> - const result : HeapObject = unsafe : : Allocate ( instanceSize ) ; <nl> + const result : HeapObject = unsafe : : Allocate ( <nl> + instanceSize , AllocationFlag : : kAllowLargeObjectAllocation ) ; <nl> * UnsafeConstCast ( & result . map ) = rtt ; <nl> return result ; <nl> } <nl> <nl> + builtin WasmAllocateArrayWithRtt ( <nl> + rtt : Map , length : uint32 , elementSize : uint32 ) : HeapObject { <nl> + / / instanceSize = RoundUp ( elementSize * length , kObjectAlignment ) <nl> + / / + WasmArray : : kHeaderSize <nl> + const instanceSize : intptr = <nl> + torque_internal : : AlignTagged ( <nl> + Convert < intptr > ( length ) * Convert < intptr > ( elementSize ) ) + <nl> + Convert < intptr > ( kWasmArrayHeaderSize ) ; <nl> + const result : HeapObject = unsafe : : Allocate ( <nl> + instanceSize , AllocationFlag : : kAllowLargeObjectAllocation ) ; <nl> + * UnsafeConstCast ( & result . map ) = rtt ; <nl> + % RawDownCast < WasmArray > ( result ) . length = length ; <nl> + return result ; <nl> + } <nl> + <nl> / / Redeclaration with different typing ( value is an Object , not JSAny ) . <nl> extern transitioning runtime <nl> CreateDataProperty ( implicit context : Context ) ( JSReceiver , JSAny , Object ) ; <nl> mmm a / src / compiler / wasm - compiler . cc <nl> ppp b / src / compiler / wasm - compiler . cc <nl> Node * WasmGraphBuilder : : ArrayNewWithRtt ( uint32_t array_index , <nl> length , gasm_ - > Uint32Constant ( wasm : : kV8MaxWasmArrayLength ) ) , <nl> position ) ; <nl> wasm : : ValueType element_type = type - > element_type ( ) ; <nl> - Node * a = CALL_BUILTIN ( <nl> - WasmAllocateArrayWithRtt , rtt , BuildChangeUint31ToSmi ( length ) , <nl> - graph ( ) - > NewNode ( mcgraph ( ) - > common ( ) - > NumberConstant ( <nl> - element_type . element_size_bytes ( ) ) ) , <nl> - LOAD_INSTANCE_FIELD ( NativeContext , MachineType : : TaggedPointer ( ) ) ) ; <nl> + Node * a = CALL_BUILTIN ( WasmAllocateArrayWithRtt , rtt , length , <nl> + graph ( ) - > NewNode ( mcgraph ( ) - > common ( ) - > Int32Constant ( <nl> + element_type . element_size_bytes ( ) ) ) ) ; <nl> auto loop = gasm_ - > MakeLoopLabel ( MachineRepresentation : : kWord32 ) ; <nl> auto done = gasm_ - > MakeLabel ( ) ; <nl> Node * start_offset = gasm_ - > Int32Constant ( <nl>
[ wasm - gc ] [ builtins ] Migrate WasmAllocateArrayWithRtt to Torque
v8/v8
e7be15c7b519c6f00ad63a632513e9abcc6aa4bc
2020-12-16T15:04:14Z
mmm a / modules / planning / common / planning_data . cc <nl> ppp b / modules / planning / common / planning_data . cc <nl> <nl> # include " modules / common / log . h " <nl> # include " modules / common / util / string_util . h " <nl> # include " modules / planning / common / path / path_data . h " <nl> - # include " modules / planning / proto / planning . pb . h " <nl> <nl> namespace apollo { <nl> namespace planning { <nl> SpeedData * PlanningData : : mutable_speed_data ( ) { return & speed_data_ ; } <nl> bool PlanningData : : aggregate ( const double time_resolution , <nl> const double relative_time , <nl> PublishableTrajectory * trajectory ) { <nl> - if ( time_resolution < 0 . 0 ) { <nl> - AERROR < < " time_resolution : " < < time_resolution < < " < 0 . 0 " ; <nl> - return false ; <nl> - } <nl> - if ( ! trajectory ) { <nl> - AERROR < < " The input trajectory is empty " ; <nl> - return false ; <nl> - } <nl> + CHECK ( time_resolution > 0 . 0 ) ; <nl> + CHECK ( trajectory ! = nullptr ) ; <nl> <nl> for ( double cur_rel_time = 0 . 0 ; cur_rel_time < speed_data_ . total_time ( ) ; <nl> cur_rel_time + = time_resolution ) { <nl> common : : SpeedPoint speed_point ; <nl> - QUIT_IF ( ! speed_data_ . get_speed_point_with_time ( cur_rel_time , & speed_point ) , <nl> - false , ERROR , " Fail to get speed point with relative time % f " , <nl> - cur_rel_time ) ; <nl> + if ( ! speed_data_ . get_speed_point_with_time ( cur_rel_time , & speed_point ) ) { <nl> + AERROR < < " Fail to get speed point with relative time " < < cur_rel_time ; <nl> + return false ; <nl> + } <nl> <nl> - common : : PathPoint path_point ; <nl> - / / TODO ( all ) : temp fix speed point s out of path point bound , need further <nl> - / / refine later <nl> if ( speed_point . s ( ) > path_data_ . discretized_path ( ) . length ( ) ) { <nl> break ; <nl> } <nl> + common : : PathPoint path_point ; <nl> if ( ! path_data_ . get_path_point_with_path_s ( speed_point . s ( ) , & path_point ) ) { <nl> AERROR < < " Fail to get path data with s " < < speed_point . s ( ) <nl> < < " path total length " < < path_data_ . discretized_path ( ) . length ( ) ; <nl> bool PlanningData : : aggregate ( const double time_resolution , <nl> trajectory_point . set_v ( speed_point . v ( ) ) ; <nl> trajectory_point . set_a ( speed_point . a ( ) ) ; <nl> trajectory_point . set_relative_time ( speed_point . t ( ) + relative_time ) ; <nl> - trajectory - > add_trajectory_point ( trajectory_point ) ; <nl> + trajectory - > append_trajectory_point ( trajectory_point ) ; <nl> } <nl> return true ; <nl> } <nl> mmm a / modules / planning / common / trajectory / discretized_trajectory . cc <nl> ppp b / modules / planning / common / trajectory / discretized_trajectory . cc <nl> std : : uint32_t DiscretizedTrajectory : : query_nearest_point ( <nl> return index_min ; <nl> } <nl> <nl> - void DiscretizedTrajectory : : add_trajectory_point ( <nl> + void DiscretizedTrajectory : : append_trajectory_point ( <nl> const TrajectoryPoint & trajectory_point ) { <nl> if ( ! _trajectory_points . empty ( ) ) { <nl> CHECK_GT ( trajectory_point . relative_time ( ) , <nl> mmm a / modules / planning / common / trajectory / discretized_trajectory . h <nl> ppp b / modules / planning / common / trajectory / discretized_trajectory . h <nl> class DiscretizedTrajectory : public Trajectory { <nl> virtual uint32_t query_nearest_point ( <nl> const common : : math : : Vec2d & position ) const ; <nl> <nl> - virtual void add_trajectory_point ( <nl> + virtual void append_trajectory_point ( <nl> const apollo : : common : : TrajectoryPoint & trajectory_point ) ; <nl> <nl> const apollo : : common : : TrajectoryPoint & trajectory_point_at ( <nl>
Restructured planning_data aggregate function
ApolloAuto/apollo
fb3699d97428623fa87b3035361c8ee93dc514c0
2017-08-04T18:10:18Z
mmm a / CMakeLists . txt <nl> ppp b / CMakeLists . txt <nl> set ( TESTS <nl> db / db_test . cc <nl> db / db_compaction_filter_test . cc <nl> db / db_dynamic_level_test . cc <nl> + db / db_tailing_iter_test . cc <nl> db / dbformat_test . cc <nl> db / deletefile_test . cc <nl> db / fault_injection_test . cc <nl> mmm a / Makefile <nl> ppp b / Makefile <nl> TESTS = \ <nl> db_iter_test \ <nl> db_log_iter_test \ <nl> db_dynamic_level_test \ <nl> + db_tailing_iter_test \ <nl> block_hash_index_test \ <nl> autovector_test \ <nl> column_family_test \ <nl> db_compaction_filter_test : db / db_compaction_filter_test . o util / db_test_util . o $ ( <nl> db_dynamic_level_test : db / db_dynamic_level_test . o util / db_test_util . o $ ( LIBOBJECTS ) $ ( TESTHARNESS ) <nl> $ ( AM_LINK ) <nl> <nl> + db_tailing_iter_test : db / db_tailing_iter_test . o util / db_test_util . o $ ( LIBOBJECTS ) $ ( TESTHARNESS ) <nl> + $ ( AM_LINK ) <nl> + <nl> db_iter_test : db / db_iter_test . o $ ( LIBOBJECTS ) $ ( TESTHARNESS ) <nl> $ ( AM_LINK ) <nl> <nl> new file mode 100644 <nl> index 0000000000 . . d36f2bb0a1 <nl> mmm / dev / null <nl> ppp b / db / db_tailing_iter_test . cc <nl> <nl> + / / Copyright ( c ) 2013 , Facebook , Inc . All rights reserved . <nl> + / / This source code is licensed under the BSD - style license found in the <nl> + / / LICENSE file in the root directory of this source tree . An additional grant <nl> + / / of patent rights can be found in the PATENTS file in the same directory . <nl> + / / <nl> + / / Copyright ( c ) 2011 The LevelDB Authors . All rights reserved . <nl> + / / Use of this source code is governed by a BSD - style license that can be <nl> + / / found in the LICENSE file . See the AUTHORS file for names of contributors . <nl> + <nl> + / / Introduction of SyncPoint effectively disabled building and running this test <nl> + / / in Release build . <nl> + / / which is a pity , it is a good test <nl> + # if ! ( defined NDEBUG ) | | ! defined ( OS_WIN ) <nl> + <nl> + # include " port / stack_trace . h " <nl> + # include " util / db_test_util . h " <nl> + <nl> + namespace rocksdb { <nl> + <nl> + class DBTestTailingIterator : public DBTestBase { <nl> + public : <nl> + DBTestTailingIterator ( ) : DBTestBase ( " / db_tailing_iterator_test " ) { } <nl> + } ; <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorSingle ) { <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + <nl> + / / add a record and check that iter can see it <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , " mirko " , " fodor " ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " mirko " ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorKeepAdding ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + std : : string value ( 1024 , ' a ' ) ; <nl> + <nl> + const int num_records = 10000 ; <nl> + for ( int i = 0 ; i < num_records ; + + i ) { <nl> + char buf [ 32 ] ; <nl> + snprintf ( buf , sizeof ( buf ) , " % 016d " , i ) ; <nl> + <nl> + Slice key ( buf , 16 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + <nl> + iter - > Seek ( key ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorSeekToNext ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + std : : string value ( 1024 , ' a ' ) ; <nl> + <nl> + const int num_records = 1000 ; <nl> + for ( int i = 1 ; i < num_records ; + + i ) { <nl> + char buf1 [ 32 ] ; <nl> + char buf2 [ 32 ] ; <nl> + snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> + <nl> + Slice key ( buf1 , 20 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + <nl> + if ( i % 100 = = 99 ) { <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + } <nl> + <nl> + snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> + Slice target ( buf2 , 20 ) ; <nl> + iter - > Seek ( target ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> + } <nl> + for ( int i = 2 * num_records ; i > 0 ; - - i ) { <nl> + char buf1 [ 32 ] ; <nl> + char buf2 [ 32 ] ; <nl> + snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> + <nl> + Slice key ( buf1 , 20 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + <nl> + if ( i % 100 = = 99 ) { <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + } <nl> + <nl> + snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> + Slice target ( buf2 , 20 ) ; <nl> + iter - > Seek ( target ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorDeletes ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + <nl> + / / write a single record , read it using the iterator , then delete it <nl> + ASSERT_OK ( Put ( 1 , " 0test " , " test " ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0test " ) ; <nl> + ASSERT_OK ( Delete ( 1 , " 0test " ) ) ; <nl> + <nl> + / / write many more records <nl> + const int num_records = 10000 ; <nl> + std : : string value ( 1024 , ' A ' ) ; <nl> + <nl> + for ( int i = 0 ; i < num_records ; + + i ) { <nl> + char buf [ 32 ] ; <nl> + snprintf ( buf , sizeof ( buf ) , " 1 % 015d " , i ) ; <nl> + <nl> + Slice key ( buf , 16 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + } <nl> + <nl> + / / force a flush to make sure that no records are read from memtable <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + <nl> + / / skip " 0test " <nl> + iter - > Next ( ) ; <nl> + <nl> + / / make sure we can read all new records using the existing iterator <nl> + int count = 0 ; <nl> + for ( ; iter - > Valid ( ) ; iter - > Next ( ) , + + count ) ; <nl> + <nl> + ASSERT_EQ ( count , num_records ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorPrefixSeek ) { <nl> + XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , <nl> + kSkipNoPrefix ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + <nl> + Options options = CurrentOptions ( ) ; <nl> + options . env = env_ ; <nl> + options . create_if_missing = true ; <nl> + options . disable_auto_compactions = true ; <nl> + options . prefix_extractor . reset ( NewFixedPrefixTransform ( 2 ) ) ; <nl> + options . memtable_factory . reset ( NewHashSkipListRepFactory ( 16 ) ) ; <nl> + DestroyAndReopen ( options ) ; <nl> + CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + ASSERT_OK ( Put ( 1 , " 0101 " , " test " ) ) ; <nl> + <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + <nl> + ASSERT_OK ( Put ( 1 , " 0202 " , " test " ) ) ; <nl> + <nl> + / / Seek ( 0102 ) shouldn ' t find any records since 0202 has a different prefix <nl> + iter - > Seek ( " 0102 " ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + <nl> + iter - > Seek ( " 0202 " ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0202 " ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorIncomplete ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . read_tier = kBlockCacheTier ; <nl> + <nl> + std : : string key ( " key " ) ; <nl> + std : : string value ( " value " ) ; <nl> + <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + / / we either see the entry or it ' s not in cache <nl> + ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> + <nl> + ASSERT_OK ( db_ - > CompactRange ( CompactRangeOptions ( ) , nullptr , nullptr ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + / / should still be true after compaction <nl> + ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , TailingIteratorSeekToSame ) { <nl> + Options options = CurrentOptions ( ) ; <nl> + options . compaction_style = kCompactionStyleUniversal ; <nl> + options . write_buffer_size = 1000 ; <nl> + CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> + <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + <nl> + const int NROWS = 10000 ; <nl> + / / Write rows with keys 00000 , 00002 , 00004 etc . <nl> + for ( int i = 0 ; i < NROWS ; + + i ) { <nl> + char buf [ 100 ] ; <nl> + snprintf ( buf , sizeof ( buf ) , " % 05d " , 2 * i ) ; <nl> + std : : string key ( buf ) ; <nl> + std : : string value ( " value " ) ; <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> + } <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + / / Seek to 00001 . We expect to find 00002 . <nl> + std : : string start_key = " 00001 " ; <nl> + iter - > Seek ( start_key ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + <nl> + std : : string found = iter - > key ( ) . ToString ( ) ; <nl> + ASSERT_EQ ( " 00002 " , found ) ; <nl> + <nl> + / / Now seek to the same key . The iterator should remain in the same <nl> + / / position . <nl> + iter - > Seek ( found ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( found , iter - > key ( ) . ToString ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorSingle ) { <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + <nl> + / / add a record and check that iter can see it <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , " mirko " , " fodor " ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " mirko " ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorKeepAdding ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + std : : string value ( 1024 , ' a ' ) ; <nl> + <nl> + const int num_records = 10000 ; <nl> + for ( int i = 0 ; i < num_records ; + + i ) { <nl> + char buf [ 32 ] ; <nl> + snprintf ( buf , sizeof ( buf ) , " % 016d " , i ) ; <nl> + <nl> + Slice key ( buf , 16 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + <nl> + iter - > Seek ( key ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorSeekToNext ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + std : : string value ( 1024 , ' a ' ) ; <nl> + <nl> + const int num_records = 1000 ; <nl> + for ( int i = 1 ; i < num_records ; + + i ) { <nl> + char buf1 [ 32 ] ; <nl> + char buf2 [ 32 ] ; <nl> + snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> + <nl> + Slice key ( buf1 , 20 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + <nl> + if ( i % 100 = = 99 ) { <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + } <nl> + <nl> + snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> + Slice target ( buf2 , 20 ) ; <nl> + iter - > Seek ( target ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> + } <nl> + for ( int i = 2 * num_records ; i > 0 ; - - i ) { <nl> + char buf1 [ 32 ] ; <nl> + char buf2 [ 32 ] ; <nl> + snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> + <nl> + Slice key ( buf1 , 20 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + <nl> + if ( i % 100 = = 99 ) { <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + } <nl> + <nl> + snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> + Slice target ( buf2 , 20 ) ; <nl> + iter - > Seek ( target ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> + } <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorDeletes ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + <nl> + / / write a single record , read it using the iterator , then delete it <nl> + ASSERT_OK ( Put ( 1 , " 0test " , " test " ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0test " ) ; <nl> + ASSERT_OK ( Delete ( 1 , " 0test " ) ) ; <nl> + <nl> + / / write many more records <nl> + const int num_records = 10000 ; <nl> + std : : string value ( 1024 , ' A ' ) ; <nl> + <nl> + for ( int i = 0 ; i < num_records ; + + i ) { <nl> + char buf [ 32 ] ; <nl> + snprintf ( buf , sizeof ( buf ) , " 1 % 015d " , i ) ; <nl> + <nl> + Slice key ( buf , 16 ) ; <nl> + ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> + } <nl> + <nl> + / / force a flush to make sure that no records are read from memtable <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + <nl> + / / skip " 0test " <nl> + iter - > Next ( ) ; <nl> + <nl> + / / make sure we can read all new records using the existing iterator <nl> + int count = 0 ; <nl> + for ( ; iter - > Valid ( ) ; iter - > Next ( ) , + + count ) { <nl> + } <nl> + <nl> + ASSERT_EQ ( count , num_records ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorPrefixSeek ) { <nl> + XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , <nl> + kSkipNoPrefix ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + <nl> + Options options = CurrentOptions ( ) ; <nl> + options . env = env_ ; <nl> + options . create_if_missing = true ; <nl> + options . disable_auto_compactions = true ; <nl> + options . prefix_extractor . reset ( NewFixedPrefixTransform ( 2 ) ) ; <nl> + options . memtable_factory . reset ( NewHashSkipListRepFactory ( 16 ) ) ; <nl> + DestroyAndReopen ( options ) ; <nl> + CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> + ASSERT_OK ( Put ( 1 , " 0101 " , " test " ) ) ; <nl> + <nl> + ASSERT_OK ( Flush ( 1 ) ) ; <nl> + <nl> + ASSERT_OK ( Put ( 1 , " 0202 " , " test " ) ) ; <nl> + <nl> + / / Seek ( 0102 ) shouldn ' t find any records since 0202 has a different prefix <nl> + iter - > Seek ( " 0102 " ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + <nl> + iter - > Seek ( " 0202 " ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0202 " ) ; <nl> + <nl> + iter - > Next ( ) ; <nl> + ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> + XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , 0 ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorIncomplete ) { <nl> + CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + read_options . read_tier = kBlockCacheTier ; <nl> + <nl> + std : : string key = " key " ; <nl> + std : : string value = " value " ; <nl> + <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + / / we either see the entry or it ' s not in cache <nl> + ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> + <nl> + ASSERT_OK ( db_ - > CompactRange ( CompactRangeOptions ( ) , nullptr , nullptr ) ) ; <nl> + iter - > SeekToFirst ( ) ; <nl> + / / should still be true after compaction <nl> + ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> + } <nl> + <nl> + TEST_F ( DBTestTailingIterator , ManagedTailingIteratorSeekToSame ) { <nl> + Options options = CurrentOptions ( ) ; <nl> + options . compaction_style = kCompactionStyleUniversal ; <nl> + options . write_buffer_size = 1000 ; <nl> + CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> + <nl> + ReadOptions read_options ; <nl> + read_options . tailing = true ; <nl> + read_options . managed = true ; <nl> + <nl> + const int NROWS = 10000 ; <nl> + / / Write rows with keys 00000 , 00002 , 00004 etc . <nl> + for ( int i = 0 ; i < NROWS ; + + i ) { <nl> + char buf [ 100 ] ; <nl> + snprintf ( buf , sizeof ( buf ) , " % 05d " , 2 * i ) ; <nl> + std : : string key ( buf ) ; <nl> + std : : string value ( " value " ) ; <nl> + ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> + } <nl> + <nl> + std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> + / / Seek to 00001 . We expect to find 00002 . <nl> + std : : string start_key = " 00001 " ; <nl> + iter - > Seek ( start_key ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + <nl> + std : : string found = iter - > key ( ) . ToString ( ) ; <nl> + ASSERT_EQ ( " 00002 " , found ) ; <nl> + <nl> + / / Now seek to the same key . The iterator should remain in the same <nl> + / / position . <nl> + iter - > Seek ( found ) ; <nl> + ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> + ASSERT_EQ ( found , iter - > key ( ) . ToString ( ) ) ; <nl> + } <nl> + <nl> + } / / namespace rocksdb <nl> + <nl> + # endif / / ! ( defined NDEBUG ) | | ! defined ( OS_WIN ) <nl> + <nl> + int main ( int argc , char * * argv ) { <nl> + # if ! ( defined NDEBUG ) | | ! defined ( OS_WIN ) <nl> + rocksdb : : port : : InstallStackTraceHandler ( ) ; <nl> + : : testing : : InitGoogleTest ( & argc , argv ) ; <nl> + return RUN_ALL_TESTS ( ) ; <nl> + # else <nl> + return 0 ; <nl> + # endif <nl> + } <nl> mmm a / db / db_test . cc <nl> ppp b / db / db_test . cc <nl> TEST_F ( DBTest , PrefixScan ) { <nl> XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , 0 ) ; <nl> } <nl> <nl> - TEST_F ( DBTest , TailingIteratorSingle ) { <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - <nl> - / / add a record and check that iter can see it <nl> - ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , " mirko " , " fodor " ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " mirko " ) ; <nl> - <nl> - iter - > Next ( ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , TailingIteratorKeepAdding ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - std : : string value ( 1024 , ' a ' ) ; <nl> - <nl> - const int num_records = 10000 ; <nl> - for ( int i = 0 ; i < num_records ; + + i ) { <nl> - char buf [ 32 ] ; <nl> - snprintf ( buf , sizeof ( buf ) , " % 016d " , i ) ; <nl> - <nl> - Slice key ( buf , 16 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - <nl> - iter - > Seek ( key ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> - } <nl> - } <nl> - <nl> - TEST_F ( DBTest , TailingIteratorSeekToNext ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - std : : string value ( 1024 , ' a ' ) ; <nl> - <nl> - const int num_records = 1000 ; <nl> - for ( int i = 1 ; i < num_records ; + + i ) { <nl> - char buf1 [ 32 ] ; <nl> - char buf2 [ 32 ] ; <nl> - snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> - <nl> - Slice key ( buf1 , 20 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - <nl> - if ( i % 100 = = 99 ) { <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - } <nl> - <nl> - snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> - Slice target ( buf2 , 20 ) ; <nl> - iter - > Seek ( target ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> - } <nl> - for ( int i = 2 * num_records ; i > 0 ; - - i ) { <nl> - char buf1 [ 32 ] ; <nl> - char buf2 [ 32 ] ; <nl> - snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> - <nl> - Slice key ( buf1 , 20 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - <nl> - if ( i % 100 = = 99 ) { <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - } <nl> - <nl> - snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> - Slice target ( buf2 , 20 ) ; <nl> - iter - > Seek ( target ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> - } <nl> - } <nl> - <nl> - TEST_F ( DBTest , TailingIteratorDeletes ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - <nl> - / / write a single record , read it using the iterator , then delete it <nl> - ASSERT_OK ( Put ( 1 , " 0test " , " test " ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0test " ) ; <nl> - ASSERT_OK ( Delete ( 1 , " 0test " ) ) ; <nl> - <nl> - / / write many more records <nl> - const int num_records = 10000 ; <nl> - std : : string value ( 1024 , ' A ' ) ; <nl> - <nl> - for ( int i = 0 ; i < num_records ; + + i ) { <nl> - char buf [ 32 ] ; <nl> - snprintf ( buf , sizeof ( buf ) , " 1 % 015d " , i ) ; <nl> - <nl> - Slice key ( buf , 16 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - } <nl> - <nl> - / / force a flush to make sure that no records are read from memtable <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - <nl> - / / skip " 0test " <nl> - iter - > Next ( ) ; <nl> - <nl> - / / make sure we can read all new records using the existing iterator <nl> - int count = 0 ; <nl> - for ( ; iter - > Valid ( ) ; iter - > Next ( ) , + + count ) ; <nl> - <nl> - ASSERT_EQ ( count , num_records ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , TailingIteratorPrefixSeek ) { <nl> - XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , <nl> - kSkipNoPrefix ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - <nl> - Options options = CurrentOptions ( ) ; <nl> - options . env = env_ ; <nl> - options . create_if_missing = true ; <nl> - options . disable_auto_compactions = true ; <nl> - options . prefix_extractor . reset ( NewFixedPrefixTransform ( 2 ) ) ; <nl> - options . memtable_factory . reset ( NewHashSkipListRepFactory ( 16 ) ) ; <nl> - DestroyAndReopen ( options ) ; <nl> - CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - ASSERT_OK ( Put ( 1 , " 0101 " , " test " ) ) ; <nl> - <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - <nl> - ASSERT_OK ( Put ( 1 , " 0202 " , " test " ) ) ; <nl> - <nl> - / / Seek ( 0102 ) shouldn ' t find any records since 0202 has a different prefix <nl> - iter - > Seek ( " 0102 " ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - <nl> - iter - > Seek ( " 0202 " ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0202 " ) ; <nl> - <nl> - iter - > Next ( ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , 0 ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , TailingIteratorIncomplete ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . read_tier = kBlockCacheTier ; <nl> - <nl> - std : : string key ( " key " ) ; <nl> - std : : string value ( " value " ) ; <nl> - <nl> - ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - / / we either see the entry or it ' s not in cache <nl> - ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> - <nl> - ASSERT_OK ( db_ - > CompactRange ( CompactRangeOptions ( ) , nullptr , nullptr ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - / / should still be true after compaction <nl> - ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , TailingIteratorSeekToSame ) { <nl> - Options options = CurrentOptions ( ) ; <nl> - options . compaction_style = kCompactionStyleUniversal ; <nl> - options . write_buffer_size = 1000 ; <nl> - CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> - <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - <nl> - const int NROWS = 10000 ; <nl> - / / Write rows with keys 00000 , 00002 , 00004 etc . <nl> - for ( int i = 0 ; i < NROWS ; + + i ) { <nl> - char buf [ 100 ] ; <nl> - snprintf ( buf , sizeof ( buf ) , " % 05d " , 2 * i ) ; <nl> - std : : string key ( buf ) ; <nl> - std : : string value ( " value " ) ; <nl> - ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> - } <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> - / / Seek to 00001 . We expect to find 00002 . <nl> - std : : string start_key = " 00001 " ; <nl> - iter - > Seek ( start_key ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - <nl> - std : : string found = iter - > key ( ) . ToString ( ) ; <nl> - ASSERT_EQ ( " 00002 " , found ) ; <nl> - <nl> - / / Now seek to the same key . The iterator should remain in the same <nl> - / / position . <nl> - iter - > Seek ( found ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( found , iter - > key ( ) . ToString ( ) ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorSingle ) { <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - <nl> - / / add a record and check that iter can see it <nl> - ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , " mirko " , " fodor " ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " mirko " ) ; <nl> - <nl> - iter - > Next ( ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorKeepAdding ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - std : : string value ( 1024 , ' a ' ) ; <nl> - <nl> - const int num_records = 10000 ; <nl> - for ( int i = 0 ; i < num_records ; + + i ) { <nl> - char buf [ 32 ] ; <nl> - snprintf ( buf , sizeof ( buf ) , " % 016d " , i ) ; <nl> - <nl> - Slice key ( buf , 16 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - <nl> - iter - > Seek ( key ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> - } <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorSeekToNext ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - std : : string value ( 1024 , ' a ' ) ; <nl> - <nl> - const int num_records = 1000 ; <nl> - for ( int i = 1 ; i < num_records ; + + i ) { <nl> - char buf1 [ 32 ] ; <nl> - char buf2 [ 32 ] ; <nl> - snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> - <nl> - Slice key ( buf1 , 20 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - <nl> - if ( i % 100 = = 99 ) { <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - } <nl> - <nl> - snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> - Slice target ( buf2 , 20 ) ; <nl> - iter - > Seek ( target ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> - } <nl> - for ( int i = 2 * num_records ; i > 0 ; - - i ) { <nl> - char buf1 [ 32 ] ; <nl> - char buf2 [ 32 ] ; <nl> - snprintf ( buf1 , sizeof ( buf1 ) , " 00a0 % 016d " , i * 5 ) ; <nl> - <nl> - Slice key ( buf1 , 20 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - <nl> - if ( i % 100 = = 99 ) { <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - } <nl> - <nl> - snprintf ( buf2 , sizeof ( buf2 ) , " 00a0 % 016d " , i * 5 - 2 ) ; <nl> - Slice target ( buf2 , 20 ) ; <nl> - iter - > Seek ( target ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . compare ( key ) , 0 ) ; <nl> - } <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorDeletes ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - <nl> - / / write a single record , read it using the iterator , then delete it <nl> - ASSERT_OK ( Put ( 1 , " 0test " , " test " ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0test " ) ; <nl> - ASSERT_OK ( Delete ( 1 , " 0test " ) ) ; <nl> - <nl> - / / write many more records <nl> - const int num_records = 10000 ; <nl> - std : : string value ( 1024 , ' A ' ) ; <nl> - <nl> - for ( int i = 0 ; i < num_records ; + + i ) { <nl> - char buf [ 32 ] ; <nl> - snprintf ( buf , sizeof ( buf ) , " 1 % 015d " , i ) ; <nl> - <nl> - Slice key ( buf , 16 ) ; <nl> - ASSERT_OK ( Put ( 1 , key , value ) ) ; <nl> - } <nl> - <nl> - / / force a flush to make sure that no records are read from memtable <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - <nl> - / / skip " 0test " <nl> - iter - > Next ( ) ; <nl> - <nl> - / / make sure we can read all new records using the existing iterator <nl> - int count = 0 ; <nl> - for ( ; iter - > Valid ( ) ; iter - > Next ( ) , + + count ) { <nl> - } <nl> - <nl> - ASSERT_EQ ( count , num_records ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorPrefixSeek ) { <nl> - XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , <nl> - kSkipNoPrefix ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - <nl> - Options options = CurrentOptions ( ) ; <nl> - options . env = env_ ; <nl> - options . create_if_missing = true ; <nl> - options . disable_auto_compactions = true ; <nl> - options . prefix_extractor . reset ( NewFixedPrefixTransform ( 2 ) ) ; <nl> - options . memtable_factory . reset ( NewHashSkipListRepFactory ( 16 ) ) ; <nl> - DestroyAndReopen ( options ) ; <nl> - CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options , handles_ [ 1 ] ) ) ; <nl> - ASSERT_OK ( Put ( 1 , " 0101 " , " test " ) ) ; <nl> - <nl> - ASSERT_OK ( Flush ( 1 ) ) ; <nl> - <nl> - ASSERT_OK ( Put ( 1 , " 0202 " , " test " ) ) ; <nl> - <nl> - / / Seek ( 0102 ) shouldn ' t find any records since 0202 has a different prefix <nl> - iter - > Seek ( " 0102 " ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - <nl> - iter - > Seek ( " 0202 " ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( iter - > key ( ) . ToString ( ) , " 0202 " ) ; <nl> - <nl> - iter - > Next ( ) ; <nl> - ASSERT_TRUE ( ! iter - > Valid ( ) ) ; <nl> - XFUNC_TEST ( " " , " dbtest_prefix " , prefix_skip1 , XFuncPoint : : SetSkip , 0 ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorIncomplete ) { <nl> - CreateAndReopenWithCF ( { " pikachu " } , CurrentOptions ( ) ) ; <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - read_options . read_tier = kBlockCacheTier ; <nl> - <nl> - std : : string key = " key " ; <nl> - std : : string value = " value " ; <nl> - <nl> - ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - / / we either see the entry or it ' s not in cache <nl> - ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> - <nl> - ASSERT_OK ( db_ - > CompactRange ( CompactRangeOptions ( ) , nullptr , nullptr ) ) ; <nl> - iter - > SeekToFirst ( ) ; <nl> - / / should still be true after compaction <nl> - ASSERT_TRUE ( iter - > Valid ( ) | | iter - > status ( ) . IsIncomplete ( ) ) ; <nl> - } <nl> - <nl> - TEST_F ( DBTest , ManagedTailingIteratorSeekToSame ) { <nl> - Options options = CurrentOptions ( ) ; <nl> - options . compaction_style = kCompactionStyleUniversal ; <nl> - options . write_buffer_size = 1000 ; <nl> - CreateAndReopenWithCF ( { " pikachu " } , options ) ; <nl> - <nl> - ReadOptions read_options ; <nl> - read_options . tailing = true ; <nl> - read_options . managed = true ; <nl> - <nl> - const int NROWS = 10000 ; <nl> - / / Write rows with keys 00000 , 00002 , 00004 etc . <nl> - for ( int i = 0 ; i < NROWS ; + + i ) { <nl> - char buf [ 100 ] ; <nl> - snprintf ( buf , sizeof ( buf ) , " % 05d " , 2 * i ) ; <nl> - std : : string key ( buf ) ; <nl> - std : : string value ( " value " ) ; <nl> - ASSERT_OK ( db_ - > Put ( WriteOptions ( ) , key , value ) ) ; <nl> - } <nl> - <nl> - std : : unique_ptr < Iterator > iter ( db_ - > NewIterator ( read_options ) ) ; <nl> - / / Seek to 00001 . We expect to find 00002 . <nl> - std : : string start_key = " 00001 " ; <nl> - iter - > Seek ( start_key ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - <nl> - std : : string found = iter - > key ( ) . ToString ( ) ; <nl> - ASSERT_EQ ( " 00002 " , found ) ; <nl> - <nl> - / / Now seek to the same key . The iterator should remain in the same <nl> - / / position . <nl> - iter - > Seek ( found ) ; <nl> - ASSERT_TRUE ( iter - > Valid ( ) ) ; <nl> - ASSERT_EQ ( found , iter - > key ( ) . ToString ( ) ) ; <nl> - } <nl> - <nl> TEST_F ( DBTest , BlockBasedTablePrefixIndexTest ) { <nl> / / create a DB with block prefix index <nl> BlockBasedTableOptions table_options ; <nl> mmm a / src . mk <nl> ppp b / src . mk <nl> TEST_BENCH_SOURCES = \ <nl> db / db_compaction_filter_test . cc \ <nl> db / db_dynamic_level_test . cc \ <nl> db / db_log_iter_test . cc \ <nl> + db / db_tailing_iter_test . cc \ <nl> db / deletefile_test . cc \ <nl> db / fault_injection_test . cc \ <nl> db / file_indexer_test . cc \ <nl>
Move TailingIterator tests from db_test . cc to db_test_tailing_iterator . cc
facebook/rocksdb
3ca6b2541e14f8166e8248333163bd25521816cd
2015-07-14T23:41:08Z
mmm a / electron . gyp <nl> ppp b / electron . gyp <nl> <nl> # Make binary search for libraries under current directory , so we <nl> # don ' t have to manually set $ LD_LIBRARY_PATH : <nl> # http : / / serverfault . com / questions / 279068 / cant - find - so - in - the - same - directory - as - the - executable <nl> - ' - rpath \ $ $ ORIGIN ' , <nl> + ' - Wl , - rpath = \ $ $ ORIGIN ' , <nl> # Make native module dynamic loading work . <nl> ' - rdynamic ' , <nl> ] , <nl>
Fix passing rpath to gcc
electron/electron
16ffff4aec977b784afe5dc2f905cf57a031f9d4
2017-11-22T02:14:20Z
mmm a / dbms / src / Functions / FunctionsString . cpp <nl> ppp b / dbms / src / Functions / FunctionsString . cpp <nl> using namespace GatherUtils ; <nl> template < bool negative = false > <nl> struct EmptyImpl <nl> { <nl> + static constexpr auto is_fixed_to_constant = false ; <nl> + <nl> static void vector ( const ColumnString : : Chars_t & / * data * / , const ColumnString : : Offsets & offsets , PaddedPODArray < UInt8 > & res ) <nl> { <nl> size_t size = offsets . size ( ) ; <nl> struct EmptyImpl <nl> } <nl> } <nl> <nl> - static void vector_fixed_to_constant ( const ColumnString : : Chars_t & / * data * / , size_t n , UInt8 & res ) <nl> + static void vector_fixed_to_constant ( const ColumnString : : Chars_t & / * data * / , size_t / * n * / , UInt8 & / * res * / ) <nl> { <nl> - res = negative ^ ( n = = 0 ) ; <nl> } <nl> <nl> - static void vector_fixed_to_vector ( const ColumnString : : Chars_t & / * data * / , size_t / * n * / , PaddedPODArray < UInt8 > & / * res * / ) <nl> + static void vector_fixed_to_vector ( const ColumnString : : Chars_t & data , size_t n , PaddedPODArray < UInt8 > & res ) <nl> { <nl> + char * empty_chars [ n ] = { 0 } ; <nl> + size_t size = data . size ( ) / n ; <nl> + <nl> + for ( size_t i = 0 ; i < size ; + + i ) <nl> + res [ i ] = negative ^ ( n = = 0 | | 0 = = memcmp ( & data [ i * size ] , empty_chars , n ) ) ; <nl> } <nl> <nl> static void array ( const ColumnString : : Offsets & offsets , PaddedPODArray < UInt8 > & res ) <nl> struct EmptyImpl <nl> * / <nl> struct LengthImpl <nl> { <nl> + static constexpr auto is_fixed_to_constant = true ; <nl> + <nl> static void vector ( const ColumnString : : Chars_t & / * data * / , const ColumnString : : Offsets & offsets , PaddedPODArray < UInt64 > & res ) <nl> { <nl> size_t size = offsets . size ( ) ; <nl> struct LengthImpl <nl> * / <nl> struct LengthUTF8Impl <nl> { <nl> + static constexpr auto is_fixed_to_constant = false ; <nl> + <nl> static void vector ( const ColumnString : : Chars_t & data , const ColumnString : : Offsets & offsets , PaddedPODArray < UInt64 > & res ) <nl> { <nl> size_t size = offsets . size ( ) ; <nl> class FunctionStringOrArrayToT : public IFunction <nl> } <nl> else if ( const ColumnFixedString * col = checkAndGetColumn < ColumnFixedString > ( column . get ( ) ) ) <nl> { <nl> - / / / For a fixed string only ` lengthUTF8 ` function returns not a constant . <nl> - if ( " lengthUTF8 " ! = getName ( ) ) <nl> + if ( Impl : : is_fixed_to_constant ) <nl> { <nl> ResultType res = 0 ; <nl> Impl : : vector_fixed_to_constant ( col - > getChars ( ) , col - > getN ( ) , res ) ; <nl> new file mode 100644 <nl> index 00000000000 . . ae8f58a27fb <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00568_empty_function_with_fixed_string . reference <nl> <nl> + \ 0 \ 0 \ 0 \ 0 1 <nl> + \ 0abc 0 <nl> new file mode 100644 <nl> index 00000000000 . . 9ceb0fa4c75 <nl> mmm / dev / null <nl> ppp b / dbms / tests / queries / 0_stateless / 00568_empty_function_with_fixed_string . sql <nl> <nl> + SELECT toFixedString ( ' ' , 4 ) AS str , empty ( str ) AS is_empty ; <nl> + SELECT toFixedString ( ' \ 0abc ' , 4 ) AS str , empty ( str ) AS is_empty ; <nl>
Merge pull request from zhang2014 / fix / ISSUES - 180
ClickHouse/ClickHouse
f8d696b46bccc0577f6a90a0503125900cd76c91
2018-02-09T17:35:49Z
mmm a / tensorflow / compiler / xla / service / shape_inference . cc <nl> ppp b / tensorflow / compiler / xla / service / shape_inference . cc <nl> ShapeInference : : InferDegenerateDimensionBroadcastShape ( HloOpcode operation , <nl> if ( operand_shapes . size ( ) = = 1 ) { <nl> return * operand_shapes [ 0 ] ; <nl> } else if ( operand_shapes . size ( ) = = 2 ) { <nl> + if ( ! ShapeUtil : : SameDimensions ( * operand_shapes [ 0 ] , <nl> + * operand_shapes [ 1 ] ) ) { <nl> + return InvalidArgument ( <nl> + " Sort keys and values dimensions must match . " <nl> + " Keys shape is : % s \ n , Values shape is : % s " , <nl> + ShapeUtil : : HumanString ( * operand_shapes [ 0 ] ) . c_str ( ) , <nl> + ShapeUtil : : HumanString ( * operand_shapes [ 1 ] ) . c_str ( ) ) ; <nl> + } <nl> return ShapeUtil : : MakeTupleShape ( <nl> { * operand_shapes [ 0 ] , * operand_shapes [ 1 ] } ) ; <nl> } <nl> mmm a / tensorflow / compiler / xla / service / shape_inference_test . cc <nl> ppp b / tensorflow / compiler / xla / service / shape_inference_test . cc <nl> TEST_F ( ShapeInferenceTest , BadSlice ) { <nl> < < statusor . status ( ) ; <nl> } <nl> <nl> + TEST_F ( ShapeInferenceTest , BadSort ) { <nl> + auto keys = ShapeUtil : : MakeShape ( F32 , { 4 } ) ; <nl> + auto values = ShapeUtil : : MakeShape ( F32 , { 5 } ) ; <nl> + StatusOr < Shape > statusor = <nl> + ShapeInference : : InferVariadicOpShape ( HloOpcode : : kSort , { & keys , & values } ) ; <nl> + ASSERT_FALSE ( statusor . ok ( ) ) ; <nl> + <nl> + EXPECT_THAT ( statusor . status ( ) . error_message ( ) , <nl> + HasSubstr ( " dimensions must match " ) ) <nl> + < < statusor . status ( ) ; <nl> + } <nl> + <nl> class GatherShapeInferenceTest : public ShapeInferenceTest { <nl> protected : <nl> const Shape s64_scalar_ = ShapeUtil : : MakeShape ( S64 , { } ) ; <nl>
[ XLA ] Shape inference should verify the shapes of sort keys and sort values match .
tensorflow/tensorflow
8c5d2127182e0fadc0dcd6e97cb4acfba3a4c343
2018-07-17T21:28:24Z
mmm a / ChangeLog . rst <nl> ppp b / ChangeLog . rst <nl> <nl> ( ` # 171 < https : / / github . com / cppformat / cppformat / issues / 171 > ` _ ) . <nl> Thanks to ` @ alfps ( Alf P . Steinbach ) < https : / / github . com / alfps > ` _ . <nl> <nl> + * [ Breaking ] Named arguments <nl> + ( ` # 169 < https : / / github . com / cppformat / cppformat / pull / 169 > ` _ , <nl> + ` # 173 < https : / / github . com / cppformat / cppformat / pull / 173 > ` _ , <nl> + ` # 174 < https : / / github . com / cppformat / cppformat / pull / 174 > ` _ ) : <nl> + <nl> + . . code : : c + + <nl> + <nl> + fmt : : print ( " The answer is { answer } . " , fmt : : arg ( " answer " , 42 ) ) ; <nl> + <nl> + Thanks to ` @ jamboree < https : / / github . com / jamboree > ` _ . <nl> + <nl> * Fixed out - of - tree documentation build <nl> ( ` # 177 < https : / / github . com / cppformat / cppformat / issues / 177 > ` _ ) . <nl> Thanks to ` @ jackyf ( Eugene V . Lyubimkin ) < https : / / github . com / jackyf > ` _ . <nl> <nl> * Implemented a workaround for a name lookup bug in MSVC2010 <nl> ( ` # 188 < https : / / github . com / cppformat / cppformat / issues / 188 > ` _ ) . <nl> <nl> - * Fixed multiple warnings <nl> + * Fixed compiler warnings <nl> ( ` # 135 < https : / / github . com / cppformat / cppformat / issues / 135 > ` _ , <nl> ` # 142 < https : / / github . com / cppformat / cppformat / issues / 142 > ` _ , <nl> ` # 145 < https : / / github . com / cppformat / cppformat / issues / 145 > ` _ , <nl> <nl> < http : / / cppformat . github . io / dev / usage . html # building - the - documentation > ` _ <nl> section to the documentation . <nl> <nl> - * Documentation build script is now compatible with Python 3 <nl> - ( ` # 209 < https : / / github . com / cppformat / cppformat / issues / 209 > ` _ ) . <nl> + * Documentation build script is now compatible with Python 3 and newer pip versions . <nl> + ( ` # 189 < https : / / github . com / cppformat / cppformat / pull / 189 > ` _ , <nl> + ` # 209 < https : / / github . com / cppformat / cppformat / issues / 209 > ` _ ) . <nl> + Thanks to ` @ JodiTheTigger < https : / / github . com / JodiTheTigger > ` _ and <nl> + ` @ xentec < https : / / github . com / xentec > ` _ . <nl> <nl> * Fixed a name conflict with macro ` ` free ` ` defined in <nl> ` ` crtdbg . h ` ` when ` ` _CRTDBG_MAP_ALLOC ` ` is set <nl>
Update ChangeLog . rst
fmtlib/fmt
387b23f890710d4fd2b04e705002c4e839c9f3aa
2015-10-30T13:45:56Z
mmm a / modules / highgui / src / ffmpeg_codecs . hpp <nl> ppp b / modules / highgui / src / ffmpeg_codecs . hpp <nl> typedef struct AVCodecTag { <nl> # define AV_CODEC_ID_H264 CODEC_ID_H264 <nl> # define AV_CODEC_ID_H263 CODEC_ID_H263 <nl> # define AV_CODEC_ID_H263P CODEC_ID_H263P <nl> + # define AV_CODEC_ID_H263I CODEC_ID_H263I <nl> # define AV_CODEC_ID_H261 CODEC_ID_H261 <nl> # define AV_CODEC_ID_MPEG4 CODEC_ID_MPEG4 <nl> # define AV_CODEC_ID_MSMPEG4V3 CODEC_ID_MSMPEG4V3 <nl> typedef struct AVCodecTag { <nl> # define AV_CODEC_ID_WMV3 CODEC_ID_WMV3 <nl> # define AV_CODEC_ID_LOCO CODEC_ID_LOCO <nl> # define AV_CODEC_ID_THEORA CODEC_ID_THEORA <nl> - # define AV_CODEC_ID_WNV CODEC_ID_WNV <nl> + # define AV_CODEC_ID_WNV1 CODEC_ID_WNV1 <nl> # define AV_CODEC_ID_AASC CODEC_ID_AASC <nl> # define AV_CODEC_ID_INDEO2 CODEC_ID_INDEO2 <nl> # define AV_CODEC_ID_FRAPS CODEC_ID_FRAPS <nl>
get code to compile on Ubuntu Saucy
opencv/opencv
50842b90363efbe2ec16c899a0295cdab9f5ea85
2015-06-09T12:53:08Z
mmm a / project / BuildDependencies / scripts / libsdl_d . bat <nl> ppp b / project / BuildDependencies / scripts / libsdl_d . bat <nl> copy SDL_image - 1 . 2 . 10 \ include \ SDL_image . h " % CUR_PATH % \ include \ SDL \ " <nl> copy SDL_image - 1 . 2 . 10 \ lib \ * . dll " % XBMC_PATH % \ tools \ TexturePacker \ " <nl> copy SDL_image - 1 . 2 . 10 \ lib \ SDL_image . lib " % CUR_PATH % \ lib \ SDL_image . lib " / Y <nl> <nl> + rem for debugging <nl> + copy SDL - 1 . 2 . 14 \ lib \ SDL . dll " % XBMC_PATH % \ project \ VS2010Express \ XBMC \ Debug ( DirectX ) \ " / Y <nl> + <nl> cd % LOC_PATH % <nl> \ No newline at end of file <nl> deleted file mode 100644 <nl> index c360194f6503 . . 000000000000 <nl> mmm a / project / BuildDependencies / scripts / python2 . 6_d . txt <nl> ppp / dev / null <nl> <nl> - ; filename source of the file <nl> - python2 . 6 . 6 . 7z http : / / xbmcwindeps . googlecode . com / files <nl> similarity index 64 % <nl> rename from project / BuildDependencies / scripts / python2 . 6_d . bat <nl> rename to project / BuildDependencies / scripts / python_d . bat <nl> mmm a / project / BuildDependencies / scripts / python2 . 6_d . bat <nl> ppp b / project / BuildDependencies / scripts / python_d . bat <nl> <nl> @ ECHO ON <nl> <nl> SET LOC_PATH = % CD % <nl> - SET FILES = % LOC_PATH % \ python2 . 6_d . txt <nl> + SET FILES = % LOC_PATH % \ python_d . txt <nl> <nl> - CALL dlextract . bat python2 . 6 % FILES % <nl> + CALL dlextract . bat python % FILES % <nl> <nl> cd % TMP_PATH % <nl> <nl> if " % DEBUG % " = = " false " ( <nl> xcopy python2 . 6 . 6 \ include \ * " % CUR_PATH % \ include \ python " / E / Q / I / Y / EXCLUDE : py_exclude . txt <nl> xcopy python2 . 6 . 6 \ python \ DLLs " % XBMC_PATH % \ system \ python \ DLLs " / E / Q / I / Y / EXCLUDE : py_exclude . txt <nl> xcopy python2 . 6 . 6 \ python \ Lib " % XBMC_PATH % \ system \ python \ Lib " / E / Q / I / Y / EXCLUDE : py_exclude . txt <nl> - xcopy python2 . 6 . 6 \ python26 . dll " % XBMC_PATH % \ system \ python \ " / Q / I / Y / EXCLUDE : py_exclude . txt <nl> - xcopy python2 . 6 . 6 \ python26_d . dll " % XBMC_PATH % \ system \ python \ " / Q / I / Y / EXCLUDE : py_exclude . txt <nl> + xcopy python2 . 6 . 6 \ python26 . dll " % XBMC_PATH % \ project \ Win32BuildSetup \ dependencies \ " / Q / I / Y / EXCLUDE : py_exclude . txt <nl> xcopy python2 . 6 . 6 \ libs \ * . lib " % CUR_PATH % \ lib \ " / E / Q / I / Y / EXCLUDE : py_exclude . txt <nl> xcopy python2 . 6 . 6 \ libs \ * . pdb " % CUR_PATH % \ lib \ " / E / Q / I / Y / EXCLUDE : py_exclude . txt <nl> <nl> + rem for debugging <nl> + xcopy python2 . 6 . 6 \ python26 . dll " % XBMC_PATH % \ project \ VS2010Express \ XBMC \ Debug ( DirectX ) \ " / Q / I / Y / EXCLUDE : py_exclude . txt <nl> + xcopy python2 . 6 . 6 \ python26_d . dll " % XBMC_PATH % \ project \ VS2010Express \ XBMC \ Debug ( DirectX ) \ " / Q / I / Y / EXCLUDE : py_exclude . txt <nl> + <nl> cd % LOC_PATH % <nl> new file mode 100644 <nl> index 000000000000 . . 1c1597944519 <nl> mmm / dev / null <nl> ppp b / project / BuildDependencies / scripts / python_d . txt <nl> <nl> + ; filename source of the file <nl> + python2 . 6 . 6 . 7z http : / / mirrors . xbmc . org / build - deps / win32 / <nl> mmm a / project / VS2010Express / XBMC . vcxproj <nl> ppp b / project / VS2010Express / XBMC . vcxproj <nl> <nl> < InlineFunctionExpansion > Default < / InlineFunctionExpansion > <nl> < FavorSizeOrSpeed > Speed < / FavorSizeOrSpeed > <nl> < OmitFramePointers > true < / OmitFramePointers > <nl> - < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ win32 \ ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ Python \ PC ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> - < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; NDEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_GL ; __STDC_CONSTANT_MACROS ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ win32 \ ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> + < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; NDEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_GL ; __STDC_CONSTANT_MACROS ; USE_EXTERNAL_PYTHON ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < StringPooling > false < / StringPooling > <nl> < MinimalRebuild > false < / MinimalRebuild > <nl> < ExceptionHandling > Async < / ExceptionHandling > <nl> <nl> < ClCompile > <nl> < Optimization > Disabled < / Optimization > <nl> < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ cores ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ xbmc \ dialogs ; . . \ . . \ xbmc \ FileSystem ; . . \ . . \ xbmc \ guilib \ ; . . \ . . \ xbmc \ utils ; . . \ . . \ xbmc \ win32 ; . . \ . . \ xbmc \ windowing ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ libflac \ flac - 1 . 2 . 1 \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libsamplerate \ src ; . . \ . . \ lib \ win32 \ libssh_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ sqlite ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> - < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; _DEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_DX ; Py_NO_ENABLE_SHARED ; USE_EXTERNAL_PYTHON ; D3D_DEBUG_INFO ; __STDC_CONSTANT_MACROS ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; _DEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_DX ; USE_EXTERNAL_PYTHON ; D3D_DEBUG_INFO ; __STDC_CONSTANT_MACROS ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < MinimalRebuild > true < / MinimalRebuild > <nl> < ExceptionHandling > Async < / ExceptionHandling > <nl> < BasicRuntimeChecks > Default < / BasicRuntimeChecks > <nl> <nl> < InlineFunctionExpansion > Default < / InlineFunctionExpansion > <nl> < FavorSizeOrSpeed > Speed < / FavorSizeOrSpeed > <nl> < OmitFramePointers > true < / OmitFramePointers > <nl> - < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ win32 \ ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ Python \ PC ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> - < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; NDEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_DX ; __STDC_CONSTANT_MACROS ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ win32 \ ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> + < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; NDEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_DX ; USE_EXTERNAL_PYTHON ; __STDC_CONSTANT_MACROS ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < StringPooling > false < / StringPooling > <nl> < MinimalRebuild > true < / MinimalRebuild > <nl> < ExceptionHandling > Async < / ExceptionHandling > <nl> <nl> < ItemDefinitionGroup Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > <nl> < ClCompile > <nl> < Optimization > Disabled < / Optimization > <nl> - < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ win32 \ ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ Python \ PC ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> - < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; _DEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_GL ; Py_NO_ENABLE_SHARED ; __STDC_CONSTANT_MACROS ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> + < AdditionalIncludeDirectories > . . \ . . \ ; . . \ . . \ xbmc \ ; . . \ . . \ xbmc \ win32 \ ; . . \ . . \ xbmc \ cores \ dvdplayer ; . . \ . . \ lib ; . . \ . . \ lib \ ffmpeg ; . . \ . . \ lib \ ffmpeg \ include - xbmc - win32 ; . . \ . . \ lib \ freetype \ include ; . . \ . . \ lib \ jsoncpp \ jsoncpp \ include ; . . \ . . \ lib \ liblame \ include ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaRenderer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaConnect ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Devices \ MediaServer ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Platinum ; . . \ . . \ lib \ libUPnP \ Platinum \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ Core ; . . \ . . \ lib \ libUPnP \ Neptune \ Source \ System \ Win32 ; . . \ . . \ lib \ win32 \ boost ; . . \ . . \ lib \ win32 \ libbluray_win32 ; . . \ . . \ lib \ win32 \ libcdio \ include ; . . \ . . \ lib \ win32 \ libiconv \ include ; . . \ . . \ lib \ win32 \ libmicrohttpd_win32 \ include ; . . \ . . \ lib \ win32 \ libwavpack ; . . \ . . \ lib \ win32 \ pcre ; . . \ . . \ lib \ win32 \ vorbisfile \ libvorbis \ include ; . . \ . . \ lib \ win32 \ vorbisfile \ ogg \ include ; . . \ . . \ lib \ jsoncpp \ include < / AdditionalIncludeDirectories > <nl> + < PreprocessorDefinitions > _WINDOWS ; _MSVC ; WIN32 ; _DEBUG ; _WIN32_WINNT = 0x0501 ; WINVER = 0x0500 ; NOMINMAX ; _USE_32BIT_TIME_T ; HAS_GL ; __STDC_CONSTANT_MACROS ; USE_EXTERNAL_PYTHON ; % ( PreprocessorDefinitions ) < / PreprocessorDefinitions > <nl> < MinimalRebuild > true < / MinimalRebuild > <nl> < ExceptionHandling > Async < / ExceptionHandling > <nl> < BasicRuntimeChecks > Default < / BasicRuntimeChecks > <nl> <nl> < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ json - rpc \ SystemOperations . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ json - rpc \ VideoLibrary . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ json - rpc \ XBMCOperations . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ action . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ control . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlbutton . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlcheckmark . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlfadelabel . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlgroup . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlimage . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controllabel . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controllist . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlprogress . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlradiobutton . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlslider . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlspin . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controltextbox . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ dialog . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindow . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindowDialog . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindowXML . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindowXMLDialog . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ infotagmusic . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ infotagvideo . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ keyboard . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ listitem . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ player . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ pyplaylist . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ PythonAddon . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ PythonPlayer . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ pyutil . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ window . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ winxml . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ winxmldialog . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcaddonmodule . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcguimodule . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcmodule . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcplugin . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcvfsmodule . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ XBPython . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ XBPyThread . cpp " / > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ action . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ control . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlbutton . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlcheckmark . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlfadelabel . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlgroup . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlimage . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controllabel . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controllist . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlprogress . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlradiobutton . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlslider . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controlspin . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ controltextbox . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ dialog . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindow . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindowDialog . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindowXML . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ GUIPythonWindowXMLDialog . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ infotagmusic . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ infotagvideo . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ keyboard . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ listitem . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ player . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ pyplaylist . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ PythonAddon . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ PythonPlayer . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ pyutil . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ window . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ winxml . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ winxmldialog . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcaddonmodule . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcguimodule . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcmodule . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcplugin . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ xbmcmodule \ xbmcvfsmodule . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ XBPython . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ interfaces \ python \ XBPyThread . cpp " > <nl> + < AdditionalIncludeDirectories Condition = " ' $ ( Configuration ) | $ ( Platform ) ' = = ' Debug ( OpenGL ) | Win32 ' " > . . \ . . \ project \ BuildDependencies \ include \ python ; % ( AdditionalIncludeDirectories ) < / AdditionalIncludeDirectories > <nl> + < / ClCompile > <nl> < ClCompile Include = " . . \ . . \ xbmc \ LangInfo . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ MediaSource . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ music \ Album . cpp " / > <nl> <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ strverscmp . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ Win32DelayedDllLoad . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WIN32Util . cpp " / > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WIN32XBPythonDll . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WINDirectSound . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WindowHelper . cpp " / > <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WINFileSMB . cpp " / > <nl> mmm a / project / VS2010Express / XBMC . vcxproj . filters <nl> ppp b / project / VS2010Express / XBMC . vcxproj . filters <nl> <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ strverscmp . cpp " > <nl> < Filter > win32 < / Filter > <nl> < / ClCompile > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ win32 \ Win32DelayedDllLoad . cpp " > <nl> - < Filter > win32 < / Filter > <nl> - < / ClCompile > <nl> < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WIN32Util . cpp " > <nl> < Filter > win32 < / Filter > <nl> < / ClCompile > <nl> <nl> < ClCompile Include = " . . \ . . \ xbmc \ XBDateTime . cpp " > <nl> < Filter > utils < / Filter > <nl> < / ClCompile > <nl> - < ClCompile Include = " . . \ . . \ xbmc \ win32 \ WIN32XBPythonDll . cpp " > <nl> - < Filter > interfaces \ python < / Filter > <nl> + < ClCompile Include = " . . \ . . \ xbmc \ win32 \ Win32DelayedDllLoad . cpp " > <nl> + < Filter > win32 < / Filter > <nl> < / ClCompile > <nl> < / ItemGroup > <nl> < ItemGroup > <nl> mmm a / xbmc / interfaces / python / XBPython . cpp <nl> ppp b / xbmc / interfaces / python / XBPython . cpp <nl> void XBPython : : Finalize ( ) <nl> Py_Finalize ( ) ; <nl> PyEval_ReleaseLock ( ) ; <nl> <nl> - # if ! ( defined ( __APPLE__ ) & & defined ( USE_EXTERNAL_PYTHON ) ) <nl> + # if ! ( ( defined ( __APPLE__ ) | | defined ( _WIN32 ) ) & & defined ( USE_EXTERNAL_PYTHON ) ) <nl> UnloadExtensionLibs ( ) ; <nl> # endif <nl> <nl> / / first free all dlls loaded by python , after that python24 . dll ( this is done by UnloadPythonDlls <nl> - # if ! ( defined ( __APPLE__ ) & & defined ( USE_EXTERNAL_PYTHON ) ) <nl> + # if ! ( ( defined ( __APPLE__ ) | | defined ( _WIN32 ) ) & & defined ( USE_EXTERNAL_PYTHON ) ) <nl> DllLoaderContainer : : UnloadPythonDlls ( ) ; <nl> # endif <nl> # if defined ( _LINUX ) & & ! ( defined ( __APPLE__ ) & & defined ( USE_EXTERNAL_PYTHON ) ) <nl> deleted file mode 100644 <nl> index 088909cdb249 . . 000000000000 <nl> mmm a / xbmc / win32 / WIN32XBPythonDll . cpp <nl> ppp / dev / null <nl> <nl> - / * <nl> - * Copyright ( C ) 2005 - 2008 Team XBMC <nl> - * http : / / www . xbmc . org <nl> - * <nl> - * This Program is free software ; you can redistribute it and / or modify <nl> - * it under the terms of the GNU General Public License as published by <nl> - * the Free Software Foundation ; either version 2 , or ( at your option ) <nl> - * any later version . <nl> - * <nl> - * This Program is distributed in the hope that it will be useful , <nl> - * but WITHOUT ANY WARRANTY ; without even the implied warranty of <nl> - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the <nl> - * GNU General Public License for more details . <nl> - * <nl> - * You should have received a copy of the GNU General Public License <nl> - * along with XBMC ; see the file COPYING . If not , write to <nl> - * the Free Software Foundation , 675 Mass Ave , Cambridge , MA 02139 , USA . <nl> - * http : / / www . gnu . org / copyleft / gpl . html <nl> - * <nl> - * / <nl> - <nl> - # include " interfaces / python / XBPythonDll . h " <nl> - # include " cores / DllLoader / DllLoader . h " <nl> - <nl> - template < byte count > <nl> - struct SVaPassNext { <nl> - SVaPassNext < count - 1 > big ; <nl> - DWORD dw ; <nl> - } ; <nl> - template < > struct SVaPassNext < 0 > { } ; <nl> - / / SVaPassNext - is generator of structure of any size at compile time . <nl> - <nl> - class CVaPassNext { <nl> - public : <nl> - SVaPassNext < 50 > svapassnext ; <nl> - CVaPassNext ( va_list & args ) { <nl> - try { / / to avoid access violation <nl> - memcpy ( & svapassnext , args , sizeof ( svapassnext ) ) ; <nl> - } catch ( . . . ) { } <nl> - } <nl> - } ; <nl> - # define va_pass ( valist ) CVaPassNext ( valist ) . svapassnext <nl> - <nl> - / / macro to make life a bit simpler <nl> - <nl> - # define DLL_FUNCTION ( function ) # function , ( void * * ) & p_ # # function <nl> - # define DLL_VA_FUNCTION ( function ) # function , ( void * * ) & p_va_ # # function <nl> - <nl> - / / use these if the dll exports pointers <nl> - # define DLL_POINTER_DATA ( data ) # data , ( void * * ) & data <nl> - # define DATA_POINTER ( data ) unsigned long data ; <nl> - <nl> - / / use these if the dll exports data structs <nl> - # define DLL_OBJECT_DATA ( data ) # data , ( void * * ) & pointer_ # # data <nl> - <nl> - # define _Py_NoneStruct ( * ( ( PyObject * ) pointer__Py_NoneStruct ) ) <nl> - # define PyString_Type ( * ( ( PyTypeObject * ) pointer_PyString_Type ) ) <nl> - # define PyList_Type ( * ( ( PyTypeObject * ) pointer_PyList_Type ) ) <nl> - # define PyLong_Type ( * ( ( PyTypeObject * ) pointer_PyLong_Type ) ) <nl> - # define PyInt_Type ( * ( ( PyTypeObject * ) pointer_PyInt_Type ) ) <nl> - # define PyUnicode_Type ( * ( ( PyTypeObject * ) pointer_PyUnicode_Type ) ) <nl> - # define PyTuple_Type ( * ( ( PyTypeObject * ) pointer_PyTuple_Type ) ) <nl> - # define PyDict_Type ( * ( ( PyTypeObject * ) pointer_PyDict_Type ) ) <nl> - <nl> - # define DLL_ORD_FUNCTION ( ord , function ) " hapdbg . dll " , ord , ( void * * ) & p_ # # function <nl> - <nl> - # define FUNCTION ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( ) ; \ <nl> - void * function ( ) { return p_ # # function ( ) ; } <nl> - <nl> - # define FUNCTION4 ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( void * a ) ; \ <nl> - void * function ( void * a ) { return p_ # # function ( a ) ; } <nl> - <nl> - # define FUNCTION8 ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( void * a , void * b ) ; \ <nl> - void * function ( void * a , void * b ) { return p_ # # function ( a , b ) ; } <nl> - <nl> - # define VA_FUNC_START ( x ) \ <nl> - void * ret ; \ <nl> - va_list va ; \ <nl> - va_start ( va , x ) ; \ <nl> - ret = <nl> - <nl> - # define VA_FUNC_END \ <nl> - va_end ( va ) ; \ <nl> - return ret ; <nl> - <nl> - # define VA_FUNCTION8 ( function ) \ <nl> - void * ( __cdecl * p_va_ # # function ) ( void * a , . . . ) ; \ <nl> - void * function ( void * a , . . . ) { VA_FUNC_START ( a ) p_va_ # # function ( a , va_pass ( va ) ) ; VA_FUNC_END } <nl> - <nl> - # define VA_FUNCTION12 ( function ) \ <nl> - void * ( __cdecl * p_va_ # # function ) ( void * a , void * b , . . . ) ; \ <nl> - void * function ( void * a , void * b , . . . ) { VA_FUNC_START ( b ) p_va_ # # function ( a , b , va_pass ( va ) ) ; VA_FUNC_END } <nl> - <nl> - # define VA_FUNCTION16 ( function ) \ <nl> - void * ( __cdecl * p_va_ # # function ) ( void * a , void * b , void * c , . . . ) ; \ <nl> - void * function ( void * a , void * b , void * c , . . . ) { VA_FUNC_START ( c ) p_va_ # # function ( a , b , c , va_pass ( va ) ) ; VA_FUNC_END } <nl> - <nl> - # define VA_FUNCTION20 ( function ) \ <nl> - void * ( __cdecl * p_va_ # # function ) ( void * a , void * b , void * c , void * d , . . . ) ; \ <nl> - void * function ( void * a , void * b , void * c , void * d , . . . ) { VA_FUNC_START ( d ) p_va_ # # function ( a , b , c , d , va_pass ( va ) ) ; VA_FUNC_END } <nl> - <nl> - # define FUNCTION12 ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( void * a , void * b , void * c ) ; \ <nl> - void * function ( void * a , void * b , void * c ) { return p_ # # function ( a , b , c ) ; } <nl> - <nl> - # define FUNCTION16 ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( void * a , void * b , void * c , void * d ) ; \ <nl> - void * function ( void * a , void * b , void * c , void * d ) { return p_ # # function ( a , b , c , d ) ; } <nl> - <nl> - # define FUNCTION20 ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( void * a , void * b , void * c , void * d , void * e ) ; \ <nl> - void * function ( void * a , void * b , void * c , void * d , void * e ) { return p_ # # function ( a , b , c , d , e ) ; } <nl> - <nl> - # define FUNCTION28 ( function ) \ <nl> - void * ( __cdecl * p_ # # function ) ( void * a , void * b , void * c , void * d , void * e , void * f , void * g ) ; \ <nl> - void * function ( void * a , void * b , void * c , void * d , void * e , void * f , void * g ) { return p_ # # function ( a , b , c , d , e , f , g ) ; } <nl> - <nl> - extern " C " <nl> - { <nl> - / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * <nl> - * python24 . dll <nl> - * / <nl> - <nl> - FUNCTION ( PyEval_ReleaseLock ) <nl> - FUNCTION ( PyEval_AcquireLock ) <nl> - FUNCTION ( PyThreadState_Get ) <nl> - FUNCTION4 ( PyRun_SimpleString ) <nl> - FUNCTION ( PyEval_InitThreads ) <nl> - FUNCTION ( PyEval_ThreadsInitialized ) <nl> - FUNCTION ( Py_Initialize ) <nl> - FUNCTION ( Py_IsInitialized ) <nl> - FUNCTION ( Py_Finalize ) <nl> - FUNCTION ( Py_NewInterpreter ) <nl> - FUNCTION4 ( Py_EndInterpreter ) <nl> - FUNCTION4 ( PyThreadState_Swap ) <nl> - FUNCTION8 ( PyErr_SetString ) <nl> - FUNCTION4 ( PyThreadState_New ) <nl> - FUNCTION ( PyErr_Print ) <nl> - FUNCTION ( PyErr_Occurred ) <nl> - FUNCTION8 ( PyRun_SimpleFile ) <nl> - FUNCTION4 ( PySys_SetPath ) <nl> - FUNCTION ( Py_GetPath ) <nl> - FUNCTION4 ( PyThreadState_Delete ) <nl> - FUNCTION4 ( PyThreadState_Clear ) <nl> - <nl> - VA_FUNCTION8 ( Py_BuildValue ) <nl> - / * void * Py_BuildValue ( void * a , . . . ) <nl> - { <nl> - void * ret ; <nl> - va_list va ; <nl> - va_start ( va , a ) ; <nl> - ret = Py_VaBuildValue ( a , va ) ; <nl> - va_end ( va ) ; <nl> - return ret ; <nl> - } * / <nl> - <nl> - VA_FUNCTION12 ( PyArg_Parse ) <nl> - VA_FUNCTION12 ( PyArg_ParseTuple ) <nl> - / * void * PyArg_ParseTuple ( void * a , void * b , . . . ) <nl> - { <nl> - void * ret ; <nl> - va_list va ; <nl> - va_start ( va , b ) ; <nl> - ret = PyArg_VaParse ( a , b , va ) ; <nl> - va_end ( va ) ; <nl> - return ret ; <nl> - } * / <nl> - <nl> - FUNCTION8 ( PyType_IsSubtype ) <nl> - VA_FUNCTION20 ( PyArg_ParseTupleAndKeywords ) <nl> - / * void * PyArg_ParseTupleAndKeywords ( void * a , void * b , void * c , void * d , . . . ) <nl> - { <nl> - void * ret ; <nl> - va_list va ; <nl> - va_start ( va , d ) ; <nl> - ret = PyArg_VaParseTupleAndKeywords ( a , b , c , d , va ) ; <nl> - va_end ( va ) ; <nl> - return ret ; <nl> - } * / <nl> - <nl> - FUNCTION4 ( PyString_AsString ) <nl> - FUNCTION8 ( Py_AddPendingCall ) <nl> - FUNCTION8 ( PyList_GetItem ) <nl> - FUNCTION4 ( PyList_Size ) <nl> - FUNCTION4 ( PyList_New ) <nl> - FUNCTION8 ( PyList_Append ) <nl> - FUNCTION4 ( _PyObject_New ) <nl> - FUNCTION4 ( PyLong_AsLong ) <nl> - FUNCTION4 ( PyLong_AsLongLong ) <nl> - <nl> - VA_FUNCTION12 ( PyErr_Format ) <nl> - / * void * PyErr_Format ( void * a , void * b , . . . ) <nl> - { <nl> - void * ret ; <nl> - va_list va ; <nl> - va_start ( va , b ) ; <nl> - ret = PyErr_VaFormat ( a , b , va ) ; <nl> - va_end ( va ) ; <nl> - return ret ; <nl> - } * / <nl> - # ifndef _LINUX <nl> - FUNCTION4 ( PyUnicodeUCS2_AsUTF8String ) <nl> - FUNCTION12 ( PyUnicodeUCS2_DecodeUTF8 ) <nl> - # else <nl> - FUNCTION4 ( PyUnicodeUCS4_AsUTF8String ) <nl> - FUNCTION12 ( PyUnicodeUCS4_DecodeUTF8 ) <nl> - # endif <nl> - FUNCTION ( Py_MakePendingCalls ) <nl> - FUNCTION ( PyEval_SaveThread ) <nl> - FUNCTION4 ( PyEval_RestoreThread ) <nl> - FUNCTION4 ( PyLong_FromLong ) <nl> - FUNCTION12 ( PyModule_AddStringConstant ) <nl> - FUNCTION12 ( PyModule_AddObject ) <nl> - # ifndef Py_TRACE_REFS <nl> - FUNCTION20 ( Py_InitModule4 ) <nl> - # else <nl> - FUNCTION20 ( Py_InitModule4TraceRefs ) <nl> - # endif <nl> - FUNCTION4 ( PyInt_AsLong ) <nl> - FUNCTION4 ( PyFloat_AsDouble ) <nl> - FUNCTION4 ( PyString_FromString ) <nl> - FUNCTION4 ( PyBool_FromLong ) <nl> - FUNCTION12 ( PyModule_AddIntConstant ) <nl> - <nl> - / / void * ( __cdecl * p_va_PyObject_CallFunction ) ( void * a , void * b , . . . ) ; <nl> - VA_FUNCTION12 ( PyObject_CallFunction ) / / va arg <nl> - / * <nl> - void * PyObject_CallFunction ( void * a , void * b , . . . ) <nl> - { <nl> - void * ret ; <nl> - va_list va ; <nl> - va_start ( va , b ) ; <nl> - ret = p_va_PyObject_CallFunction ( a , b , va_pass ( va ) ) ; <nl> - va_end ( va ) ; <nl> - return ret ; <nl> - } * / <nl> - <nl> - / / void * ( __cdecl * p_va_PyObject_CallMethod ) ( void * a , void * b , void * c , . . . ) ; <nl> - VA_FUNCTION16 ( PyObject_CallMethod ) <nl> - / * void * PyObject_CallMethod ( void * a , void * b , void * c , . . . ) <nl> - { <nl> - void * ret ; <nl> - va_list va ; <nl> - va_start ( va , c ) ; <nl> - ret = p_va_PyObject_CallMethod ( a , b , c , va_pass ( va ) ) ; <nl> - va_end ( va ) ; <nl> - return ret ; <nl> - } * / <nl> - FUNCTION12 ( PyDict_SetItemString ) <nl> - FUNCTION ( PyDict_New ) <nl> - FUNCTION4 ( PyModule_GetDict ) <nl> - FUNCTION4 ( PyImport_Import ) <nl> - FUNCTION4 ( PyInt_FromLong ) <nl> - FUNCTION8 ( PyDict_GetItemString ) <nl> - / / FUNCTION8 ( PyDict_GetItem ) <nl> - / / FUNCTION4 ( PyDict_Keys ) <nl> - FUNCTION16 ( PyDict_Next ) <nl> - FUNCTION4 ( PyDict_Size ) <nl> - FUNCTION4 ( PyType_Ready ) <nl> - FUNCTION12 ( PyType_GenericNew ) <nl> - FUNCTION4 ( PyTuple_New ) <nl> - FUNCTION12 ( PyTuple_SetItem ) <nl> - FUNCTION8 ( PySys_SetArgv ) <nl> - FUNCTION12 ( PyObject_RichCompare ) <nl> - FUNCTION12 ( PyErr_Fetch ) <nl> - FUNCTION4 ( PyImport_AddModule ) <nl> - FUNCTION4 ( PyImport_ImportModule ) <nl> - FUNCTION4 ( PyObject_Str ) <nl> - FUNCTION20 ( PyRun_File ) <nl> - FUNCTION16 ( PyRun_String ) <nl> - FUNCTION4 ( PyErr_ExceptionMatches ) <nl> - FUNCTION ( PyErr_Clear ) <nl> - FUNCTION12 ( PyObject_SetAttrString ) <nl> - <nl> - # ifdef Py_TRACE_REFS <nl> - FUNCTION12 ( _Py_NegativeRefcount ) <nl> - FUNCTION4 ( _Py_Dealloc ) <nl> - # endif <nl> - <nl> - # if ( defined HAVE_LIBPYTHON2_6 ) <nl> - FUNCTION8 ( PyRun_SimpleStringFlags ) <nl> - FUNCTION20 ( PyRun_StringFlags ) <nl> - FUNCTION28 ( PyRun_FileExFlags ) <nl> - # endif <nl> - <nl> - / / PyFloat_FromDouble ( double ) <nl> - void * ( __cdecl * p_PyFloat_FromDouble ) ( double a ) ; \ <nl> - void * PyFloat_FromDouble ( double a ) { return p_PyFloat_FromDouble ( a ) ; } <nl> - <nl> - DATA_OBJECT ( PyExc_SystemExit ) <nl> - DATA_OBJECT ( PyExc_SystemError ) <nl> - DATA_OBJECT ( PyExc_ValueError ) <nl> - DATA_OBJECT ( PyExc_Exception ) <nl> - DATA_OBJECT ( PyExc_TypeError ) <nl> - DATA_OBJECT ( PyExc_KeyboardInterrupt ) <nl> - DATA_OBJECT ( PyExc_RuntimeError ) <nl> - DATA_OBJECT ( PyExc_ReferenceError ) <nl> - <nl> - DATA_OBJECT ( _Py_NoneStruct ) <nl> - DATA_OBJECT ( _Py_NotImplementedStruct ) <nl> - DATA_OBJECT ( _Py_TrueStruct ) <nl> - DATA_OBJECT ( _Py_ZeroStruct ) <nl> - DATA_OBJECT ( PyString_Type ) <nl> - DATA_OBJECT ( PyList_Type ) <nl> - DATA_OBJECT ( PyLong_Type ) <nl> - DATA_OBJECT ( PyInt_Type ) <nl> - DATA_OBJECT ( PyUnicode_Type ) <nl> - DATA_OBJECT ( PyTuple_Type ) <nl> - DATA_OBJECT ( PyDict_Type ) <nl> - <nl> - # ifdef Py_TRACE_REFS <nl> - DATA_OBJECT ( _Py_RefTotal ) <nl> - # endif <nl> - <nl> - bool python_load_dll ( LibraryLoader & dll ) <nl> - { <nl> - bool bResult ; <nl> - <nl> - bResult = ( <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyEval_ReleaseLock ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyEval_AcquireLock ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyThreadState_Get ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_SimpleString ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyEval_InitThreads ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyEval_ThreadsInitialized ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_Initialize ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_IsInitialized ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_Finalize ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_NewInterpreter ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_EndInterpreter ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyThreadState_Swap ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyErr_SetString ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyThreadState_New ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyErr_Print ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyErr_Occurred ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_SimpleFile ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PySys_SetPath ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_GetPath ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyThreadState_Delete ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyThreadState_Clear ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( Py_BuildValue ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyType_IsSubtype ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( PyArg_ParseTupleAndKeywords ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyString_AsString ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_AddPendingCall ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( PyObject_CallMethod ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyList_GetItem ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyList_Size ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyList_New ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyList_Append ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( _PyObject_New ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyLong_AsLong ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyLong_AsLongLong ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( PyErr_Format ) ) & & <nl> - # ifndef _LINUX <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyUnicodeUCS2_AsUTF8String ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyUnicodeUCS2_DecodeUTF8 ) ) & & <nl> - # else <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyUnicodeUCS4_AsUTF8String ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyUnicodeUCS4_DecodeUTF8 ) ) & & <nl> - # endif <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_MakePendingCalls ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyEval_SaveThread ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyEval_RestoreThread ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyLong_FromLong ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyModule_AddStringConstant ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyModule_AddObject ) ) & & <nl> - # ifndef Py_TRACE_REFS <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_InitModule4 ) ) & & <nl> - # else <nl> - dll . ResolveExport ( DLL_FUNCTION ( Py_InitModule4TraceRefs ) ) & & <nl> - # endif <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyInt_AsLong ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyFloat_AsDouble ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyString_FromString ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyBool_FromLong ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyModule_AddIntConstant ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( PyObject_CallFunction ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyDict_SetItemString ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyDict_New ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyModule_GetDict ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyImport_Import ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyFloat_FromDouble ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyInt_FromLong ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyDict_GetItemString ) ) & & <nl> - / / dll . ResolveExport ( DLL_FUNCTION ( PyDict_GetItem ) ) & & <nl> - / / dll . ResolveExport ( DLL_FUNCTION ( PyDict_Keys ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyDict_Next ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyDict_Size ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyType_Ready ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyType_GenericNew ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyTuple_New ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyTuple_SetItem ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( PyArg_Parse ) ) & & <nl> - dll . ResolveExport ( DLL_VA_FUNCTION ( PyArg_ParseTuple ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PySys_SetArgv ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyObject_RichCompare ) ) & & <nl> - <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_SystemExit ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_SystemError ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_ValueError ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_Exception ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_TypeError ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_KeyboardInterrupt ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_RuntimeError ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyExc_ReferenceError ) ) & & <nl> - <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( _Py_NoneStruct ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( _Py_NotImplementedStruct ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( _Py_TrueStruct ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( _Py_ZeroStruct ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyString_Type ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyList_Type ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyLong_Type ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyInt_Type ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyUnicode_Type ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyTuple_Type ) ) & & <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( PyDict_Type ) ) & & <nl> - # ifdef Py_TRACE_REFS <nl> - dll . ResolveExport ( DLL_OBJECT_DATA ( _Py_RefTotal ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( _Py_NegativeRefcount ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( _Py_Dealloc ) ) & & <nl> - # endif <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyErr_Fetch ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyImport_AddModule ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyImport_ImportModule ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyObject_Str ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_File ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyErr_Clear ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyObject_SetAttrString ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyErr_ExceptionMatches ) ) & & <nl> - # if ( defined HAVE_LIBPYTHON2_6 ) <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_SimpleStringFlags ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_StringFlags ) ) & & <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_FileExFlags ) ) & & <nl> - # endif <nl> - dll . ResolveExport ( DLL_FUNCTION ( PyRun_String ) ) ) ; <nl> - <nl> - return bResult ; <nl> - } <nl> - } <nl>
Adding external python to the win32 build system . credit to WiSo and blinkseb .
xbmc/xbmc
7f63a5e3df00db9703d68be8a9fafba16bafe472
2011-04-06T17:43:43Z
mmm a / README . md <nl> ppp b / README . md <nl> <nl> # Caffe2 <nl> <nl> [ ! [ License ] ( https : / / img . shields . io / badge / License - Apache % 202 . 0 - brightgreen . svg ) ] ( https : / / opensource . org / licenses / Apache - 2 . 0 ) <nl> - [ ! [ TravisCI Build Status ] ( https : / / img . shields . io / travis / caffe2 / caffe2 . svg ) ] ( https : / / travis - ci . org / caffe2 / caffe2 ) <nl> + [ ! [ Jenkins Build Status ] ( https : / / ci . pytorch . org / jenkins / job / caffe2 - master / badge / icon ) ] ( https : / / ci . pytorch . org / jenkins / job / caffe2 - master ) <nl> [ ! [ Appveyor Build Status ] ( https : / / img . shields . io / appveyor / ci / Yangqing / caffe2 . svg ) ] ( https : / / ci . appveyor . com / project / Yangqing / caffe2 ) <nl> <nl> Caffe2 is a lightweight , modular , and scalable deep learning framework . Building on the original [ Caffe ] ( http : / / caffe . berkeleyvision . org ) , Caffe2 is designed with expression , speed , and modularity in mind . <nl>
Use Jenkins build status badge
pytorch/pytorch
31c3766d5a31293774e0b8682df344d0209e5398
2017-12-15T18:23:34Z
mmm a / tensorflow / tensorboard / backend / server_test . py <nl> ppp b / tensorflow / tensorboard / backend / server_test . py <nl> def _GenerateProjectorTestData ( self , run_path ) : <nl> # Write a projector config file in run1 . <nl> config_path = os . path . join ( run_path , ' projector_config . pbtxt ' ) <nl> config = ProjectorConfig ( ) <nl> + embedding = config . embeddings . add ( ) <nl> + # Add an embedding by its canonical tensor name . <nl> + embedding . tensor_name = ' var1 : 0 ' <nl> config_pbtxt = text_format . MessageToString ( config ) <nl> with tf . gfile . GFile ( config_path , ' w ' ) as f : <nl> f . write ( config_pbtxt ) <nl> mmm a / tensorflow / tensorboard / plugins / projector / plugin . py <nl> ppp b / tensorflow / tensorboard / plugins / projector / plugin . py <nl> def _run_paths_changed ( self ) : <nl> <nl> def _augment_configs_with_checkpoint_info ( self ) : <nl> for run , config in self . _configs . items ( ) : <nl> - # Find the size of the embeddings that are associated with a tensor file . <nl> for embedding in config . embeddings : <nl> + # Normalize the name of the embeddings . <nl> + if embedding . tensor_name . endswith ( ' : 0 ' ) : <nl> + embedding . tensor_name = embedding . tensor_name [ : - 2 ] <nl> + # Find the size of embeddings associated with a tensors file . <nl> if embedding . tensor_path and not embedding . tensor_shape : <nl> tensor = _read_tensor_file ( embedding . tensor_path ) <nl> embedding . tensor_shape . extend ( [ len ( tensor ) , len ( tensor [ 0 ] ) ] ) <nl>
Embedding Projector : Send readable tensor names to client .
tensorflow/tensorflow
c40efbdd377f157297c37d5f2d3fec45e775fdb0
2016-11-14T20:35:27Z
mmm a / tensorflow / compiler / mlir / runlit . site . cfg . py <nl> ppp b / tensorflow / compiler / mlir / runlit . site . cfg . py <nl> <nl> config . llvm_tools_dir = os . path . join ( os . environ [ ' TEST_SRCDIR ' ] , ' llvm - project ' , <nl> ' llvm ' ) <nl> config . mlir_obj_root = os . path . join ( os . environ [ ' TEST_SRCDIR ' ] ) <nl> - config . mlir_tools_dir = os . path . join ( os . environ [ ' TEST_SRCDIR ' ] , ' lllvm - project ' , <nl> + config . mlir_tools_dir = os . path . join ( os . environ [ ' TEST_SRCDIR ' ] , ' llvm - project ' , <nl> ' mlir ' ) <nl> # TODO ( jpienaar ) : Replace with suffices in build rule . <nl> config . suffixes = [ ' . td ' , ' . mlir ' , ' . pbtxt ' ] <nl> mmm a / tensorflow / python / lib / core / pybind11_absl . h <nl> ppp b / tensorflow / python / lib / core / pybind11_absl . h <nl> limitations under the License . <nl> # ifndef TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_ABSL_H_ <nl> # define TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_ABSL_H_ <nl> <nl> - # include " pybind11 / pybind11 . h " <nl> + # include " include / pybind11 / pybind11 . h " <nl> # include " tensorflow / core / platform / stringpiece . h " <nl> <nl> # ifndef ABSL_USES_STD_STRING_VIEW <nl> mmm a / tensorflow / python / lib / core / pybind11_lib . h <nl> ppp b / tensorflow / python / lib / core / pybind11_lib . h <nl> See the License for the specific language governing permissions and <nl> limitations under the License . <nl> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = * / <nl> <nl> - # include " pybind11 / pybind11 . h " <nl> - # include " pybind11 / pytypes . h " <nl> + # include " include / pybind11 / pybind11 . h " <nl> + # include " include / pybind11 / pytypes . h " <nl> <nl> # ifndef TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_LIB_H_ <nl> # define TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_LIB_H_ <nl> mmm a / tensorflow / python / lib / core / pybind11_proto . h <nl> ppp b / tensorflow / python / lib / core / pybind11_proto . h <nl> limitations under the License . <nl> # define TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_PROTO_H_ <nl> <nl> # include " absl / strings / str_cat . h " <nl> - # include " pybind11 / pybind11 . h " <nl> + # include " include / pybind11 / pybind11 . h " <nl> <nl> namespace tensorflow { <nl> <nl> mmm a / tensorflow / python / lib / core / pybind11_status . h <nl> ppp b / tensorflow / python / lib / core / pybind11_status . h <nl> limitations under the License . <nl> <nl> # include < Python . h > <nl> <nl> - # include " pybind11 / pybind11 . h " <nl> + # include " include / pybind11 / pybind11 . h " <nl> # include " tensorflow / c / tf_status . h " <nl> # include " tensorflow / core / lib / core / status . h " <nl> # include " tensorflow / core / protobuf / error_codes . pb . h " <nl> mmm a / third_party / mlir / BUILD <nl> ppp b / third_party / mlir / BUILD <nl> package ( default_visibility = [ " : friends " ] ) <nl> <nl> package_group ( <nl> name = " subpackages " , <nl> - packages = [ " / / . . . " ] , <nl> + packages = [ " / / third_party / llvm / llvm / projects / google_mlir / . . . " ] , <nl> ) <nl> <nl> # In particular the OWNERS file of the dependent project should be updated . <nl> package_group ( <nl> package_group ( <nl> name = " friends " , <nl> includes = [ " @ org_tensorflow / / tensorflow / compiler / mlir : subpackages " ] , <nl> - packages = [ <nl> - " / / . . . " , <nl> - " / / learning / brain / research / sair / . . . " , <nl> - " / / learning / brain / swift / swift_mlir / . . . " , <nl> - " / / learning / glassbox / evaluation / compiler / . . . " , <nl> - " / / tensorflow / compiler / mlir / tfrt / . . . " , <nl> - " / / tensorflow / core / tfrt_delegate / . . . " , <nl> - " / / tensorflow / lite / experimental / tf_runtime / . . . " , <nl> - " / / third_party / tf_runtime_google / . . . " , <nl> - ] , <nl> + packages = [ " / / . . . " ] , <nl> ) <nl> <nl> exports_files ( [ <nl>
Internal build change
tensorflow/tensorflow
3a094e6d1c927967438c0b263db0bf42d16813ae
2019-12-30T15:59:44Z
mmm a / spec / chromium - spec . coffee <nl> ppp b / spec / chromium - spec . coffee <nl> describe ' chromium feature ' , - > <nl> b . close ( ) <nl> done ( if opener isnt null then undefined else opener ) <nl> <nl> + describe ' window . opener . postMessage ' , - > <nl> + it ' sets source and origin correctly ' , ( done ) - > <nl> + b = window . open " file : / / # { fixtures } / pages / window - opener - postMessage . html " , ' test ' , ' show = no ' <nl> + window . addEventListener ' message ' , ( event ) - > <nl> + b . close ( ) <nl> + assert . equal event . source . guestId , b . guestId <nl> + assert . equal event . origin , ' file : / / ' <nl> + done ( ) <nl> + <nl> describe ' creating a Uint8Array under browser side ' , - > <nl> it ' does not crash ' , - > <nl> RUint8Array = remote . getGlobal ' Uint8Array ' <nl> new file mode 100644 <nl> index 000000000000 . . 5d0f8ede6d37 <nl> mmm / dev / null <nl> ppp b / spec / fixtures / pages / window - opener - postMessage . html <nl> <nl> + < html > <nl> + < body > <nl> + < script type = " text / javascript " charset = " utf - 8 " > <nl> + window . opener . postMessage ( ' message ' , ' * ' ) ; <nl> + < / script > <nl> + < / body > <nl> + < / html > <nl>
spec : window . opener . postMessage should set source and origin
electron/electron
c70513f7ce2f3773d869ea53bd3c547ce8c34067
2015-09-01T04:15:00Z
new file mode 100644 <nl> index 00000000000 . . aa655b53788 <nl> mmm / dev / null <nl> ppp b / modules / tools / extractor / extractor . py <nl> <nl> + # ! / usr / bin / env python <nl> + <nl> + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> + # Copyright 2017 The Apollo Authors . All Rights Reserved . <nl> + # <nl> + # Licensed under the Apache License , Version 2 . 0 ( the " License " ) ; <nl> + # you may not use this file except in compliance with the License . <nl> + # You may obtain a copy of the License at <nl> + # <nl> + # http : / / www . apache . org / licenses / LICENSE - 2 . 0 <nl> + # <nl> + # Unless required by applicable law or agreed to in writing , software <nl> + # distributed under the License is distributed on an " AS IS " BASIS , <nl> + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . <nl> + # See the License for the specific language governing permissions and <nl> + # limitations under the License . <nl> + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # <nl> + <nl> + import rospy <nl> + from std_msgs . msg import String <nl> + from modules . planning . proto . planning_pb2 import ADCTrajectory <nl> + from modules . routing . proto . routing_pb2 import RoutingResponse <nl> + <nl> + <nl> + class Extractor ( object ) : <nl> + <nl> + def __init__ ( self ) : <nl> + self . routing = rospy . Publisher ( <nl> + ' / apollo / routing_response ' , RoutingResponse , queue_size = 1 ) <nl> + <nl> + def callback_planning ( self , data ) : <nl> + self . routing . publish ( data . debug . planning_data . routing ) <nl> + print " New Planning " <nl> + <nl> + <nl> + def main ( ) : <nl> + " " " <nl> + Main function <nl> + " " " <nl> + extract = Extractor ( ) <nl> + rospy . init_node ( ' extract_routing ' , anonymous = True ) <nl> + planning_sub = rospy . Subscriber ( <nl> + ' / apollo / planning ' , <nl> + ADCTrajectory , <nl> + extract . callback_planning , <nl> + queue_size = 1 ) <nl> + rospy . spin ( ) <nl> + <nl> + <nl> + if __name__ = = ' __main__ ' : <nl> + main ( ) <nl>
Add tool to extract routing from planning debug
ApolloAuto/apollo
189ec6dabc25eb91335568a7e6547483f9ec2960
2017-08-22T23:25:02Z
mmm a / src / value - serializer . cc <nl> ppp b / src / value - serializer . cc <nl> <nl> # include " src / base / logging . h " <nl> # include " src / conversions . h " <nl> # include " src / factory . h " <nl> + # include " src / flags . h " <nl> # include " src / handles - inl . h " <nl> # include " src / isolate . h " <nl> # include " src / objects - inl . h " <nl> # include " src / objects . h " <nl> + # include " src / snapshot / code - serializer . h " <nl> # include " src / transitions . h " <nl> + # include " src / wasm / wasm - module . h " <nl> + # include " src / wasm / wasm - result . h " <nl> <nl> namespace v8 { <nl> namespace internal { <nl> enum class SerializationTag : uint8_t { <nl> kArrayBufferView = ' V ' , <nl> / / Shared array buffer ( transferred ) . transferID : uint32_t <nl> kSharedArrayBufferTransfer = ' u ' , <nl> + / / Compiled WebAssembly module . encodingType : ( one - byte tag ) . <nl> + / / If encodingType = = ' y ' ( raw bytes ) : <nl> + / / wasmWireByteLength : uint32_t , then raw data <nl> + / / compiledDataLength : uint32_t , then raw data <nl> + kWasmModule = ' W ' , <nl> } ; <nl> <nl> namespace { <nl> enum class ArrayBufferViewTag : uint8_t { <nl> kDataView = ' ? ' , <nl> } ; <nl> <nl> + enum class WasmEncodingTag : uint8_t { <nl> + kRawBytes = ' y ' , <nl> + } ; <nl> + <nl> } / / namespace <nl> <nl> ValueSerializer : : ValueSerializer ( Isolate * isolate , <nl> Maybe < bool > ValueSerializer : : WriteJSReceiver ( Handle < JSReceiver > receiver ) { <nl> case JS_OBJECT_TYPE : <nl> case JS_API_OBJECT_TYPE : { <nl> Handle < JSObject > js_object = Handle < JSObject > : : cast ( receiver ) ; <nl> - return js_object - > GetInternalFieldCount ( ) ? WriteHostObject ( js_object ) <nl> - : WriteJSObject ( js_object ) ; <nl> + Map * map = js_object - > map ( ) ; <nl> + if ( FLAG_expose_wasm & & <nl> + map - > GetConstructor ( ) = = <nl> + isolate_ - > native_context ( ) - > wasm_module_constructor ( ) ) { <nl> + return WriteWasmModule ( js_object ) ; <nl> + } else if ( JSObject : : GetInternalFieldCount ( map ) ) { <nl> + return WriteHostObject ( js_object ) ; <nl> + } else { <nl> + return WriteJSObject ( js_object ) ; <nl> + } <nl> } <nl> case JS_SPECIAL_API_OBJECT_TYPE : <nl> return WriteHostObject ( Handle < JSObject > : : cast ( receiver ) ) ; <nl> Maybe < bool > ValueSerializer : : WriteJSArrayBufferView ( JSArrayBufferView * view ) { <nl> return Just ( true ) ; <nl> } <nl> <nl> + Maybe < bool > ValueSerializer : : WriteWasmModule ( Handle < JSObject > object ) { <nl> + Handle < wasm : : WasmCompiledModule > compiled_part ( <nl> + wasm : : WasmCompiledModule : : cast ( object - > GetInternalField ( 0 ) ) , isolate_ ) ; <nl> + WasmEncodingTag encoding_tag = WasmEncodingTag : : kRawBytes ; <nl> + WriteTag ( SerializationTag : : kWasmModule ) ; <nl> + WriteRawBytes ( & encoding_tag , sizeof ( encoding_tag ) ) ; <nl> + <nl> + Handle < String > wire_bytes = compiled_part - > module_bytes ( ) ; <nl> + int wire_bytes_length = wire_bytes - > length ( ) ; <nl> + WriteVarint < uint32_t > ( wire_bytes_length ) ; <nl> + uint8_t * destination = ReserveRawBytes ( wire_bytes_length ) ; <nl> + String : : WriteToFlat ( * wire_bytes , destination , 0 , wire_bytes_length ) ; <nl> + <nl> + std : : unique_ptr < ScriptData > script_data = <nl> + WasmCompiledModuleSerializer : : SerializeWasmModule ( isolate_ , <nl> + compiled_part ) ; <nl> + int script_data_length = script_data - > length ( ) ; <nl> + WriteVarint < uint32_t > ( script_data_length ) ; <nl> + WriteRawBytes ( script_data - > data ( ) , script_data_length ) ; <nl> + <nl> + return Just ( true ) ; <nl> + } <nl> + <nl> Maybe < bool > ValueSerializer : : WriteHostObject ( Handle < JSObject > object ) { <nl> if ( ! delegate_ ) { <nl> isolate_ - > Throw ( * isolate_ - > factory ( ) - > NewError ( <nl> MaybeHandle < Object > ValueDeserializer : : ReadObjectInternal ( ) { <nl> const bool is_shared = true ; <nl> return ReadTransferredJSArrayBuffer ( is_shared ) ; <nl> } <nl> + case SerializationTag : : kWasmModule : <nl> + return ReadWasmModule ( ) ; <nl> default : <nl> / / TODO ( jbroman ) : Introduce an explicit tag for host objects to avoid <nl> / / having to treat every unknown tag as a potential host object . <nl> MaybeHandle < JSArrayBufferView > ValueDeserializer : : ReadJSArrayBufferView ( <nl> return typed_array ; <nl> } <nl> <nl> + MaybeHandle < JSObject > ValueDeserializer : : ReadWasmModule ( ) { <nl> + if ( ! FLAG_expose_wasm ) return MaybeHandle < JSObject > ( ) ; <nl> + <nl> + Vector < const uint8_t > encoding_tag ; <nl> + if ( ! ReadRawBytes ( sizeof ( WasmEncodingTag ) ) . To ( & encoding_tag ) | | <nl> + encoding_tag [ 0 ] ! = static_cast < uint8_t > ( WasmEncodingTag : : kRawBytes ) ) { <nl> + return MaybeHandle < JSObject > ( ) ; <nl> + } <nl> + <nl> + / / Extract the data from the buffer : wasm wire bytes , followed by V8 compiled <nl> + / / script data . <nl> + static_assert ( sizeof ( int ) < = sizeof ( uint32_t ) , <nl> + " max int must fit in uint32_t " ) ; <nl> + const uint32_t max_valid_size = std : : numeric_limits < int > : : max ( ) ; <nl> + uint32_t wire_bytes_length = 0 ; <nl> + Vector < const uint8_t > wire_bytes ; <nl> + uint32_t compiled_bytes_length = 0 ; <nl> + Vector < const uint8_t > compiled_bytes ; <nl> + if ( ! ReadVarint < uint32_t > ( ) . To ( & wire_bytes_length ) | | <nl> + wire_bytes_length > max_valid_size | | <nl> + ! ReadRawBytes ( wire_bytes_length ) . To ( & wire_bytes ) | | <nl> + ! ReadVarint < uint32_t > ( ) . To ( & compiled_bytes_length ) | | <nl> + compiled_bytes_length > max_valid_size | | <nl> + ! ReadRawBytes ( compiled_bytes_length ) . To ( & compiled_bytes ) ) { <nl> + return MaybeHandle < JSObject > ( ) ; <nl> + } <nl> + <nl> + / / Try to deserialize the compiled module first . <nl> + ScriptData script_data ( compiled_bytes . start ( ) , compiled_bytes . length ( ) ) ; <nl> + Handle < FixedArray > compiled_part ; <nl> + if ( WasmCompiledModuleSerializer : : DeserializeWasmModule ( <nl> + isolate_ , & script_data , wire_bytes ) <nl> + . ToHandle ( & compiled_part ) ) { <nl> + return wasm : : CreateWasmModuleObject ( <nl> + isolate_ , Handle < wasm : : WasmCompiledModule > : : cast ( compiled_part ) , <nl> + wasm : : ModuleOrigin : : kWasmOrigin ) ; <nl> + } <nl> + <nl> + / / If that fails , recompile . <nl> + wasm : : ErrorThrower thrower ( isolate_ , " ValueDeserializer : : ReadWasmModule " ) ; <nl> + return wasm : : CreateModuleObjectFromBytes ( <nl> + isolate_ , wire_bytes . begin ( ) , wire_bytes . end ( ) , & thrower , <nl> + wasm : : ModuleOrigin : : kWasmOrigin , Handle < Script > : : null ( ) , nullptr , <nl> + nullptr ) ; <nl> + } <nl> + <nl> MaybeHandle < JSObject > ValueDeserializer : : ReadHostObject ( ) { <nl> if ( ! delegate_ ) return MaybeHandle < JSObject > ( ) ; <nl> STACK_CHECK ( isolate_ , MaybeHandle < JSObject > ( ) ) ; <nl> mmm a / src / value - serializer . h <nl> ppp b / src / value - serializer . h <nl> class ValueSerializer { <nl> Maybe < bool > WriteJSSet ( Handle < JSSet > map ) WARN_UNUSED_RESULT ; <nl> Maybe < bool > WriteJSArrayBuffer ( JSArrayBuffer * array_buffer ) ; <nl> Maybe < bool > WriteJSArrayBufferView ( JSArrayBufferView * array_buffer ) ; <nl> + Maybe < bool > WriteWasmModule ( Handle < JSObject > object ) WARN_UNUSED_RESULT ; <nl> Maybe < bool > WriteHostObject ( Handle < JSObject > object ) WARN_UNUSED_RESULT ; <nl> <nl> / * <nl> class ValueDeserializer { <nl> WARN_UNUSED_RESULT ; <nl> MaybeHandle < JSArrayBufferView > ReadJSArrayBufferView ( <nl> Handle < JSArrayBuffer > buffer ) WARN_UNUSED_RESULT ; <nl> + MaybeHandle < JSObject > ReadWasmModule ( ) WARN_UNUSED_RESULT ; <nl> MaybeHandle < JSObject > ReadHostObject ( ) WARN_UNUSED_RESULT ; <nl> <nl> / * <nl> mmm a / test / unittests / value - serializer - unittest . cc <nl> ppp b / test / unittests / value - serializer - unittest . cc <nl> TEST_F ( ValueSerializerTestWithHostObject , RoundTripSameObject ) { <nl> } ) ; <nl> } <nl> <nl> + / / It ' s expected that WebAssembly has more exhaustive tests elsewhere ; this <nl> + / / mostly checks that the logic to embed it in structured clone serialization <nl> + / / works correctly . <nl> + <nl> + class ValueSerializerTestWithWasm : public ValueSerializerTest { <nl> + protected : <nl> + static void SetUpTestCase ( ) { <nl> + g_saved_flag = i : : FLAG_expose_wasm ; <nl> + i : : FLAG_expose_wasm = true ; <nl> + ValueSerializerTest : : SetUpTestCase ( ) ; <nl> + } <nl> + <nl> + static void TearDownTestCase ( ) { <nl> + ValueSerializerTest : : TearDownTestCase ( ) ; <nl> + i : : FLAG_expose_wasm = g_saved_flag ; <nl> + g_saved_flag = false ; <nl> + } <nl> + <nl> + private : <nl> + static bool g_saved_flag ; <nl> + } ; <nl> + <nl> + bool ValueSerializerTestWithWasm : : g_saved_flag = false ; <nl> + <nl> + / / A simple module which exports an " increment " function . <nl> + / / Copied from test / mjsunit / wasm / incrementer . wasm . <nl> + const unsigned char kIncrementerWasm [ ] = { <nl> + 0x00 , 0x61 , 0x73 , 0x6d , 0x0d , 0x00 , 0x00 , 0x00 , 0x01 , 0x06 , 0x01 , 0x60 , <nl> + 0x01 , 0x7f , 0x01 , 0x7f , 0x03 , 0x02 , 0x01 , 0x00 , 0x07 , 0x0d , 0x01 , 0x09 , <nl> + 0x69 , 0x6e , 0x63 , 0x72 , 0x65 , 0x6d , 0x65 , 0x6e , 0x74 , 0x00 , 0x00 , 0x0a , <nl> + 0x08 , 0x01 , 0x06 , 0x00 , 0x20 , 0x00 , 0x41 , 0x01 , 0x6a } ; <nl> + <nl> + TEST_F ( ValueSerializerTestWithWasm , RoundTripWasmModule ) { <nl> + RoundTripTest ( <nl> + [ this ] ( ) { <nl> + return WasmCompiledModule : : DeserializeOrCompile ( <nl> + isolate ( ) , { nullptr , 0 } , <nl> + { kIncrementerWasm , sizeof ( kIncrementerWasm ) } ) <nl> + . ToLocalChecked ( ) ; <nl> + } , <nl> + [ this ] ( Local < Value > value ) { <nl> + ASSERT_TRUE ( value - > IsWebAssemblyCompiledModule ( ) ) ; <nl> + EXPECT_TRUE ( EvaluateScriptForResultBool ( <nl> + " new WebAssembly . Instance ( result ) . exports . increment ( 8 ) = = = 9 " ) ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + / / As produced around Chrome 56 . <nl> + const unsigned char kSerializedIncrementerWasm [ ] = { <nl> + 0xff , 0x09 , 0x3f , 0x00 , 0x57 , 0x79 , 0x2d , 0x00 , 0x61 , 0x73 , 0x6d , 0x0d , <nl> + 0x00 , 0x00 , 0x00 , 0x01 , 0x06 , 0x01 , 0x60 , 0x01 , 0x7f , 0x01 , 0x7f , 0x03 , <nl> + 0x02 , 0x01 , 0x00 , 0x07 , 0x0d , 0x01 , 0x09 , 0x69 , 0x6e , 0x63 , 0x72 , 0x65 , <nl> + 0x6d , 0x65 , 0x6e , 0x74 , 0x00 , 0x00 , 0x0a , 0x08 , 0x01 , 0x06 , 0x00 , 0x20 , <nl> + 0x00 , 0x41 , 0x01 , 0x6a , 0xf8 , 0x04 , 0xa1 , 0x06 , 0xde , 0xc0 , 0xc6 , 0x44 , <nl> + 0x3c , 0x29 , 0x00 , 0x00 , 0x00 , 0x00 , 0x1f , 0x02 , 0x00 , 0x00 , 0x81 , 0x4e , <nl> + 0xce , 0x7c , 0x05 , 0x00 , 0x00 , 0x00 , 0x02 , 0x00 , 0x00 , 0x00 , 0x30 , 0x02 , <nl> + 0x00 , 0x00 , 0xb0 , 0x25 , 0x30 , 0xe3 , 0xf2 , 0xdb , 0x2e , 0x48 , 0x00 , 0x00 , <nl> + 0x00 , 0x80 , 0xe8 , 0x00 , 0x00 , 0x80 , 0xe0 , 0x01 , 0x00 , 0x80 , 0x00 , 0x00 , <nl> + 0x00 , 0x80 , 0x00 , 0x00 , 0x00 , 0x80 , 0x07 , 0x08 , 0x00 , 0x00 , 0x09 , 0x04 , <nl> + 0x10 , 0x02 , 0x00 , 0x00 , 0x00 , 0x00 , 0x01 , 0x3c , 0x8c , 0xc0 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x0d , 0x00 , 0x00 , 0x00 , 0x01 , 0x10 , 0x8c , 0xc0 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x02 , 0x00 , 0x00 , 0x00 , 0x02 , 0x70 , 0x94 , 0x01 , 0x0c , 0x8b , <nl> + 0xc1 , 0x00 , 0x00 , 0x00 , 0x00 , 0x02 , 0x00 , 0x00 , 0x00 , 0x25 , 0xdc , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x9e , 0x01 , 0x10 , 0x8c , 0xc0 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x02 , 0x00 , 0x00 , 0x00 , 0x84 , 0xc0 , 0x00 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x05 , 0x7d , 0x01 , 0x1a , 0xe1 , 0x02 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x11 , 0x23 , 0x88 , 0x42 , 0x32 , 0x03 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x63 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x3e , 0x00 , 0x00 , 0x00 , 0x04 , 0x00 , <nl> + 0x00 , 0x02 , 0xa1 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0xff , 0xff , <nl> + 0xff , 0xff , 0x00 , 0x00 , 0x00 , 0x00 , 0x49 , 0x3b , 0xa5 , 0x60 , 0x0c , 0x00 , <nl> + 0x00 , 0x0f , 0x86 , 0x04 , 0x00 , 0x00 , 0x00 , 0x83 , 0xc0 , 0x01 , 0xc3 , 0x55 , <nl> + 0x48 , 0x89 , 0xe5 , 0x49 , 0xba , 0x00 , 0x00 , 0x00 , 0x00 , 0x06 , 0x00 , 0x00 , <nl> + 0x00 , 0x41 , 0x52 , 0x48 , 0x83 , 0xec , 0x08 , 0x48 , 0x89 , 0x45 , 0xf0 , 0x48 , <nl> + 0xbb , 0xb0 , 0x67 , 0xc6 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x33 , 0xc0 , 0x48 , <nl> + 0xbe , 0xe1 , 0x57 , 0x81 , 0x85 , 0xf6 , 0x14 , 0x00 , 0x00 , 0xe8 , 0xfc , 0x3c , <nl> + 0xea , 0xff , 0x48 , 0x8b , 0x45 , 0xf0 , 0x48 , 0x8b , 0xe5 , 0x5d , 0xeb , 0xbf , <nl> + 0x66 , 0x90 , 0x01 , 0x00 , 0x00 , 0x00 , 0x03 , 0x00 , 0x00 , 0x00 , 0x44 , 0x00 , <nl> + 0x00 , 0x00 , 0xff , 0xff , 0xff , 0x0f , 0xff , 0xff , 0x00 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x0f , 0x20 , 0x84 , 0x0f , 0x7d , 0x01 , 0x0d , 0x00 , 0x0f , 0x04 , <nl> + 0x6d , 0x08 , 0x0f , 0xf0 , 0x02 , 0x80 , 0x94 , 0x01 , 0x0c , 0x8b , 0xc1 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x03 , 0x00 , 0x00 , 0x00 , 0xed , 0xa9 , 0x2d , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x9e , 0xe0 , 0x38 , 0x1a , 0x61 , 0x03 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x11 , 0x23 , 0x88 , 0x42 , 0x32 , 0x03 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x9a , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x4e , 0x00 , 0x00 , 0x00 , 0x04 , 0x00 , 0x00 , <nl> + 0x02 , 0xf9 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0xff , 0xff , 0xff , <nl> + 0xff , 0x00 , 0x00 , 0x00 , 0x00 , 0x55 , 0x48 , 0x89 , 0xe5 , 0x56 , 0x57 , 0x48 , <nl> + 0x8b , 0x45 , 0x10 , 0xe8 , 0x11 , 0xed , 0xed , 0xff , 0xa8 , 0x01 , 0x0f , 0x85 , <nl> + 0x2d , 0x00 , 0x00 , 0x00 , 0x48 , 0xc1 , 0xe8 , 0x20 , 0xc5 , 0xf9 , 0x57 , 0xc0 , <nl> + 0xc5 , 0xfb , 0x2a , 0xc0 , 0xc4 , 0xe1 , 0xfb , 0x2c , 0xc0 , 0x48 , 0x83 , 0xf8 , <nl> + 0x01 , 0x0f , 0x80 , 0x34 , 0x00 , 0x00 , 0x00 , 0x8b , 0xc0 , 0xe8 , 0x27 , 0xfe , <nl> + 0xff , 0xff , 0x48 , 0xc1 , 0xe0 , 0x20 , 0x48 , 0x8b , 0xe5 , 0x5d , 0xc2 , 0x10 , <nl> + 0x00 , 0x49 , 0x39 , 0x45 , 0xa0 , 0x0f , 0x84 , 0x07 , 0x00 , 0x00 , 0x00 , 0xc5 , <nl> + 0xfb , 0x10 , 0x40 , 0x07 , 0xeb , 0xce , 0x49 , 0xba , 0x00 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0xf8 , 0x7f , 0xc4 , 0xc1 , 0xf9 , 0x6e , 0xc2 , 0xeb , 0xbd , 0x48 , <nl> + 0x83 , 0xec , 0x08 , 0xc5 , 0xfb , 0x11 , 0x04 , 0x24 , 0xe8 , 0xcc , 0xfe , 0xff , <nl> + 0xff , 0x48 , 0x83 , 0xc4 , 0x08 , 0xeb , 0xb8 , 0x66 , 0x90 , 0x02 , 0x00 , 0x00 , <nl> + 0x00 , 0x03 , 0x00 , 0x00 , 0x00 , 0x0f , 0x00 , 0x00 , 0x00 , 0xff , 0xff , 0xff , <nl> + 0x0f , 0x39 , 0x00 , 0x00 , 0x00 , 0xff , 0xff , 0xff , 0x0f , 0xff , 0xff , 0x00 , <nl> + 0xff , 0xff , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x0f , 0x20 , 0x84 , <nl> + 0x0f , 0xcc , 0x6e , 0x7d , 0x01 , 0x72 , 0x98 , 0x00 , 0x0f , 0xdc , 0x6d , 0x0c , <nl> + 0x0f , 0xb0 , 0x84 , 0x0d , 0x04 , 0x84 , 0xe3 , 0xc0 , 0x00 , 0x00 , 0x00 , 0x00 , <nl> + 0x00 , 0x00 , 0x00 , 0x00 , 0x84 , 0xe0 , 0x84 , 0x84 , 0x18 , 0x2f , 0x2f , 0x2f , <nl> + 0x2f , 0x2f } ; <nl> + <nl> + TEST_F ( ValueSerializerTestWithWasm , DecodeWasmModule ) { <nl> + std : : vector < uint8_t > raw ( <nl> + kSerializedIncrementerWasm , <nl> + kSerializedIncrementerWasm + sizeof ( kSerializedIncrementerWasm ) ) ; <nl> + DecodeTest ( raw , [ this ] ( Local < Value > value ) { <nl> + ASSERT_TRUE ( value - > IsWebAssemblyCompiledModule ( ) ) ; <nl> + EXPECT_TRUE ( EvaluateScriptForResultBool ( <nl> + " new WebAssembly . Instance ( result ) . exports . increment ( 8 ) = = = 9 " ) ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + / / As above , but with empty compiled data . Should work due to fallback to wire <nl> + / / data . <nl> + const unsigned char kSerializedIncrementerWasmWithInvalidCompiledData [ ] = { <nl> + 0xff , 0x09 , 0x3f , 0x00 , 0x57 , 0x79 , 0x2d , 0x00 , 0x61 , 0x73 , 0x6d , <nl> + 0x0d , 0x00 , 0x00 , 0x00 , 0x01 , 0x06 , 0x01 , 0x60 , 0x01 , 0x7f , 0x01 , <nl> + 0x7f , 0x03 , 0x02 , 0x01 , 0x00 , 0x07 , 0x0d , 0x01 , 0x09 , 0x69 , 0x6e , <nl> + 0x63 , 0x72 , 0x65 , 0x6d , 0x65 , 0x6e , 0x74 , 0x00 , 0x00 , 0x0a , 0x08 , <nl> + 0x01 , 0x06 , 0x00 , 0x20 , 0x00 , 0x41 , 0x01 , 0x6a , 0x00 } ; <nl> + <nl> + TEST_F ( ValueSerializerTestWithWasm , DecodeWasmModuleWithInvalidCompiledData ) { <nl> + std : : vector < uint8_t > raw ( <nl> + kSerializedIncrementerWasmWithInvalidCompiledData , <nl> + kSerializedIncrementerWasmWithInvalidCompiledData + <nl> + sizeof ( kSerializedIncrementerWasmWithInvalidCompiledData ) ) ; <nl> + DecodeTest ( raw , [ this ] ( Local < Value > value ) { <nl> + ASSERT_TRUE ( value - > IsWebAssemblyCompiledModule ( ) ) ; <nl> + EXPECT_TRUE ( EvaluateScriptForResultBool ( <nl> + " new WebAssembly . Instance ( result ) . exports . increment ( 8 ) = = = 9 " ) ) ; <nl> + } ) ; <nl> + } <nl> + <nl> + / / As above , but also with empty wire data . Should fail . <nl> + const unsigned char kSerializedIncrementerWasmInvalid [ ] = { <nl> + 0xff , 0x09 , 0x3f , 0x00 , 0x57 , 0x79 , 0x00 , 0x00 } ; <nl> + <nl> + TEST_F ( ValueSerializerTestWithWasm , <nl> + DecodeWasmModuleWithInvalidCompiledAndWireData ) { <nl> + std : : vector < uint8_t > raw ( kSerializedIncrementerWasmInvalid , <nl> + kSerializedIncrementerWasmInvalid + <nl> + sizeof ( kSerializedIncrementerWasmInvalid ) ) ; <nl> + InvalidDecodeTest ( raw ) ; <nl> + } <nl> + <nl> + TEST_F ( ValueSerializerTestWithWasm , DecodeWasmModuleWithInvalidDataLength ) { <nl> + InvalidDecodeTest ( { 0xff , 0x09 , 0x3f , 0x00 , 0x57 , 0x79 , 0x7f , 0x00 } ) ; <nl> + InvalidDecodeTest ( { 0xff , 0x09 , 0x3f , 0x00 , 0x57 , 0x79 , 0x00 , 0x7f } ) ; <nl> + } <nl> + <nl> } / / namespace <nl> } / / namespace v8 <nl>
Support structured clone of compiled WebAssembly modules .
v8/v8
39a1c9678e3e925f854b67e5e2ca61ac745824a8
2016-11-04T15:35:55Z
mmm a / test / perftest / rapidjsontest . cpp <nl> ppp b / test / perftest / rapidjsontest . cpp <nl> TEST_F ( RapidJson , SIMD_SUFFIX ( ReaderParse_DummyHandler_ValidateEncoding ) ) { <nl> } <nl> <nl> TEST_F ( RapidJson , SIMD_SUFFIX ( DocumentParseInsitu_MemoryPoolAllocator ) ) { <nl> - / / const size_t userBufferSize = 128 * 1024 ; <nl> - / / char * userBuffer = ( char * ) malloc ( userBufferSize ) ; <nl> - <nl> for ( size_t i = 0 ; i < kTrialCount ; i + + ) { <nl> memcpy ( temp_ , json_ , length_ + 1 ) ; <nl> - / / MemoryPoolAllocator < > allocator ( userBuffer , userBufferSize ) ; <nl> - / / Document doc ( & allocator ) ; <nl> Document doc ; <nl> doc . ParseInsitu ( temp_ ) ; <nl> ASSERT_TRUE ( doc . IsObject ( ) ) ; <nl> - / / if ( i = = 0 ) { <nl> - / / size_t size = doc . GetAllocator ( ) . Size ( ) ; <nl> - / / size_t capacity = doc . GetAllocator ( ) . Capacity ( ) ; <nl> - / / size_t stack_capacity = doc . GetStackCapacity ( ) ; <nl> - / / size_t actual = size - stack_capacity ; <nl> - / / std : : cout < < " Size : " < < size < < " Capacity : " < < capacity < < " Stack : " < < stack_capacity < < " Actual : " < < actual < < std : : endl ; <nl> - / / } <nl> } <nl> + } <nl> <nl> - / / free ( userBuffer ) ; <nl> + TEST_F ( RapidJson , SIMD_SUFFIX ( DocumentParseIterativeInsitu_MemoryPoolAllocator ) ) { <nl> + for ( size_t i = 0 ; i < kTrialCount ; i + + ) { <nl> + memcpy ( temp_ , json_ , length_ + 1 ) ; <nl> + Document doc ; <nl> + doc . ParseInsitu < kParseIterativeFlag > ( temp_ ) ; <nl> + ASSERT_TRUE ( doc . IsObject ( ) ) ; <nl> + } <nl> } <nl> <nl> TEST_F ( RapidJson , SIMD_SUFFIX ( DocumentParse_MemoryPoolAllocator ) ) { <nl> - / / const size_t userBufferSize = 128 * 1024 ; <nl> - / / char * userBuffer = ( char * ) malloc ( userBufferSize ) ; <nl> - <nl> for ( size_t i = 0 ; i < kTrialCount ; i + + ) { <nl> - / / MemoryPoolAllocator < > allocator ( userBuffer , userBufferSize ) ; <nl> - / / Document doc ( & allocator ) ; <nl> Document doc ; <nl> doc . Parse ( json_ ) ; <nl> ASSERT_TRUE ( doc . IsObject ( ) ) ; <nl> - / / if ( i = = 0 ) { <nl> - / / size_t size = doc . GetAllocator ( ) . Size ( ) ; <nl> - / / size_t capacity = doc . GetAllocator ( ) . Capacity ( ) ; <nl> - / / size_t stack_capacity = doc . GetStackCapacity ( ) ; <nl> - / / size_t actual = size - stack_capacity ; <nl> - / / std : : cout < < " Size : " < < size < < " Capacity : " < < capacity < < " Stack : " < < stack_capacity < < " Actual : " < < actual < < std : : endl ; <nl> - / / } <nl> } <nl> + } <nl> <nl> - / / free ( userBuffer ) ; <nl> + TEST_F ( RapidJson , SIMD_SUFFIX ( DocumentParseIterative_MemoryPoolAllocator ) ) { <nl> + for ( size_t i = 0 ; i < kTrialCount ; i + + ) { <nl> + Document doc ; <nl> + doc . Parse < kParseIterativeFlag > ( json_ ) ; <nl> + ASSERT_TRUE ( doc . IsObject ( ) ) ; <nl> + } <nl> } <nl> <nl> TEST_F ( RapidJson , SIMD_SUFFIX ( DocumentParse_CrtAllocator ) ) { <nl>
Add perf test cases for document using iterative parsing
Tencent/rapidjson
8081e2a2c85eb78a8af52dd34c3a46c4cac51ad8
2014-07-26T16:03:37Z
mmm a / test / api - digester / Outputs / cake . json <nl> ppp b / test / api - digester / Outputs / cake . json <nl> <nl> " printedName " : " C1 " <nl> } <nl> ] <nl> - } , <nl> - { <nl> - " kind " : " TypeNominal " , <nl> - " name " : " C1 " , <nl> - " printedName " : " C1 " <nl> } <nl> ] <nl> } , <nl> <nl> " name " : " Void " , <nl> " printedName " : " ( ) " <nl> } , <nl> - { <nl> - " kind " : " TypeNominal " , <nl> - " name " : " C1 " , <nl> - " printedName " : " C1 " <nl> - } , <nl> { <nl> " kind " : " TypeNominal " , <nl> " name " : " Optional " , <nl> <nl> " location " : " " , <nl> " moduleName " : " cake " , <nl> " children " : [ <nl> - { <nl> - " kind " : " TypeNominal " , <nl> - " name " : " C1 " , <nl> - " printedName " : " C1 " <nl> - } , <nl> { <nl> " kind " : " TypeNominal " , <nl> " name " : " C1 " , <nl> <nl> " name " : " Void " , <nl> " printedName " : " ( ) " <nl> } , <nl> - { <nl> - " kind " : " TypeNominal " , <nl> - " name " : " C1 " , <nl> - " printedName " : " C1 " <nl> - } , <nl> { <nl> " kind " : " TypeNominal " , <nl> " name " : " C1 " , <nl> mmm a / test / api - digester / source - stability . swift . expected <nl> ppp b / test / api - digester / source - stability . swift . expected <nl> Func Dictionary . removeValue ( forKey : ) has been removed <nl> Func Dictionary . updateValue ( _ : forKey : ) has been removed <nl> <nl> / * FIXME : Bogus * / <nl> + Var BidirectionalCollection . indices has declared type change from DefaultBidirectionalIndices < Self > to Self . Indices <nl> Var Dictionary . endIndex has declared type change from DictionaryIndex < Key , Value > to Dictionary < Key , Value > . Index <nl> Var Dictionary . startIndex has declared type change from DictionaryIndex < Key , Value > to Dictionary < Key , Value > . Index <nl> + Var RandomAccessCollection . indices has declared type change from DefaultRandomAccessIndices < Self > to Self . Indices <nl> Var Set . endIndex has declared type change from SetIndex < Element > to Set < Element > . Index <nl> Var Set . startIndex has declared type change from SetIndex < Element > to Set < Element > . Index <nl> Constructor AnyIterator . init ( _ : ) has parameter 0 type change from ( ) - > Element ? to ( ) - > AnyIterator . Element ? <nl> mmm a / tools / swift - api - digester / swift - api - digester . cpp <nl> ppp b / tools / swift - api - digester / swift - api - digester . cpp <nl> static SDKNode * constructTypeNode ( SDKContext & Ctx , Type T ) { <nl> / / We sometimes skip the first parameter because it can be metatype of dynamic <nl> / / this if the function is a member function . <nl> static SDKNode * constructFunctionNode ( SDKContext & Ctx , FuncDecl * FD , <nl> - SDKNodeKind Kind , bool SkipFirst ) { <nl> + SDKNodeKind Kind ) { <nl> auto Func = SDKNodeInitInfo ( Ctx , FD ) . createSDKNode ( Kind ) ; <nl> Func - > addChild ( constructTypeNode ( Ctx , FD - > getResultInterfaceType ( ) ) ) ; <nl> for ( auto * paramList : FD - > getParameterLists ( ) ) { <nl> - for ( auto param : * paramList ) <nl> - Func - > addChild ( constructTypeNode ( Ctx , param - > getInterfaceType ( ) ) ) ; <nl> - } <nl> - if ( SkipFirst ) { <nl> - Func - > removeChild ( Func - > getChildBegin ( ) + 1 ) ; <nl> + for ( auto param : * paramList ) { <nl> + if ( ! param - > isSelfParameter ( ) ) <nl> + Func - > addChild ( constructTypeNode ( Ctx , param - > getInterfaceType ( ) ) ) ; <nl> + } <nl> } <nl> return Func ; <nl> } <nl> static SDKNode * constructVarNode ( SDKContext & Ctx , ValueDecl * VD ) { <nl> Var - > addChild ( constructTypeNode ( Ctx , VD - > getInterfaceType ( ) ) ) ; <nl> if ( auto VAD = dyn_cast < AbstractStorageDecl > ( VD ) ) { <nl> if ( auto Getter = VAD - > getGetter ( ) ) <nl> - Var - > addChild ( constructFunctionNode ( Ctx , Getter , SDKNodeKind : : Getter , false ) ) ; <nl> + Var - > addChild ( constructFunctionNode ( Ctx , Getter , SDKNodeKind : : Getter ) ) ; <nl> if ( auto Setter = VAD - > getSetter ( ) ) <nl> - Var - > addChild ( constructFunctionNode ( Ctx , Setter , SDKNodeKind : : Setter , false ) ) ; <nl> + Var - > addChild ( constructFunctionNode ( Ctx , Setter , SDKNodeKind : : Setter ) ) ; <nl> } <nl> return Var ; <nl> } <nl> static void addMembersToRoot ( SDKContext & Ctx , SDKNode * Root , <nl> if ( shouldIgnore ( Member ) ) <nl> continue ; <nl> if ( auto Func = dyn_cast < FuncDecl > ( Member ) ) { <nl> - Root - > addChild ( constructFunctionNode ( Ctx , Func , SDKNodeKind : : Function , true ) ) ; <nl> + Root - > addChild ( constructFunctionNode ( Ctx , Func , SDKNodeKind : : Function ) ) ; <nl> } else if ( auto CD = dyn_cast < ConstructorDecl > ( Member ) ) { <nl> Root - > addChild ( constructInitNode ( Ctx , CD ) ) ; <nl> } else if ( auto VD = dyn_cast < VarDecl > ( Member ) ) { <nl> class SwiftDeclCollector : public VisibleDeclConsumer { <nl> return ; <nl> <nl> if ( auto FD = dyn_cast < FuncDecl > ( VD ) ) { <nl> - RootNode - > addChild ( constructFunctionNode ( Ctx , FD , SDKNodeKind : : Function , false ) ) ; <nl> + RootNode - > addChild ( constructFunctionNode ( Ctx , FD , SDKNodeKind : : Function ) ) ; <nl> } else if ( auto NTD = dyn_cast < NominalTypeDecl > ( VD ) ) { <nl> RootNode - > addChild ( constructTypeDeclNode ( Ctx , NTD ) ) ; <nl> } <nl>
Swift - api - digester : check self - parameter explicitly instead of using its context . NFC ( )
apple/swift
7ccef06aa84725c1d10a7c51c76d162ba3d5f0d1
2017-04-10T20:53:48Z
mmm a / docs / development / coding - style . md <nl> ppp b / docs / development / coding - style . md <nl> etc . <nl> # # JavaScript <nl> <nl> * Write [ standard ] ( http : / / npm . im / standard ) JavaScript style . <nl> - * Files should * * NOT * * end with new line , because we want to match Google ' s <nl> - styles . <nl> * File names should be concatenated with ` - ` instead of ` _ ` , e . g . <nl> ` file - name . js ` rather than ` file_name . js ` , because in <nl> [ github / atom ] ( https : / / github . com / github / atom ) module names are usually in <nl>
source files DO have newlines at the end
electron/electron
515e25b749d498832b9b8aadca7666de7228c6d8
2016-08-17T04:24:53Z
mmm a / scene / gui / control . cpp <nl> ppp b / scene / gui / control . cpp <nl> void Control : : _size_changed ( ) { <nl> <nl> Size2 minimum_size = get_combined_minimum_size ( ) ; <nl> <nl> - if ( data . h_grow = = GROW_DIRECTION_BEGIN ) { <nl> - if ( minimum_size . width > new_size_cache . width ) { <nl> - new_pos_cache . x = new_pos_cache . x + new_size_cache . width - minimum_size . width ; <nl> - new_size_cache . width = minimum_size . width ; <nl> + if ( minimum_size . width > new_size_cache . width ) { <nl> + if ( data . h_grow = = GROW_DIRECTION_BEGIN ) { <nl> + new_pos_cache . x + = new_size_cache . width - minimum_size . width ; <nl> + } else if ( data . h_grow = = GROW_DIRECTION_BOTH ) { <nl> + new_pos_cache . x + = 0 . 5 * ( new_size_cache . width - minimum_size . width ) ; <nl> } <nl> - } else { <nl> - new_size_cache . width = MAX ( minimum_size . width , new_size_cache . width ) ; <nl> + <nl> + new_size_cache . width = minimum_size . width ; <nl> } <nl> <nl> - if ( data . v_grow = = GROW_DIRECTION_BEGIN ) { <nl> - if ( minimum_size . height > new_size_cache . height ) { <nl> - new_pos_cache . y = new_pos_cache . y + new_size_cache . height - minimum_size . height ; <nl> - new_size_cache . height = minimum_size . height ; <nl> + if ( minimum_size . height > new_size_cache . height ) { <nl> + if ( data . v_grow = = GROW_DIRECTION_BEGIN ) { <nl> + new_pos_cache . y + = new_size_cache . height - minimum_size . height ; <nl> + } else if ( data . v_grow = = GROW_DIRECTION_BOTH ) { <nl> + new_pos_cache . y + = 0 . 5 * ( new_size_cache . height - minimum_size . height ) ; <nl> } <nl> - } else { <nl> - new_size_cache . height = MAX ( minimum_size . height , new_size_cache . height ) ; <nl> + <nl> + new_size_cache . height = minimum_size . height ; <nl> } <nl> <nl> if ( get_viewport ( ) - > is_snap_controls_to_pixels_enabled ( ) ) { <nl> void Control : : _bind_methods ( ) { <nl> ADD_PROPERTYINZ ( PropertyInfo ( Variant : : INT , " margin_bottom " , PROPERTY_HINT_RANGE , " - 4096 , 4096 " ) , " set_margin " , " get_margin " , MARGIN_BOTTOM ) ; <nl> <nl> ADD_GROUP ( " Grow Direction " , " grow_ " ) ; <nl> - ADD_PROPERTYNO ( PropertyInfo ( Variant : : INT , " grow_horizontal " , PROPERTY_HINT_ENUM , " Begin , End " ) , " set_h_grow_direction " , " get_h_grow_direction " ) ; <nl> - ADD_PROPERTYNO ( PropertyInfo ( Variant : : INT , " grow_vertical " , PROPERTY_HINT_ENUM , " Begin , End " ) , " set_v_grow_direction " , " get_v_grow_direction " ) ; <nl> + ADD_PROPERTYNO ( PropertyInfo ( Variant : : INT , " grow_horizontal " , PROPERTY_HINT_ENUM , " Begin , End , Both " ) , " set_h_grow_direction " , " get_h_grow_direction " ) ; <nl> + ADD_PROPERTYNO ( PropertyInfo ( Variant : : INT , " grow_vertical " , PROPERTY_HINT_ENUM , " Begin , End , Both " ) , " set_v_grow_direction " , " get_v_grow_direction " ) ; <nl> <nl> ADD_GROUP ( " Rect " , " rect_ " ) ; <nl> ADD_PROPERTYNZ ( PropertyInfo ( Variant : : VECTOR2 , " rect_position " , PROPERTY_HINT_NONE , " " , PROPERTY_USAGE_EDITOR ) , " set_position " , " get_position " ) ; <nl> void Control : : _bind_methods ( ) { <nl> <nl> BIND_ENUM_CONSTANT ( GROW_DIRECTION_BEGIN ) ; <nl> BIND_ENUM_CONSTANT ( GROW_DIRECTION_END ) ; <nl> + BIND_ENUM_CONSTANT ( GROW_DIRECTION_BOTH ) ; <nl> <nl> BIND_ENUM_CONSTANT ( ANCHOR_BEGIN ) ; <nl> BIND_ENUM_CONSTANT ( ANCHOR_END ) ; <nl> mmm a / scene / gui / control . h <nl> ppp b / scene / gui / control . h <nl> class Control : public CanvasItem { <nl> <nl> enum GrowDirection { <nl> GROW_DIRECTION_BEGIN , <nl> - GROW_DIRECTION_END <nl> + GROW_DIRECTION_END , <nl> + GROW_DIRECTION_BOTH <nl> } ; <nl> <nl> enum FocusMode { <nl>
Implements by adding GROW_DIRECTION_BOTH which allows a control to grow from its center .
godotengine/godot
4ef11eb3ed4c9a00ca64c242e61ff82de1e151ea
2018-02-12T06:39:18Z